在反序列化期间如何执行 python 代码?

How is it possible to execute python code during deserialization?

我正在阅读关于在持久实例的上下文中进行酸洗的内容,运行 在这个片段中:

Pickle files can be hacked. If you receive a raw pickle file over the network, don't trust it! It could have malicious code in it, that would run arbitrary python when you try to de-pickle it. [1]

我的理解是 pickling 将数据结构转换为字节数组,pickle 库还包含获取 pickle 字节数组并从中重建 python 实例的方法。

我测试了一些代码,看看是否简单地将代码放入 class 或 init 方法中 运行 它:

import pickle

class A:
    print('class')
    def __init__(self):
        print('instance')

a = A()

print('pickling...')
with open('/home/usrname/Desktop/pfile', 'wb') as pfile:
    pickle.dump(a, pfile, pickle.HIGHEST_PROTOCOL)

print('de-pickling...')
with open('/home/usrname/Desktop/pfile', 'rb') as pfile:
    a2 = pickle.load(pfile)

然而这只会产生

class
instance
pickling...
de-pickling...

表明 __ init__ 方法在实例未被 pickled 时实际上并没有得到 运行。所以我仍然很困惑你会如何在那个过程中编写代码运行。

这里写得真透彻:https://intoli.com/blog/dangerous-pickles/

据我了解,这与泡菜机 (PM) 和 运行 解释泡菜的方式有关。您可以制作一个 pickle 文件,使其使用 eval() 提供的语句进行评估。