Description
Deserializing attacker-controlled data can execute arbitrary code or change application behavior. This often occurs when an application reconstructs serialized objects received over a network.
Potential impact
- Code execution: Malicious data may execute code and compromise the system.
- Data tampering: An attacker may alter application data.
- Information disclosure: Sensitive information may be exposed.
Remediation
- Do not use
pickleor loaders that construct arbitrary objects on untrusted input. - Verify the data's integrity and trustworthiness before deserialization.
- Use parsers such as
jsonoryaml.safe_loadthat do not construct arbitrary objects, and validate input size and structure.
Examples
pickle / JSON
Before
python
# Unsafe pickle deserialization
import pickle
def unsafe_loads(data):
return pickle.loads(data)
After
python
# JSON deserialization
import json
def safe_loads(data):
return json.loads(data)
Explanation:
- Before: A malicious pickle payload can execute code during deserialization.
- After: JSON avoids constructing arbitrary Python objects. Input size and structure still need validation.
YAML
Before
python
# Unsafe YAML deserialization
import yaml
def unsafe_load(data):
return yaml.load(data, Loader=yaml.Loader)
After
python
# Safe YAML deserialization
import yaml
def safe_load(data):
return yaml.safe_load(data)
Explanation:
- Before:
yaml.loadwith the illustrated loader can execute code from a malicious payload. - After:
yaml.safe_loadprevents arbitrary Python object construction. Input size and structure still need validation.