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. Aikido, healeycodes
  • Convenience defaults. **kwargs forwarding into ORMs, yaml.load, stdlib XML parsers, tarfile.extractall, debug=True, and frameworks that rebuild URLs from Host. 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. 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(). 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. 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. 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. 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 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:

SinkSafer pattern
eval/exec/compileast.literal_eval() or no evaluation
subprocess.*(..., shell=True), os.systemargv list with shell=False, which still allows Argument Injection
pickle/dill/jsonpickle/shelve/marshalJSON 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 defaultdefusedxml; 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 templatesRestrict Formatter.get_field(); PEP 750 t-strings
tempfile.mktemp(), assert for authz, == on secrets, verify=Falsemkstemp(), explicit raise, secrets.compare_digest(), real TLS

Snyk code injection, Snyk command injection, Semgrep, t-strings, 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(). 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. 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. stackurity, 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. Casino walkthrough, 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. 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. 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. AWS MCP, Redash, CrewAI, Langflow, 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. 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"]. BadHost

  • Flask. debug=True, no built-in CSRF (use Flask-WTF CSRFProtect), and the Flask-Admin FileAdmin startswith(base_path) sibling-prefix traversal. Snyk Flask, Flask-Admin

  • FastAPI. /openapi.json, /docs and /redoc are on by default. Set docs_url=None in production. FastAPI attacks

  • aiohttp CVE-2026-34519 (< 3.13.4). CRLF in Response(reason=...) causes response splitting. 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).
    • 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.

    ERPNext SQLi (sort), ERPNext SQLi (Selling/Buying), Frappe IDOR, Frappe SSRF, 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. Ostorlab, safeguard.sh, pin the algorithm

AI and ML frameworks

Details in Python AI and ML Framework Vulnerabilities.

CaseWhat 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-64849Full-read webhook SSRF
SGLang CVE-2026-5760GGUF chat_template SSTI
NeMo / Uni2TSHydra _target_ from model metadata
XoscarDeserialization 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. six layers

Marimo, LangChain, MLflow, SGLang, Unit 42, Xoscar, 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. agent-framework check, VeritasChain
    • A .pth file in site-packages runs on every interpreter start (LiteLLM 1.82.8 litellm_init.pth). Any line beginning with import executes before the user’s script; the agent-framework variant then fork()+setsid()’d a detached collector so the parent showed no delay. Elastic
    • setup.py overriding the install command (instantscrape 0.1.5/0.1.8 ran an embedded infostealer executable; MAL-2026-20322). GHSA
    • 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. Wiz TeamPCP, 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. 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. agent-framework check
    • pip 26.1 dependency cooldowns and experimental PEP 751 pylock.toml.
    • Malware feeds are noisy on PyPI: a re-measurement read 72.7–77.3% of Amazon Inspector’s PyPI malware records as benign, PyPI acted on 0 of 12 packages the researchers read as malicious, and nine reported packages were still served six days later. Treat a feed hit as a lead to read, not a verdict. modelmarket.dev
    • uv lockfiles with hashes.
    • Upgrade certifi ≥ 2026.10.19 and pip ≥ 26.2.2 after the eMudhra/emSign CA compromise.

    InfoQ pip 26.1, 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.

    Bishop Fox, 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. GitGuardian

Tools

NeedTool / command
Pattern SASTbandit -r src/ --severity-level high; baseline with -f json -o baseline.json then -b baseline.json; -f sarif for code scanning
Taint across modulesSemgrep (12+ deser libraries), CodeQL, Pyre/Pysa, Bearer
JOSE misconfiggrep -rnE "algorithms\s*=\s*\[.*HS[0-9]+.*(RS\|ES\|PS\|EdDSA)" --include=*.py .; grep -rn "jwt.decode\|jws.verify" --include=*.py .
Sink grepsshell=True, pickle.load, yaml.load(, allow_pickle=True, torch.load(, instantiate(, render_template_string, \.objects\.(filter\|exclude\|get)\(\*\*, request.url.path in middleware
Versionspip show arize-phoenix pyjwt python-jose, pip freeze \| grep -i jose
Package triageguarddog pypi scan <pkg> --version <v>; PyPI security tab
Dependency auditpip-audit, CycloneDX SBOM, uv hash-pinned lockfiles
Pickle scannerspicklescan, Fickling, modelscan (bypassed repeatedly, so not a boundary)
TrainingOWASP PyGoat (Django)

appsecsanta, Bandit guide, bito, GuardDog, picklescan bypass, 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. 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. Endor Labs
  • Starlette CVE-2026-48710 (BadHost): Host-derived path desync bypasses path-based authz. korben
  • Arize Phoenix CVE-2026-53998: format-string leak of PHOENIX_SECRET, CVSS 10. stackurity
  • python-jose CVE-2026-120459: empty HMAC key forgery, unpatched. Ostorlab
  • OpenShot CVE-2026-134704: .osp project file goes to pickle.load(). GHSA
  • ERPNext CVE-2026-134372 / CVE-2026-134431: authenticated SQLi leading to session data and admin takeover. GHSA, GHSA
  • Frappe CVE-2026-134371: IDOR leaking Contact phone numbers. GHSA
  • pydantic-ai GHSA-5fj9-5pjw-vpwc: SSRF guard missed Tencent metadata. GHSA
  • RunSybil CPython 0-day: Jinja ImmutableSandboxedEnvironment escape via a model chat template in vLLM. RunSybil
  • Marimo CVE-2026-39987: pre-auth terminal WebSocket, CISA KEV. THN
  • AWS MCP run_script: AST validator bypass, with blast radius contained by a deny-all role. xplo1t
  • LiteLLM 1.82.7/1.82.8 (TeamPCP): import-time and .pth payloads. Wiz
  • Ultralytics 8.3.41/8.3.42: GitHub Actions branch-name injection leading to XMRig. Wiz
  • Labs: Casino (Flask SSTI via render_template_string) and Poet (LFI, then forged cookie, then Jinja2 SSTI). Casino, Poet
  • BentoML GHSA-v959-cwq9-7hr6: malicious bento archive’s Dockerfile template gives host RCE on containerize. GHSA
  • lxml < 6.1 GHSA-vfmq-68hx-4jfw: iterparse()/ETCompatXMLParser() default XXE to local files. GHSA
  • yt CVE-2026-132751: eval() on a stored HDF5 attribute during yt.load(). r3vpwnx
  • Microsoft agent-framework 1.26.1/1.26.2: .pth credential stealer from a valid publisher credential. VeritasChain; flagged six minutes after publish, minted CI OIDC and IMDS tokens. Elastic
  • instantscrape (PyPI, Nov 2026): setup.py install override drops an infostealer that exfiltrates files. GHSA-wqr9-48cj-55gj
  • PyJWT USN-9177-1: non-canonical signature-segment encodings accepted, possibly bypassing token revocation checks. Ubuntu
  • FortiPy lab: blacklist-filtered Jinja2 SSTI bypassed with \xNN escapes, root via the app running as PID 1. 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

Related pages in other topics:

See also: Path Traversal · Zip Slip and Archive Extraction

Sources