# 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 | 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, [[XML External Entity Injection\|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 ```python 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. [[raw/r3vpwnx.medium.com/loading-a-dataset-should-not-run-code-15851|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. [[raw/github.com/lxml-default-iterparse-etcompatxmlparser-allows-xxe-to-local-files-15827|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. [[raw/github.com/bentoml-ssti-via-unsandboxed-jinja2-in-dockerfile-generation-15849|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. [[raw/medium.com/microsoft-s-ai-agent-package-was-hijacked-on-pypi-here-s-how-to-check-15853|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. ## 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 - [[raw/snyk.io/code-injection-in-python-examples-and-prevention-9665|Code injection in Python: examples and prevention]] - [[raw/snyk.io/command-injection-in-python-examples-and-prevention-9615|Command injection in Python: examples and prevention]] - [[raw/link.medium.com/10-common-security-gotchas-in-python-and-how-to-avoid-them-831|10 common security gotchas in Python and how to avoid them]] - [[raw/aikido.dev/python-security-vulnerabilities-top-issues-aikido-2859|Python Security Vulnerabilities: Top Issues (Aikido)]] - [[raw/semgrep.dev/insecure-deserialization-in-python-semgrep-2854|Insecure Deserialization in Python (Semgrep)]] - [[raw/levelup.gitconnected.com/python-just-got-a-new-kind-of-string-it-could-end-a-whole-class-of-sec-14232|Python Just Got a New Kind of String (t-strings)]] - [[raw/github.com/arize-phoenix-format-string-injection-in-applychattemplate-graphql-que-14497|Arize Phoenix: format string injection in applyChatTemplate]] - [[raw/github.com/datamodel-code-generator-before-0-84-0-code-injection-14380|datamodel-code-generator before 0.84.0 code injection]] - [[raw/unit42.paloaltonetworks.com/rce-with-modern-ai-ml-formats-and-python-libraries-3396|RCE With Modern AI/ML Formats and Python Libraries]] - [[raw/sentinelone.com/cve-2025-56005-ply-rce-vulnerability-3382|CVE-2025-56005: PLY RCE Vulnerability]] - [[raw/sentinelone.com/cve-2026-33873-langflow-agentic-assistant-rce-vulnerability-2981|CVE-2026-33873: Langflow Agentic Assistant RCE]] - [[raw/infosecwriteups.com/how-i-found-a-high-severity-directory-traversal-in-flask-admin-10887|Directory Traversal in Flask-Admin]] - [[raw/github.com/tandoor-recipes-xxe-local-file-read-via-lxml-and-ssrf-in-importer-12618|Tandoor Recipes XXE via lxml and SSRF]] - [[raw/stackurity.ai/arize-phoenix-cve-2026-53998-graphql-format-string-secrets-leak-15629|Arize Phoenix CVE-2026-53998 GraphQL format-string secrets leak]] - [[raw/r3vpwnx.medium.com/loading-a-dataset-should-not-run-code-15851|Loading a Dataset Should Not Run Code (yt CVE-2026-132751)]] - [[raw/github.com/lxml-default-iterparse-etcompatxmlparser-allows-xxe-to-local-files-15827|lxml GHSA-vfmq-68hx-4jfw: iterparse/ETCompatXMLParser XXE]] - [[raw/github.com/bentoml-ssti-via-unsandboxed-jinja2-in-dockerfile-generation-15849|BentoML GHSA-v959-cwq9-7hr6: SSTI via unsandboxed Jinja2]] - [[raw/medium.com/microsoft-s-ai-agent-package-was-hijacked-on-pypi-here-s-how-to-check-15853|Microsoft's agent-framework hijacked on PyPI: how to check]]