# Python Security > Securing Python code and the ecosystem around it. That means the language-level sinks that turn data into code, framework failure modes, in-interpreter sandboxes, the JOSE and AI/ML library stack, and the packaging supply chain that delivers all of it. ## What it is Python security is a review and hardening discipline for one ecosystem rather than one bug class. Its attack surface comes from three properties: - **Dynamism.** Introspection, `eval`/`exec`, `__reduce__` and `str.format` field resolution mean many "load", "parse" or "render" APIs actually execute code. Any object can reach the object graph, so in-process sandboxes fail. [[raw/aikido.dev/python-security-vulnerabilities-top-issues-aikido-2859|Aikido]], [[raw/healeycodes.com/running-untrusted-python-code-683|healeycodes]] - **Convenience defaults.** `**kwargs` forwarding into ORMs, `yaml.load`, stdlib XML parsers, `tarfile.extractall`, `debug=True`, and frameworks that rebuild URLs from `Host`. [[raw/link.medium.com/10-common-security-gotchas-in-python-and-how-to-avoid-them-831|10 gotchas]] - **Ecosystem depth.** Most risk arrives transitively: PyJWT under an auth library, pickle under `torch.load`, Starlette under FastAPI, vLLM and LiteLLM. PyPI itself is a direct attack vector. [[raw/bernat.tech/defense-in-depth-a-practical-guide-to-python-supply-chain-security-4234|bernat.tech]] The AI stack is now Python's highest-churn attack surface. In it, model files, chat templates, metadata and LLM output are effectively code, and notebook, MLOps and inference servers often ship without authentication. ## Core concepts - **"Load" means "execute".** `pickle`, `torch.load`, `numpy.load(allow_pickle=True)`, `yaml.load`, Hydra `instantiate()` and `str.format` over user templates all run attacker-chosen code paths. See [[Unsafe Python Functions]] and [[Python Pickle Deserialization]]. - **Indirect evaluation.** The dangerous call is often inside a library rather than the app. datamodel-code-generator < 0.84.0 (CVE-2026-127208) `eval()`s a schema-supplied expression during Pydantic `model_rebuild()`. [[raw/github.com/datamodel-code-generator-before-0-84-0-code-injection-14380|datamodel-code-generator]] - **Attribute traversal.** Jinja2 expressions and `str.format` fields walk `__class__`/`__globals__` from any reachable object to module globals. A wrapper `__getattr__` guard doesn't stop `Formatter.get_field()`. See [[Jinja2 SSTI]] and [[Unsafe Python Functions]]. - **Class pollution.** This is Python's analogue of mutating shared object state. Attacker-controlled attribute writes alter class definitions or instances in deployed apps. It was presented at DEF CON 34, but only the talk excerpt is in the vault. [[raw/media.defcon.org/def-con-34-unveiling-python-class-pollution-in-the-wild-13411|DEF CON 34: Python Class Pollution]] - **Sandbox is not a boundary.** CPython explicitly doesn't treat sandboxing untrusted Python as a security boundary. Isolate at the process, container or VM level. See [[Python Sandbox Escapes]]. [[raw/runsybil.com/cpython-0-days-threaten-the-ai-supply-chain-jinja-model-template-sandb-15664|RunSybil]] - **Derived request values.** Authz on a value the framework reconstructs, such as Starlette's `request.url.path` built from `Host`, can diverge from what the router dispatches. See [[Python Web Framework Security]]. - **Caller-side preconditions in JOSE.** Most Python JWT bypasses need a caller mistake: an HS+RS mixed `algorithms` list, or a key that can resolve to empty. See [[Python JWT Library Vulnerabilities]]. ## How to approach it 1. **Inventory.** Record the framework, Python version and the security-relevant libraries (Django, Starlette, PyJWT/Authlib/python-jose, Jinja2, aiohttp, any AI framework). Check versions with `pip show <pkg>` and lockfiles. [[raw/stackurity.ai/arize-phoenix-cve-2026-53998-graphql-format-string-secrets-leak-15629|stackurity]] 2. **Fast SAST pass.** Run Bandit at high severity, then targeted greps for sinks Bandit doesn't model. See [[Python SAST Tools]]. 3. **Map execution sinks.** Find every place that loads a model, config, template, schema, project file or pickle from outside, and treat each one as code execution until you've read the library. 4. **Framework review.** Look for kwargs expansion into QuerySets, user-controlled sort or order parameters, path-prefix jail checks, `render_template_string`, debug mode, exposed OpenAPI docs and Host-derived authz. 5. **AuthN/Z libraries.** Read every `jwt.decode` call: algorithm pinning, key source (can it be empty?), and `verify_signature`. 6. **Outbound fetches.** Webhooks, URL inputs, RAG loaders and model-supplied URLs are [[Server-Side Request Forgery|SSRF]] sinks. Check that guards pin the resolved IP, re-check on redirects and cover every cloud metadata address. 7. **Code-running features.** For any feature that runs user or LLM Python or templates, confirm OS/VM-level isolation that fails closed, with no credentials and no egress. 8. **Supply chain.** Check hash-pinned lockfiles, audit, cooldowns, provenance and Trusted Publishing. Review CI workflows that publish to PyPI. ## Key techniques ### Language and stdlib sinks Full table in [[Unsafe Python Functions]]. The high-value ones: | Sink | Safer pattern | |---|---| | `eval`/`exec`/`compile` | `ast.literal_eval()` or no evaluation | | `subprocess.*(..., shell=True)`, `os.system` | argv list with `shell=False`, which still allows [[Argument Injection]] | | `pickle`/`dill`/`jsonpickle`/`shelve`/`marshal` | JSON or MessagePack; see [[Python Pickle Deserialization]] | | `torch.load()`, `numpy.load(allow_pickle=True)` | safetensors, `weights_only=True` (not a full boundary: Stanza CVE-2026-115878) | | `yaml.load()` | `yaml.safe_load()` (CVE-2017-18342) | | `hydra.utils.instantiate()` | Allowlist `_target_` | | `xml.etree`/`lxml` default | `defusedxml`; lxml < 6.1 `iterparse()`/`ETCompatXMLParser()` still resolve external entities (GHSA-vfmq-68hx-4jfw): upgrade or pass `resolve_entities='internal'` | | `tarfile.extractall()` | Validate members (CVE-2007-4559) | | `str.format` over user templates | Restrict `Formatter.get_field()`; PEP 750 t-strings | | `tempfile.mktemp()`, `assert` for authz, `==` on secrets, `verify=False` | `mkstemp()`, explicit `raise`, `secrets.compare_digest()`, real TLS | [[raw/snyk.io/code-injection-in-python-examples-and-prevention-9665|Snyk code injection]], [[raw/snyk.io/command-injection-in-python-examples-and-prevention-9615|Snyk command injection]], [[raw/semgrep.dev/insecure-deserialization-in-python-semgrep-2854|Semgrep]], [[raw/levelup.gitconnected.com/python-just-got-a-new-kind-of-string-it-could-end-a-whole-class-of-sec-14232|t-strings]], [[raw/github.com/stanza-rce-via-pickle-deserialization-in-the-lemmatizer-13585|Stanza]] Pickle also shows up in desktop "project file" formats. OpenShot ≤ 4.1.1 (CVE-2026-134704) passes non-JSON `.osp` files to `pickle.load()` in `ProjectDataStore.load()` and `read_legacy_project_file()`. [[raw/github.com/openshot-video-editor-openshot-qt-unsafe-deserialization-15662|OpenShot advisory]] `eval()` shows up in data loaders too. yt ≤ 4.4.4 (CVE-2026-132751, CWE-95) `eval()`s the `con_args` attribute stored in a saved ytdata HDF5 file inside `SavedDataset._parse_parameter_file()`, so `yt.load()` on a shared dataset runs its author's code. [[raw/r3vpwnx.medium.com/loading-a-dataset-should-not-run-code-15851|r3vpwnx]] ### Format-string injection Arize Phoenix CVE-2026-53998 (CVSS 10, CWE-134/CWE-200, 13.0.0 to < 15.7.0) is the reference case. The `applyChatTemplate` GraphQL query accepts f-string-style templates, and attribute traversal reaches `os.environ`, including `PHOENIX_SECRET`. That key enables admin session forgery and decryption of stored LLM provider keys. The endpoint is unauthenticated on default installs. Turning on auth doesn't fix it because any account works. Fix: upgrade, then rotate `PHOENIX_SECRET` and the stored keys. [[raw/stackurity.ai/arize-phoenix-cve-2026-53998-graphql-format-string-secrets-leak-15629|stackurity]], [[raw/github.com/arize-phoenix-format-string-injection-in-applychattemplate-graphql-que-14497|GHSA]] ### Template injection (Jinja2) `render_template_string()` / `jinja2.Template()` on user text is the sink. `render_template()` with user data as context is safe. One unsafe sink is enough: in the HackSmarter Casino lab, the dashboard escaped the display name but the profile view put it through `render_template_string`. There, `{{7*7}}{{config}}` returned `49` and the Flask `SECRET_KEY`. In the Poet lab, path traversal reached `/proc/self/environ` and `app.py`, which exposed the cookie secret and then the admin panel's SSTI. Details in [[Jinja2 SSTI]]. [[raw/github.com/hacksmarter-casino-walkthrough-leaked-source-map-api-to-flask-ssti-15666|Casino walkthrough]], [[raw/n0xshell.dev/poet-writeup-lfi-to-forged-cookie-to-jinja2-ssti-rce-15665|Poet writeup]] Two more shapes: - **Template shipped inside an artifact.** BentoML (GHSA-v959-cwq9-7hr6) rendered a bento archive's `env/docker/Dockerfile.template` during `bentoml containerize` in an unsandboxed `jinja2.Environment` with `jinja2.ext.do` and `jinja2.ext.debug`. Code ran on the host before Docker started, so container isolation never applied. Fix: `SandboxedEnvironment` and drop `do`/`debug`. [[raw/github.com/bentoml-ssti-via-unsandboxed-jinja2-in-dockerfile-generation-15849|BentoML advisory]] - **Blacklist in front of `render_template_string`.** FortiPy concatenated `?user=` into the template source behind a case-insensitive substring blacklist (`__`, `os`, `globals`, `[`, `%`…). Jinja resolves `\xNN` escapes in string literals after the filter has scanned the raw bytes, and `|attr()`/`__getitem__` replace dot and subscript access, so the filter never saw the tokens. The Flask process was PID 1 as root, and `{{ config }}` leaked `SECRET_KEY` for forged `role: admin` session cookies. [[raw/ssstrickys.com/fortipy-ssti-to-root-writeup-15855|FortiPy]] ### Sandboxes In-interpreter sandboxes keep failing: - **AST validators and proxy builtins.** AWS MCP `run_script` and Redash both fell to these. - **Fallback to an in-process mode.** CrewAI CVE-2026-2275/2287. - **No isolation at all.** Langflow CVE-2026-33873. - **CPython memory-safety bugs.** RunSybil escaped Jinja's `ImmutableSandboxedEnvironment` in a model `chat_template.jinja` through an out-of-bounds read in generic-alias parameter substitution. This gave code execution in vLLM serving processes. CPython patched it but declined to backport, so "security-fix-only" CPython releases remain exposed. See [[Python Sandbox Escapes]]. [[raw/xplo1t-sec.github.io/breaking-the-aws-mcp-python-sandbox-12381|AWS MCP]], [[raw/ox.security/known-unpatched-exploitable-redashs-python-sandbox-escape-gives-attack-5213|Redash]], [[raw/kb.cert.org/crewai-contains-multiple-vulnerabilities-including-ssrf-rce-2963|CrewAI]], [[raw/sentinelone.com/cve-2026-33873-langflow-agentic-assistant-rce-vulnerability-2981|Langflow]], [[raw/runsybil.com/cpython-0-days-threaten-the-ai-supply-chain-jinja-model-template-sandb-15664|RunSybil]] ### Web frameworks Details in [[Python Web Framework Security]]. - **Django CVE-2025-64459.** `filter(**request.GET.dict())` lets an attacker inject `_connector=OR` and `_negated=True`. Fixed in 5.2.8, 5.1.14 and 4.2.26. See [[ORM Injection]]. [[raw/endorlabs.com/critical-sql-injection-vulnerability-in-django-cve-2025-64459-4814|Endor Labs]] - **Starlette BadHost CVE-2026-48710.** `Host: foo?` desyncs `request.url.path` from the routed path (`/admin` goes from 403 to 200). Fixed in ≥ 1.0.1. Make security decisions on `request.scope["path"]`. [[raw/korben.info/badhost-one-character-and-your-ai-agent-switches-sides-9901|BadHost]] - **Flask.** `debug=True`, no built-in CSRF (use Flask-WTF `CSRFProtect`), and the Flask-Admin `FileAdmin` `startswith(base_path)` sibling-prefix traversal. [[raw/snyk.io/how-to-secure-python-flask-applications-9508|Snyk Flask]], [[raw/infosecwriteups.com/how-i-found-a-high-severity-directory-traversal-in-flask-admin-10887|Flask-Admin]] - **FastAPI.** `/openapi.json`, `/docs` and `/redoc` are on by default. Set `docs_url=None` in production. [[raw/medium.com/9-attacks-that-own-most-fastapi-apps-in-under-an-hour-exploit-fix-for-13020|FastAPI attacks]] - **aiohttp CVE-2026-34519** (< 3.13.4). CRLF in `Response(reason=...)` causes response splitting. [[raw/sentinelone.com/cve-2026-34519-aiohttp-xss-vulnerability-2982|SentinelOne]] - **Frappe/ERPNext.** This framework produces a steady advisory stream: - SQLi via caller-supplied sort parameters (CVE-2026-134431, fixed 15.122.0 / 16.50.0). - SQLi in Selling/Buying where an early-validated value is overridden by caller data. Any portal user can extract session data and take over admin accounts (CVE-2026-134372, fixed 15.121.6 / 16.37.0). - [[Insecure Direct Object Reference|IDOR]] in SMS Settings `get_contact_number` via an uncorrelated `EXISTS` subquery (CVE-2026-134371, < 16.30.0). - SSRF via Premailer (CVE-2026-130069). - Frappe Builder's SSRF guard bypassed through redirects and DNS rebinding. [[raw/github.com/frappe-erpnext-sql-injection-15648|ERPNext SQLi (sort)]], [[raw/github.com/frappe-erpnext-sql-injection-4-3-0-to-15-121-6-15645|ERPNext SQLi (Selling/Buying)]], [[raw/github.com/frappe-insecure-direct-object-reference-15617|Frappe IDOR]], [[raw/github.com/frappe-framework-ssrf-14907|Frappe SSRF]], [[raw/github.com/frappe-builder-ssrf-guard-bypass-via-redirects-and-dns-rebinding-12767|Frappe Builder]] ### JWT and auth libraries Python JOSE libraries guess whether an HMAC "secret" is really public-key material, and each guess is a bypassable denylist. The four PyJWT 2.14.0 encodings are whitespace/CR PEM, DER, BOM-prefixed JWK and a JWK wrapped in a JWKS. See [[JWT Algorithm Confusion]]. The second recurring class is the empty HMAC key ([[JWT Empty Key Forgery]]): - **python-jose ≤ 3.5.0 (CVE-2026-120459, CVSS v4 9.1).** There is no fixed release. An empty `str`/`bytes` key or an `oct` JWK with `k: ""` verifies signatures anyone can compute. The typical trigger is `os.environ.get("JWT_SECRET", "")`. `jwt.decode()` also defaults `algorithms` to `None`. - **Fix.** Guard against empty key material before decode, always pass `algorithms=["HS256"]`, and migrate to PyJWT 2.15.1, which raises `InvalidKeyError` in `HMACAlgorithm.prepare_key`. Also validate JWKS documents when you fetch them. See [[Python JWT Library Vulnerabilities]]. [[raw/blog.ostorlab.co/python-jose-jwt-forgery-with-an-empty-hmac-key-cve-2026-120459-15663|Ostorlab]], [[raw/safeguard.sh/pyjwt-2-14-2-15-algorithm-confusion-advisories-explained-13229|safeguard.sh]], [[raw/dev.to/jwt-verification-bugs-pin-the-algorithm-then-prove-the-fix-14230|pin the algorithm]] ### AI and ML frameworks Details in [[Python AI and ML Framework Vulnerabilities]]. | Case | What went wrong | |---|---| | Marimo CVE-2026-39987 (KEV) | Pre-auth `/terminal/ws`, exploited within 10 hours | | LangChain CVE-2025-68664 | `"lc"` key revival of untrusted dicts | | MLflow CVE-2026-64849 | Full-read webhook SSRF | | SGLang CVE-2026-5760 | GGUF `chat_template` SSTI | | NeMo / Uni2TS | Hydra `_target_` from model metadata | | Xoscar | Deserialization before auth | Fetch guards are incomplete in practice. pydantic-ai (GHSA-5fj9-5pjw-vpwc) left Tencent Cloud's metadata IP `169.254.0.23` off its cloud-metadata blocklist. That matters when `force_download='allow-local'` or `web_fetch_tool(allow_local_urls=True)` is set, and the URL can come from model output. See [[SSRF in AI Agents and LLM Tools]] and [[Cloud Metadata Service Exploitation]]. Prompt injection in Python LLM apps is handled in layers, not by one filter: delimited user input with forged tags stripped, NFKC-normalised and labelled untrusted documents, per-intent tool allowlists with pydantic-validated arguments and approval gates, then output checks (canary, image-host allowlist, cited-source subset) before rendering. See [[Prompt Injection]]. [[raw/karthikupadrasta.medium.com/how-to-prevent-prompt-injection-in-python-llm-apps-6-layers-that-actua-15852|six layers]] [[raw/thehackernews.com/marimo-rce-flaw-cve-2026-39987-exploited-within-10-hours-of-disclosure-4813|Marimo]], [[raw/socradar.io/cve-2025-68664-critical-langchain-flaw-enables-secret-extraction-4808|LangChain]], [[raw/patchnext.com/mlflow-unauthenticated-full-read-ssrf-in-webhook-delivery-12765|MLflow]], [[raw/thehackernews.com/sglang-cve-2026-5760-cvss-9-8-enables-rce-via-malicious-gguf-model-fil-4812|SGLang]], [[raw/unit42.paloaltonetworks.com/rce-with-modern-ai-ml-formats-and-python-libraries-3396|Unit 42]], [[raw/github.com/xoscar-unauthenticated-rce-through-actor-message-deserialization-12478|Xoscar]], [[raw/github.com/pydantic-ai-ssrf-guard-misses-tencent-cloud-metadata-169-254-0-23-15642|pydantic-ai]] ### Supply chain - **Execution hooks.** - Microsoft agent-framework 1.26.1/1.26.2 (17 November 2026, PYSEC-2026-4388): the genuine 1.26.0 wheel plus `agent_framework_meta.pth` / `af_runtime_diag.pth`, so the stealer ran on every interpreter start in the environment, including `pip`, without any import. It took cloud, CI, package-manager and Hugging Face credentials and (1.26.2) GitHub Actions OIDC tokens. Wiz assesses a stolen ESRP release certificate and key, so the publish credential was valid. Response: list `.pth` lines starting with `import` in every site-packages (`distutils-precedence.pth` is normal), remove the hooks before running Python tooling there, check lockfiles, CI logs and image layers, purge caches and mirrors, and rotate everything reachable. See [[AI Infrastructure Vulnerabilities]]. [[raw/medium.com/microsoft-s-ai-agent-package-was-hijacked-on-pypi-here-s-how-to-check-15853|agent-framework check]], [[raw/medium.com/the-credential-was-valid-the-publisher-was-not-15854|VeritasChain]] - A `.pth` file in site-packages runs on every interpreter start (LiteLLM 1.82.8 `litellm_init.pth`). - Import-time injection (LiteLLM 1.82.7). - A trojanized CI workflow published Ultralytics 8.3.41/8.3.42 with XMRig via branch-name injection. See [[Malicious Packages]], [[GitHub Actions Security]], [[Pwn Requests]] and [[Shai-Hulud Worm]]. [[raw/wiz.io/three-s-a-crowd-teampcp-trojanizes-litellm-in-continuation-of-campaign-8841|Wiz TeamPCP]], [[raw/wiz.io/ultralytics-ai-library-hacked-via-github-for-cryptomining-9459|Wiz Ultralytics]] - **Name attacks.** [[Typosquatting]], [[Dependency Confusion]] and [[Slopsquatting]]. - **Provenance.** PyPI project pages have a security tab. - **Full Provenance** means every file carries a PyPI Publish (Trusted Publisher) or SLSA Build attestation. - **Warnings** flag mixed attested/unattested files, files from different build systems, a changed source repo or workflow, and a project that stopped attesting. Any of these can signal account or pipeline takeover. - **Late files.** Since July 2026, files uploaded more than 14 days after a release are rejected. See [[SBOM and Provenance]]. [[raw/blog.pypi.org/pypi-s-redesigned-project-pages-with-clearer-security-signals-are-now-15656|PyPI blog]] - **Install policy.** - `pip-compile --generate-hashes` or `uv pip compile --generate-hashes` with `pip install --require-hashes`; let new releases age before adoption (agent-framework was live under an hour); CI `permissions: contents: read` by default, `id-token: write` only where needed; egress allowlists on runners. [[raw/medium.com/microsoft-s-ai-agent-package-was-hijacked-on-pypi-here-s-how-to-check-15853|agent-framework check]] - pip 26.1 dependency cooldowns and experimental PEP 751 `pylock.toml`. - `uv` lockfiles with hashes. - Upgrade certifi ≥ 2026.10.19 and pip ≥ 26.2.2 after the eMudhra/emSign CA compromise. [[raw/infoq.com/pip-26-1-ships-dependency-cooldowns-and-experimental-lockfile-support-8131|InfoQ pip 26.1]], [[raw/stepsecurity.io/emudhra-emsign-ca-compromise-what-python-pip-and-ci-cd-users-need-to-u-14804|StepSecurity]] - **Interpreter and release.** - CVE-2026-12003 is an uncontrolled search path in CPython 3.11.0a3–3.15.0b2 on Windows. - CPython isolated its source-artifact build, cutting dependencies from 800+ to about 170. [[raw/bishopfox.com/python-software-foundation-python-3-11-0a3-to-3-15-0b2-11233|Bishop Fox]], [[raw/sethmlarson.dev/isolating-risk-in-the-cpython-release-process-5341|Seth Larson]] - **Secrets.** Load them from the environment or a secret manager, never from source, logs or shell history. See [[Hardcoded Secrets]] and [[Secrets Management]]. [[raw/blog.gitguardian.com/how-to-handle-secrets-in-python-six-secure-patterns-15509|GitGuardian]] ## Tools | Need | Tool / command | |---|---| | Pattern SAST | `bandit -r src/ --severity-level high`; baseline with `-f json -o baseline.json` then `-b baseline.json`; `-f sarif` for code scanning | | Taint across modules | Semgrep (12+ deser libraries), CodeQL, Pyre/Pysa, Bearer | | JOSE misconfig | `grep -rnE "algorithms\s*=\s*\[.*HS[0-9]+.*(RS\|ES\|PS\|EdDSA)" --include=*.py .`; `grep -rn "jwt.decode\|jws.verify" --include=*.py .` | | Sink greps | `shell=True`, `pickle.load`, `yaml.load(`, `allow_pickle=True`, `torch.load(`, `instantiate(`, `render_template_string`, `\.objects\.(filter\|exclude\|get)\(\*\*`, `request.url.path` in middleware | | Versions | `pip show arize-phoenix pyjwt python-jose`, `pip freeze \| grep -i jose` | | Package triage | `guarddog pypi scan <pkg> --version <v>`; PyPI security tab | | Dependency audit | `pip-audit`, CycloneDX SBOM, `uv` hash-pinned lockfiles | | Pickle scanners | picklescan, Fickling, modelscan (bypassed repeatedly, so not a boundary) | | Training | OWASP PyGoat (Django) | [[raw/appsecsanta.com/bandit-python-free-sast-in-10-seconds-2026-review-4809|appsecsanta]], [[raw/dev.to/bandit-python-static-application-security-testing-guide-2858|Bandit guide]], [[raw/bito.ai/python-sast-tools-free-paid-solutions-for-secure-code-analysis-2852|bito]], [[raw/github.com/guarddog-cli-tool-to-identify-malicious-pypi-and-npm-packages-4339|GuardDog]], [[raw/sonatype.com/cve-2025-1716-sonatype-security-advisory-3384|picklescan bypass]], [[raw/owasp.org/owasp-pygoat-699|PyGoat]] ## Pitfalls - **Grepping only app code.** `eval` inside Pydantic `model_rebuild()` and `instantiate()` inside a model loader are invisible to pattern SAST. Read the loading library. - **Trusting `weights_only=True` or pickle scanners as boundaries.** Stanza, picklescan CVE-2025-1716 and Fickling CVE-2026-22607 all show bypasses. [[raw/afine.com/pickle-deserialization-in-ml-pipelines-the-rce-that-won-t-go-away-3815|afine]] - **Treating a Jinja sandbox or AST filter as isolation.** It is best-effort at most. RunSybil advises assuming code execution through template engines and expression evaluators. - **Fixing one render path.** Casino escaped the dashboard but not the profile view. Audit every sink that echoes the same field. - **Substring blacklists in front of templates.** The engine decodes escapes after the filter inspects bytes (FortiPy). Never splice input into template source. - **Assuming build tooling runs inside the container.** BentoML rendered the archive's template on the host before Docker was invoked. - **Partial default fixes.** lxml 5.0 made `resolve_entities='internal'` the default for the normal XML and HTML parsers but not `iterparse()`/`ETCompatXMLParser()` until 6.1. - **Auth as the fix for an unauthenticated bug.** For Phoenix, enabling auth still lets any account exploit it. Upgrade and rotate secrets. - **Empty-default secrets.** `os.environ.get("X", "")` feeding an HMAC key gives a forgeable JWT with python-jose. - **Path checks with `startswith`.** These pass sibling directories. Browsers normalize `../`, so test with a raw client. - **Incomplete SSRF denylists.** Metadata IPs vary by cloud (`169.254.0.23` on Tencent). Guards must also re-check redirects and rebinding. - **Assuming validated input stays validated.** ERPNext CVE-2026-134372 let caller data override a value after it had been validated. - **Pinning but not auditing transitives.** PyJWT and Starlette usually arrive transitively. ## Real-world cases - Django CVE-2025-64459: `_connector`/`_negated` kwargs injection, CVSS 9.1. [[raw/endorlabs.com/critical-sql-injection-vulnerability-in-django-cve-2025-64459-4814|Endor Labs]] - Starlette CVE-2026-48710 (BadHost): Host-derived path desync bypasses path-based authz. [[raw/korben.info/badhost-one-character-and-your-ai-agent-switches-sides-9901|korben]] - Arize Phoenix CVE-2026-53998: format-string leak of `PHOENIX_SECRET`, CVSS 10. [[raw/stackurity.ai/arize-phoenix-cve-2026-53998-graphql-format-string-secrets-leak-15629|stackurity]] - python-jose CVE-2026-120459: empty HMAC key forgery, unpatched. [[raw/blog.ostorlab.co/python-jose-jwt-forgery-with-an-empty-hmac-key-cve-2026-120459-15663|Ostorlab]] - OpenShot CVE-2026-134704: `.osp` project file goes to `pickle.load()`. [[raw/github.com/openshot-video-editor-openshot-qt-unsafe-deserialization-15662|GHSA]] - ERPNext CVE-2026-134372 / CVE-2026-134431: authenticated SQLi leading to session data and admin takeover. [[raw/github.com/frappe-erpnext-sql-injection-4-3-0-to-15-121-6-15645|GHSA]], [[raw/github.com/frappe-erpnext-sql-injection-15648|GHSA]] - Frappe CVE-2026-134371: IDOR leaking Contact phone numbers. [[raw/github.com/frappe-insecure-direct-object-reference-15617|GHSA]] - pydantic-ai GHSA-5fj9-5pjw-vpwc: SSRF guard missed Tencent metadata. [[raw/github.com/pydantic-ai-ssrf-guard-misses-tencent-cloud-metadata-169-254-0-23-15642|GHSA]] - RunSybil CPython 0-day: Jinja `ImmutableSandboxedEnvironment` escape via a model chat template in vLLM. [[raw/runsybil.com/cpython-0-days-threaten-the-ai-supply-chain-jinja-model-template-sandb-15664|RunSybil]] - Marimo CVE-2026-39987: pre-auth terminal WebSocket, CISA KEV. [[raw/thehackernews.com/marimo-rce-flaw-cve-2026-39987-exploited-within-10-hours-of-disclosure-4813|THN]] - AWS MCP `run_script`: AST validator bypass, with blast radius contained by a deny-all role. [[raw/xplo1t-sec.github.io/breaking-the-aws-mcp-python-sandbox-12381|xplo1t]] - LiteLLM 1.82.7/1.82.8 (TeamPCP): import-time and `.pth` payloads. [[raw/wiz.io/three-s-a-crowd-teampcp-trojanizes-litellm-in-continuation-of-campaign-8841|Wiz]] - Ultralytics 8.3.41/8.3.42: GitHub Actions branch-name injection leading to XMRig. [[raw/wiz.io/ultralytics-ai-library-hacked-via-github-for-cryptomining-9459|Wiz]] - Labs: Casino (Flask SSTI via `render_template_string`) and Poet (LFI, then forged cookie, then Jinja2 SSTI). [[raw/github.com/hacksmarter-casino-walkthrough-leaked-source-map-api-to-flask-ssti-15666|Casino]], [[raw/n0xshell.dev/poet-writeup-lfi-to-forged-cookie-to-jinja2-ssti-rce-15665|Poet]] - BentoML GHSA-v959-cwq9-7hr6: malicious bento archive's Dockerfile template gives host RCE on `containerize`. [[raw/github.com/bentoml-ssti-via-unsandboxed-jinja2-in-dockerfile-generation-15849|GHSA]] - lxml < 6.1 GHSA-vfmq-68hx-4jfw: `iterparse()`/`ETCompatXMLParser()` default XXE to local files. [[raw/github.com/lxml-default-iterparse-etcompatxmlparser-allows-xxe-to-local-files-15827|GHSA]] - yt CVE-2026-132751: `eval()` on a stored HDF5 attribute during `yt.load()`. [[raw/r3vpwnx.medium.com/loading-a-dataset-should-not-run-code-15851|r3vpwnx]] - Microsoft agent-framework 1.26.1/1.26.2: `.pth` credential stealer from a valid publisher credential. [[raw/medium.com/the-credential-was-valid-the-publisher-was-not-15854|VeritasChain]] - FortiPy lab: blacklist-filtered Jinja2 SSTI bypassed with `\xNN` escapes, root via the app running as PID 1. [[raw/ssstrickys.com/fortipy-ssti-to-root-writeup-15855|FortiPy]] ## Checklist - [ ] `bandit -r . --severity-level high` is clean or triaged, with suppressions scoped as `# nosec Bxxx`. - [ ] No `eval`/`exec`, `shell=True`, `pickle`/`dill`/`marshal`, `yaml.load` or `allow_pickle=True` on external data. - [ ] Every model, config, template, schema or project-file loader is reviewed as a code-execution sink. Hydra `_target_` is allowlisted and loads are safetensors-only. - [ ] No `render_template_string`/`Template()` or `str.format` over user-controlled template text. Autoescape is on. - [ ] Any Jinja2 rendering of files from archives, models or users uses `SandboxedEnvironment` without `jinja2.ext.do`/`debug`. - [ ] lxml ≥ 6.1, or `resolve_entities` set explicitly on every parser including `iterparse()`. - [ ] Django: no `objects.filter(**request...)`. Version ≥ 5.2.8 / 5.1.14 / 4.2.26. - [ ] Starlette ≥ 1.0.1. Authz uses `request.scope["path"]`. Proxy rejects `/?#` in Host. - [ ] Sort/order parameters are allowlisted. Validated values can't be overridden later in the request. - [ ] Object-level authz on every whitelisted or RPC method (Frappe-style). - [ ] Flask/Django `DEBUG` off, `SECRET_KEY` from the environment, CSRF on, FastAPI docs disabled. - [ ] `jwt.decode` uses one pinned algorithm per issuer, a non-empty typed key and no `verify_signature: False`. python-jose is replaced. - [ ] Outbound fetchers pin the resolved IP, re-check every redirect and block all cloud metadata IPs, including `169.254.0.23`. - [ ] User/LLM code runs in a VM/container that fails closed, with no credentials, no egress and per-session state. - [ ] CPython is on a release that receives bugfixes wherever templates or sandboxes process untrusted input. - [ ] Hash-pinned lockfile, `pip-audit`, cooldowns, Trusted Publishing, and PyPI provenance warnings reviewed. - [ ] Executable `.pth` files in each site-packages reviewed; CI jobs hold no long-lived secrets and mint OIDC tokens only where needed. - [ ] pip ≥ 26.2.2, certifi ≥ 2026.10.19. Secrets are absent from source, logs and shell history. ## Sub-pages - [[Unsafe Python Functions]]: the sink reference, covering `eval`/`exec`, `shell=True`, pickle/YAML, format strings, Hydra, XML, tarfile and TLS. - [[Python Sandbox Escapes]]: why AST and builtin-filter sandboxes fail, and how to isolate at the OS/VM level instead. - [[Python Web Framework Security]]: Django, Flask, FastAPI/Starlette, aiohttp and Frappe failure modes and CVEs. - [[Python AI and ML Framework Vulnerabilities]]: Marimo, Langflow, LangChain, SGLang, MLflow, CrewAI and Hydra model loaders. - [[Python SAST Tools]]: Bandit IDs and CI usage, Semgrep, CodeQL, Pysa, and targeted grep for library misuse. Related pages in other topics: - [[Python Pickle Deserialization]]: `__reduce__` gadgets, ML checkpoints and scanner limits (deser). - [[Jinja2 SSTI]]: Flask, Frappe and model chat-template injection, and sandbox failures (ssti). - [[Python JWT Library Vulnerabilities]]: PyJWT, Authlib, joserfc and python-jose key confusion and empty keys (jwt). - [[Malicious Packages]], [[Typosquatting]], [[Dependency Confusion]], [[Slopsquatting]], [[Shai-Hulud Worm]]: PyPI delivery vectors (supplychain). - [[GitHub Actions Security]], [[Pwn Requests]], [[SBOM and Provenance]]: CI publishing and provenance. - [[Remote Code Execution]], [[Code Injection]], [[Command Injection]], [[Insecure Deserialization]], [[Model Deserialization Attacks]], [[Server-Side Template Injection]], [[JSON Web Tokens]], [[SQL Injection]], [[ORM Injection]], [[Server-Side Request Forgery]], [[Software Supply Chain Security]], [[AI and LLM Security]], [[GraphQL Security]]. See also: [[Path Traversal]] · [[Zip Slip and Archive Extraction]] ## Sources - [[raw/aikido.dev/python-security-vulnerabilities-top-issues-aikido-2859|Python Security Vulnerabilities: Top Issues (Aikido)]] - [[raw/link.medium.com/10-common-security-gotchas-in-python-and-how-to-avoid-them-831|10 common security gotchas in Python]] - [[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/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/stackurity.ai/arize-phoenix-cve-2026-53998-graphql-format-string-secrets-leak-15629|Arize Phoenix CVE-2026-53998: GraphQL format-string secrets leak]] - [[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-2026-33873-langflow-agentic-assistant-rce-vulnerability-2981|CVE-2026-33873: Langflow Agentic Assistant RCE]] - [[raw/healeycodes.com/running-untrusted-python-code-683|Running Untrusted Python Code]] - [[raw/xplo1t-sec.github.io/breaking-the-aws-mcp-python-sandbox-12381|Breaking the AWS MCP Python Sandbox]] - [[raw/ox.security/known-unpatched-exploitable-redashs-python-sandbox-escape-gives-attack-5213|Redash's Python Sandbox Escape Gives Attackers Full Server Access]] - [[raw/kb.cert.org/crewai-contains-multiple-vulnerabilities-including-ssrf-rce-2963|CrewAI contains multiple vulnerabilities including SSRF, RCE]] - [[raw/thehackernews.com/sglang-cve-2026-5760-cvss-9-8-enables-rce-via-malicious-gguf-model-fil-4812|SGLang CVE-2026-5760 RCE via malicious GGUF]] - [[raw/runsybil.com/cpython-0-days-threaten-the-ai-supply-chain-jinja-model-template-sandb-15664|CPython 0-days threaten the AI supply chain (Jinja model-template sandbox escape)]] - [[raw/media.defcon.org/def-con-34-unveiling-python-class-pollution-in-the-wild-13411|DEF CON 34: Unveiling Python Class Pollution in the Wild]] - [[raw/endorlabs.com/critical-sql-injection-vulnerability-in-django-cve-2025-64459-4814|Critical SQL Injection Vulnerability in Django (CVE-2025-64459)]] - [[raw/korben.info/badhost-one-character-and-your-ai-agent-switches-sides-9901|BadHost: one character and your AI agent switches sides]] - [[raw/snyk.io/how-to-secure-python-flask-applications-9508|How to secure Python Flask applications]] - [[raw/infosecwriteups.com/how-i-found-a-high-severity-directory-traversal-in-flask-admin-10887|Directory Traversal in Flask-Admin]] - [[raw/medium.com/9-attacks-that-own-most-fastapi-apps-in-under-an-hour-exploit-fix-for-13020|9 Attacks That Own Most FastAPI Apps]] - [[raw/sentinelone.com/cve-2026-34519-aiohttp-xss-vulnerability-2982|CVE-2026-34519: AIOHTTP response splitting]] - [[raw/github.com/frappe-framework-ssrf-14907|Frappe Framework SSRF]] - [[raw/github.com/frappe-builder-ssrf-guard-bypass-via-redirects-and-dns-rebinding-12767|Frappe Builder SSRF guard bypass]] - [[raw/github.com/frappe-erpnext-sql-injection-15648|Frappe ERPNext SQL injection]] - [[raw/github.com/frappe-erpnext-sql-injection-4-3-0-to-15-121-6-15645|Frappe ERPNext SQL injection (4.3.0 to 15.121.6)]] - [[raw/github.com/frappe-insecure-direct-object-reference-15617|Frappe insecure direct object reference]] - [[raw/github.com/openshot-video-editor-openshot-qt-unsafe-deserialization-15662|OpenShot Video Editor (openshot-qt) unsafe deserialization]] - [[raw/github.com/hacksmarter-casino-walkthrough-leaked-source-map-api-to-flask-ssti-15666|HackSmarter Casino walkthrough: leaked source-map API to Flask SSTI]] - [[raw/n0xshell.dev/poet-writeup-lfi-to-forged-cookie-to-jinja2-ssti-rce-15665|Poet writeup: LFI to forged cookie to Jinja2 SSTI RCE]] - [[raw/blog.ostorlab.co/python-jose-jwt-forgery-with-an-empty-hmac-key-cve-2026-120459-15663|python-jose JWT forgery with an empty HMAC key (CVE-2026-120459)]] - [[raw/safeguard.sh/pyjwt-2-14-2-15-algorithm-confusion-advisories-explained-13229|PyJWT 2.14/2.15 advisories explained]] - [[raw/dev.to/jwt-verification-bugs-pin-the-algorithm-then-prove-the-fix-14230|JWT verification bugs: pin the algorithm, then prove the fix]] - [[raw/github.com/pydantic-ai-ssrf-guard-misses-tencent-cloud-metadata-169-254-0-23-15642|pydantic-ai SSRF guard misses Tencent Cloud metadata (169.254.0.23)]] - [[raw/thehackernews.com/marimo-rce-flaw-cve-2026-39987-exploited-within-10-hours-of-disclosure-4813|Marimo RCE Flaw CVE-2026-39987 Exploited Within 10 Hours]] - [[raw/socradar.io/cve-2025-68664-critical-langchain-flaw-enables-secret-extraction-4808|CVE-2025-68664: LangChain secret extraction]] - [[raw/patchnext.com/mlflow-unauthenticated-full-read-ssrf-in-webhook-delivery-12765|MLflow unauthenticated full-read SSRF in webhook delivery]] - [[raw/github.com/xoscar-unauthenticated-rce-through-actor-message-deserialization-12478|Xoscar unauthenticated RCE through actor message deserialization]] - [[raw/sonatype.com/cve-2025-1716-sonatype-security-advisory-3384|CVE-2025-1716 picklescan bypass]] - [[raw/afine.com/pickle-deserialization-in-ml-pipelines-the-rce-that-won-t-go-away-3815|Pickle Deserialization in ML Pipelines]] - [[raw/github.com/stanza-rce-via-pickle-deserialization-in-the-lemmatizer-13585|Stanza RCE via pickle deserialization]] - [[raw/appsecsanta.com/bandit-python-free-sast-in-10-seconds-2026-review-4809|Bandit Python: Free SAST in 10 Seconds]] - [[raw/dev.to/bandit-python-static-application-security-testing-guide-2858|Bandit: Python Static Application Security Testing Guide]] - [[raw/bito.ai/python-sast-tools-free-paid-solutions-for-secure-code-analysis-2852|Python SAST Tools: Free & Paid Solutions]] - [[raw/github.com/guarddog-cli-tool-to-identify-malicious-pypi-and-npm-packages-4339|GuardDog]] - [[raw/bernat.tech/defense-in-depth-a-practical-guide-to-python-supply-chain-security-4234|Defense in Depth: Python Supply Chain Security]] - [[raw/infoq.com/pip-26-1-ships-dependency-cooldowns-and-experimental-lockfile-support-8131|pip 26.1 ships dependency cooldowns]] - [[raw/stepsecurity.io/emudhra-emsign-ca-compromise-what-python-pip-and-ci-cd-users-need-to-u-14804|eMudhra/emSign CA compromise: what Python users need to update]] - [[raw/bishopfox.com/python-software-foundation-python-3-11-0a3-to-3-15-0b2-11233|Python 3.11.0a3 to 3.15.0b2 (CVE-2026-12003)]] - [[raw/sethmlarson.dev/isolating-risk-in-the-cpython-release-process-5341|Isolating risk in the CPython release process]] - [[raw/wiz.io/ultralytics-ai-library-hacked-via-github-for-cryptomining-9459|Ultralytics AI Library Hacked via GitHub]] - [[raw/wiz.io/three-s-a-crowd-teampcp-trojanizes-litellm-in-continuation-of-campaign-8841|TeamPCP trojanizes LiteLLM]] - [[raw/blog.pypi.org/pypi-s-redesigned-project-pages-with-clearer-security-signals-are-now-15656|PyPI's redesigned project pages with clearer security signals are now live]] - [[raw/owasp.org/owasp-pygoat-699|OWASP PyGoat]] - [[raw/blog.gitguardian.com/how-to-handle-secrets-in-python-six-secure-patterns-15509|How to Handle Secrets in Python]] - [[raw/github.com/bentoml-ssti-via-unsandboxed-jinja2-in-dockerfile-generation-15849|BentoML GHSA-v959-cwq9-7hr6: SSTI via unsandboxed Jinja2]] - [[raw/github.com/lxml-default-iterparse-etcompatxmlparser-allows-xxe-to-local-files-15827|lxml GHSA-vfmq-68hx-4jfw: iterparse/ETCompatXMLParser XXE]] - [[raw/karthikupadrasta.medium.com/how-to-prevent-prompt-injection-in-python-llm-apps-6-layers-that-actua-15852|How to Prevent Prompt Injection in Python LLM Apps: 6 Layers]] - [[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]] - [[raw/medium.com/the-credential-was-valid-the-publisher-was-not-15854|The Credential Was Valid. The Publisher Was Not. (agent-framework)]] - [[raw/r3vpwnx.medium.com/loading-a-dataset-should-not-run-code-15851|Loading a Dataset Should Not Run Code (yt CVE-2026-132751)]] - [[raw/ssstrickys.com/fortipy-ssti-to-root-writeup-15855|FortiPy: SSTI to root writeup]]