【发布时间】:2022-11-04 00:14:39
【问题描述】:
Python 的 pickle 模块包含一个关于攻击向量的warning,可以通过使用 hmac 散列验证来缓解。为了验证,可以在酸洗后对对象进行哈希处理,并在上传到单独的笔记本并重新酸洗以进行 hmac 检查后进行比较。
部分挑战在于,当酸洗时,比如包含函数地址值的字典,这些地址在笔记本之间可能不持久。因此,为了使用 hmac 进行验证,需要比较 pickle 字典的哈希,这意味着在第二个笔记本中,需要在使用 pickle 反序列化之前检查 hmac 哈希。
是否可以在不反序列化的情况下上传腌制对象?
import pickle
import hmac, hashlib
def function():
return True
dictionary = \
{'function' : function}
pickled_dictionary = \
pickle.dumps(dictionary)
secret_key = '1234'
hmaced_dictionary = \
hmac.new(secret_key.encode(),
pickled_dictionary,
hashlib.sha256
).hexdigest()
with open('filename.pickle', 'wb') as handle:
pickle.dump(dictionary, handle, protocol=pickle.HIGHEST_PROTOCOL)
#________________
#now in seperate notebook we want to validate the dictionary contents
import pickle
import hmac, hashlib
import pickle
with open('filename.pickle', 'rb') as handle:
dictionary_upload = pickle.load(handle)
pickled_dicitonary_upload = \
pickle.dumps(dictionary_upload)
hmaced_dictionary_upload = \
hmac.new(secret_key.encode(), pickled_dicitonary_upload, hashlib.sha256).hexdigest()
#unfortunately we can't validate with hmac
#since the functions will have a diferent memory address in new notebook
hmaced_dictionary_upload != hmaced_dictionary
#________________
#we could circumvent this obstacle
#if possible to upload and hmac the pickled dictionary
#without deserializing
#couldn't figure out how to upload with pickle without deserializing
【问题讨论】: