Unsafe Python Functions

The stdlib and ecosystem APIs that turn attacker-controlled data into code, commands, object graphs or filesystem writes. They are the sink list for any Python code review.

How it works

Python’s dynamism means many “parse” or “load” APIs are really “execute” APIs. Bugs come in three shapes:

  • Direct sinks: eval, exec, os.system, pickle.loads, yaml.load. These are easy to grep and still ship.
  • Indirect evaluation: a library calls eval() or an object factory for you, for example Pydantic model_rebuild() on generated annotations, or Hydra instantiate() on model metadata. The dangerous call isn’t in the app’s code.
  • Unsafe defaults: stdlib XML parsers, tarfile.extractall(), tempfile.mktemp(), assert. These are “safe” until a hostile input or python -O arrives.

Sink reference

SinkRiskSafer pattern
eval() / exec() / compile()Code injection. __import__('os').system(...) works as an expression.ast.literal_eval() for literals; otherwise don’t evaluate input
os.system, os.popen, subprocess.*(..., shell=True)Command injection via ;, \|, $() in interpolated stringsArgument list with shell=False; shlex.quote() if a shell is unavoidable
pickle/cPickle/_pickle, dill, jsonpickle, shelve, marshalRCE via __reduce__JSON; see Python Pickle Deserialization
numpy.load(allow_pickle=True), torch.load()Pickle under the hoodallow_pickle=False, torch.load(weights_only=True), safetensors
yaml.load() (PyYAML < 5.1 default loader)!!python/object/apply:os.system [...], CVE-2017-18342yaml.safe_load()
str.format() / f-string-style templates over user templatesAttribute traversal from any passed object to __globals__, then secretsRestrict at Formatter.get_field(); PEP 750 t-strings for interpolation
hydra.utils.instantiate()_target_ accepts any callable, not just classesAllowlist _target_ and resolve and check before calling
xml.etree, xml.dom, xmlrpc; lxml default parserBillion laughs, XXE. lxml < 6.1 iterparse() and ETCompatXMLParser() default to resolve_entities=True and read local filesdefusedxml drop-in; lxml ≥ 6.1 or resolve_entities='internal'/False
tarfile.extractall()../ member names write outside the target directory (CVE-2007-4559, 15+ years old)Validate members before extraction
tempfile.mktemp()TOCTOU race on the returned nametempfile.mkstemp()
assert user.is_adminStripped under -O / PYTHONOPTIMIZEExplicit if/raise
== on secretsTiming oraclesecrets.compare_digest()
requests.*(verify=False)MitM; CVE-2024-35195 made a single verify=False stick for the whole SessionNever in production; pin if self-signed
path.startswith(base) as a jail check/data/uploads_secret passes a /data/uploads checkCompare path components, not string prefixes
jinja2.Environment(extensions=["jinja2.ext.do", ...]) on untrusted templates{% do %} evaluates arbitrary expressions; rendering is code executionjinja2.sandbox.SandboxedEnvironment, no do/debug extensions
*.pth in site-packagesLines starting with import run at every interpreter startAudit site-packages; hash-pinned installs

Command injection shape

cmd = 'ffmpeg -i "{}" out.mpg'.format(filename)
subprocess.call(cmd, shell=True)          # filename = '"; cat /etc/passwd #'
subprocess.run(["ffmpeg", "-i", filename, "out.mpg"])   # no shell

An argument list stops shell metacharacters but not option injection (- prefixed values). See Argument Injection.

Format-string attribute traversal

str.format resolves dotted and indexed fields against whatever objects the caller supplies. A template like {u.__class__.__bases__[0].__init__.__globals__[...]} walks from a harmless dict wrapper to module globals. A wrapper-level __getattr__ guard doesn’t stop it because the traversal happens inside Formatter.get_field(). Arize Phoenix’s applyChatTemplate GraphQL query (13.0.0 up to but not including 15.7.0 (CVE-2026-53998)) leaked os.environ and PHOENIX_SECRET this way, which gave JWT forgery and decryption of stored credentials. The levelup note argues f-strings “cannot be made safe” because interpolation is eager. PEP 750 t-strings keep the static parts and the values separate, so a SQL, HTML or shell consumer can escape the values.

Notable cases

  • datamodel-code-generator < 0.84.0 (CVE-2026-127208): a malicious JSON Schema x-python-type with a string ast.Constant in a subscript slice bypasses the AST validation. The embedded expression is then eval()’d during Pydantic v2 model_rebuild(), giving RCE on dev workstations and CI.
  • Hydra instantiate() in ML libraries: NeMo (CVE-2025-23304, fixed 2.3.2 with safe_instantiate), Uni2TS (CVE-2026-22584, allowlist fix) and FlexTok ran code from model metadata. Hydra later added a doc warning and a block-list, which Unit 42 notes doesn’t stop implicit imports.
  • PLY 3.11 (CVE-2025-56005, disputed): the undocumented yacc(picklefile=...) parameter calls pickle.load() on a caller-supplied path.
  • Ansible Vault (TALOS-2017-0305): yaml.load executing !!python/object/apply:os.system.
  • Langflow < 1.9.0 (CVE-2026-33873): executes LLM-generated Python during “validation”, so exec becomes reachable through model output.
  • yt ≤ 4.4.4 (CVE-2026-132751, CWE-95): SavedDataset._parse_parameter_file() passes the stored con_args HDF5 attribute to eval(), so loading a shared ytdata file runs code. Values read from files must be parsed, not evaluated. r3vpwnx
  • lxml GHSA-vfmq-68hx-4jfw: 5.0 changed the default to resolve_entities='internal' for the normal XML/HTML parsers but left iterparse() and ETCompatXMLParser() resolving external entities until 6.1. lxml advisory
  • BentoML GHSA-v959-cwq9-7hr6: unsandboxed Jinja2 with jinja2.ext.do rendered a Dockerfile template from an imported bento archive on the host. BentoML advisory
  • Microsoft agent-framework 1.26.1/1.26.2: a .pth hook ran a credential stealer on every interpreter start, with no import needed. agent-framework check
  • Requests: CVE-2023-32681 leaked Proxy-Authorization to the redirect destination (fixed 2.31.0).

Defenses

  • Ban the direct sinks in SAST (Bandit B102/B307 eval/exec, B301 pickle, B602 shell, yaml_load). See Python SAST Tools.
  • Treat any “load config / model / schema” path as an execution sink until you’ve read the library code. Look especially for factory callables (_target_, !!python/, __reduce__).
  • Use defusedxml, yaml.safe_load, json and safetensors by default. Archive extraction must validate every member path.
  • For templates, render with a sandboxed engine (see Jinja2 SSTI) or restrict field resolution. Never hand live objects to str.format over a user template.

Sources