Deserialization of Untrusted Data in pickle
Module
The Python pickle
module is a serialization module that can be used to
serialize and deserialize Python objects. Pickle is not secure because it can
be used to deserialize malicious code. For example, an attacker could create a
pickle file that contains malicious code and then trick a user into opening the
file. When the user opens the file, the malicious code would be executed.
Example
import pickle
def load_pickle_file(file_path):
with open(file_path, 'rb') as file:
data = file.read()
# WARNING: Unpickle data without proper validation
obj = pickle.loads(data)
return obj
# Example usage (assuming 'malicious.pickle' contains malicious code)
pickle_file = 'malicious.pickle'
loaded_object = load_pickle_file(pickle_file)
Remediation
Consider signing data with hmac if you need to ensure that pickle data has not been tampered with.
Alternatively if you need to serialize sensitive data, you could use a secure serialization format, such as JSON or XML. These formats are designed to be secure and cannot be used to execute malicious code.
False Positives
In the case of a false positive the rule can be suppressed. Simply add a
trailing or preceding comment line with either the rule ID (PY013
) or
rule category name (deserialization_of_untrusted_data
).
- Using rule ID
- Using category name
import pickle
def load_pickle_file(file_path):
with open(file_path, 'rb') as file:
data = file.read()
# WARNING: Unpickle data without proper validation
# suppress: PY013
obj = pickle.loads(data)
return obj
# Example usage (assuming 'malicious.pickle' contains malicious code)
pickle_file = 'malicious.pickle'
loaded_object = load_pickle_file(pickle_file)
import pickle
def load_pickle_file(file_path):
with open(file_path, 'rb') as file:
data = file.read()
# WARNING: Unpickle data without proper validation
# suppress: deserialization_of_untrusted_data
obj = pickle.loads(data)
return obj
# Example usage (assuming 'malicious.pickle' contains malicious code)
pickle_file = 'malicious.pickle'
loaded_object = load_pickle_file(pickle_file)