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 Pydanticmodel_rebuild()on generated annotations, or Hydrainstantiate()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 orpython -Oarrives.
Sink reference
| Sink | Risk | Safer 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 strings | Argument list with shell=False; shlex.quote() if a shell is unavoidable |
pickle/cPickle/_pickle, dill, jsonpickle, shelve, marshal | RCE via __reduce__ | JSON; see Python Pickle Deserialization |
numpy.load(allow_pickle=True), torch.load() | Pickle under the hood | allow_pickle=False, torch.load(weights_only=True), safetensors |
yaml.load() (PyYAML < 5.1 default loader) | !!python/object/apply:os.system [...], CVE-2017-18342 | yaml.safe_load() |
str.format() / f-string-style templates over user templates | Attribute traversal from any passed object to __globals__, then secrets | Restrict at Formatter.get_field(); PEP 750 t-strings for interpolation |
hydra.utils.instantiate() | _target_ accepts any callable, not just classes | Allowlist _target_ and resolve and check before calling |
xml.etree, xml.dom, xmlrpc; lxml default parser | Billion laughs, XXE. lxml < 6.1 iterparse() and ETCompatXMLParser() default to resolve_entities=True and read local files | defusedxml 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 name | tempfile.mkstemp() |
assert user.is_admin | Stripped under -O / PYTHONOPTIMIZE | Explicit if/raise |
== on secrets | Timing oracle | secrets.compare_digest() |
requests.*(verify=False) | MitM; CVE-2024-35195 made a single verify=False stick for the whole Session | Never in production; pin if self-signed |
path.startswith(base) as a jail check | /data/uploads_secret passes a /data/uploads check | Compare path components, not string prefixes |
jinja2.Environment(extensions=["jinja2.ext.do", ...]) on untrusted templates | {% do %} evaluates arbitrary expressions; rendering is code execution | jinja2.sandbox.SandboxedEnvironment, no do/debug extensions |
*.pth in site-packages | Lines starting with import run at every interpreter start | Audit 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 shellAn 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-typewith a stringast.Constantin a subscript slice bypasses the AST validation. The embedded expression is theneval()’d during Pydantic v2model_rebuild(), giving RCE on dev workstations and CI. - Hydra
instantiate()in ML libraries: NeMo (CVE-2025-23304, fixed 2.3.2 withsafe_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 callspickle.load()on a caller-supplied path. - Ansible Vault (TALOS-2017-0305):
yaml.loadexecuting!!python/object/apply:os.system. - Langflow < 1.9.0 (CVE-2026-33873): executes LLM-generated Python during “validation”, so
execbecomes reachable through model output. - yt ≤ 4.4.4 (CVE-2026-132751, CWE-95):
SavedDataset._parse_parameter_file()passes the storedcon_argsHDF5 attribute toeval(), 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 leftiterparse()andETCompatXMLParser()resolving external entities until 6.1. lxml advisory - BentoML GHSA-v959-cwq9-7hr6: unsandboxed Jinja2 with
jinja2.ext.dorendered a Dockerfile template from an imported bento archive on the host. BentoML advisory - Microsoft agent-framework 1.26.1/1.26.2: a
.pthhook ran a credential stealer on every interpreter start, with no import needed. agent-framework check - Requests: CVE-2023-32681 leaked
Proxy-Authorizationto 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,jsonand 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.formatover a user template.
Related
- Python Security
- Python Sandbox Escapes
- Python SAST Tools
- Python AI and ML Framework Vulnerabilities
- Python Pickle Deserialization
- Code Injection
- Command Injection
- Argument Injection
- Insecure Deserialization
- XML External Entity Injection
Sources
- Code injection in Python: examples and prevention · original
- Command injection in Python: examples and prevention · original
- 10 common security gotchas in Python and how to avoid them · original
- Python Security Vulnerabilities: Top Issues (Aikido) · original
- Insecure Deserialization in Python (Semgrep) · original
- Python Just Got a New Kind of String (t-strings) · original
- Arize Phoenix: format string injection in applyChatTemplate · original
- datamodel-code-generator before 0.84.0 code injection · original
- RCE With Modern AI/ML Formats and Python Libraries · original
- CVE-2025-56005: PLY RCE Vulnerability · original
- CVE-2026-33873: Langflow Agentic Assistant RCE · original
- Directory Traversal in Flask-Admin · original
- Tandoor Recipes XXE via lxml and SSRF · original
- Arize Phoenix CVE-2026-53998 GraphQL format-string secrets leak · original
- Loading a Dataset Should Not Run Code (yt CVE-2026-132751) · original
- lxml GHSA-vfmq-68hx-4jfw: iterparse/ETCompatXMLParser XXE · original
- BentoML GHSA-v959-cwq9-7hr6: SSTI via unsandboxed Jinja2 · original
- Microsoft's agent-framework hijacked on PyPI: how to check · original