deserialize-untrusted-data

Try in Playground
python-securitySecurityCritical

0

No tags

CWE-502

Do not deserialize untrusted data. Make sure you use alternatives to check that the data can be deserialized safely. There is no workaround around this: unless you really trust the data source, it's better to use another way to exchange data, such as an API or other protocols such as protobuf or thrift.

Read More

  • Unsafe Deserialization in Python (CWE-502)

  • CWE-502: Deserialization of Untrusted Data

Ast Rule: function call


deserialize-untrusted-data

How to write a rule
const MODULES_FUNCTIONS_TO_AVOID = {
  "pickle": ["loads", "load", "Unpickler"],
  "shelve": ["open"],
  "marshal": ["load", "loads"],
  "jsonpickled": ["decode"],
  "pandas": ["read_pickle"]
}


function visit(node, filename, code){
  if(!node || !node.functionName || !node.moduleOrObject || !node.context) {
    return;
  }
  
  if(filename.includes("_test.py") || filename.startsWith("test_")) {
    return;
  }

  const module = node.moduleOrObject.value;
  const func = node.functionName.value;
  
  if(MODULES_FUNCTIONS_TO_AVOID[module]) {
    const allPackages = node.context.imports.filter(r => r.packages).flatMap(i => i.packages.map(p => p.name.str));
    const useModule = allPackages.filter(i => i === module).length > 0;
  	if (!useModule){
    	return;
  	}
    
    const functions = MODULES_FUNCTIONS_TO_AVOID[module];
    
    if (functions.includes(func)) {
      const error = buildError(node.start.line, node.start.col, node.end.line, node.end.col, `${module}.${func} is not safe for deserializing unstrusted data`, "CRITICAL", "SECURITY");
    	addError(error);
    }
  }
}

pickle_test.py

Expected test result: no error

import pickle

data = pickle.loads(data)

no_import.py

Expected test result: no error

data = pickle.loads(data)

pickle-loads.py

Expected test result: has error

import pickle

data = pickle.loads(data)
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Explore
  • Cookbooks
  • Playground
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.