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"],
	"marshal": ["load", "loads"]
}


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);
    }
  }
}

marshal.py

Expected test result: has error

import marshal
person = {"name":"xyz", "age":22, "marks":[45,56,78]}
data = marshal.dumps(person)
obj = marshal.loads(data)

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

Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Playground
  • Snippets
  • Cookbooks
Legal
  • Security
  • Privacy Policy
  • Code Privacy
  • Terms of Service
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.