# Python Web Framework Security
> Framework-specific failure modes in Django, Flask, FastAPI/Starlette, aiohttp and Frappe. Most real bugs sit where a framework convenience (kwargs expansion, reconstructed URLs, debug mode, unsafe renderer defaults) meets untrusted input.
## How it works
Python frameworks ship safe defaults: ORM parameterization, template autoescape, Django CSRF middleware. Bugs concentrate in:
- **Convenience APIs that forward user dicts**: `Model.objects.filter(**request.GET.dict())`.
- **Derived request values used for authz** that differ from what the router dispatches on.
- **Unsafe renderer and helper defaults**: Docutils directives, email HTML inliners, file-admin path checks.
- **Production misconfiguration**: `DEBUG=True`, a weak or committed `SECRET_KEY`, exposed OpenAPI docs.
## Techniques / patterns by framework
### Django
- **CVE-2025-64459 (CVSS 9.1)**: `filter()`, `exclude()` and `get()` with `**kwargs` from the request let an attacker inject the internal `Q` parameters `_connector` and `_negated`:
```python
User.objects.filter(**request.GET.dict()) # ?_connector=OR&is_superuser=True
```
Impacts are auth bypass, cross-owner reads and inverted permission checks. Fixed in 5.2.8, 5.1.14 and 4.2.26 via `PROHIBITED_FILTER_KWARGS`. Hunt for any kwargs expansion of request data into QuerySets and look for `_connector`/`_negated` in logs. See [[ORM Injection]].
- Raw SQL: `objects.raw("... '%s'" % u)` is injectable; `objects.raw("... %s", [u])` is not. Bandit flags `extra()` and `mark_safe`.
- Hardening settings: `SECURE_SSL_REDIRECT`, `SESSION_COOKIE_SECURE`, `CSRF_COOKIE_SECURE`, `SECURE_CONTENT_TYPE_NOSNIFF`, `SECRET_KEY` from the environment. Django 4.1 deprecated `PickleSerializer` for sessions. Don't re-enable it ([[Python Pickle Deserialization]]).
- Ecosystem bugs: **django-tenants** 3.4.8–4.0.0 put unescaped schema names into `SET search_path` (GHSA-pg64-4qv2-75g5). **DjangoBlog** comment sanitizer allowed `autofocus`/`onfocus` on `div` (CVE-2026-129155, [[Stored XSS]]). **django-docutils** < 0.30.0 enabled reST `include`/`raw` directives and unsafe URI schemes, giving local file read, SSRF and XSS. **Pytition** < 2.10 let any user delete signatures by sequential ID ([[Insecure Direct Object Reference|IDOR]], CVE-2026-130872).
### Flask
- `debug=True` in production exposes detailed errors and internal application state. Bandit `flask_debug_true` catches it.
- No built-in CSRF: use Flask-WTF `CSRFProtect` with `{{ csrf_token() }}`. Regenerate the session on login to prevent fixation.
- **Flask-Admin `FileAdmin` traversal**: the jail check `normpath(dir).startswith(base_path)` accepts sibling directories that share a prefix (`/data/uploads_secret` vs `/data/uploads`). This affected download, rename and delete. Note that browsers normalize `../`, so test with a raw client.
- **Flask Ninja gadget**: a pickled `HttpBearer` subclass with `header` retargeted to a proxy-injected header (e.g. `Proxy-Token`) makes the app reflect internal headers if it unpickles and calls attacker data. The report was closed "informative" as a gadget rather than a standalone bug.
- **`render_template_string` on concatenated input** (FortiPy lab): a blacklist in front of the sink was bypassed with Jinja string escapes, `{{ config }}` leaked `SECRET_KEY`, and the key minted a `role: admin` session cookie through Flask's `SecureCookieSessionInterface`, opening an admin route that dumped credentials. The process ran as root. Pass input as a template variable, load `SECRET_KEY` from the environment, and never authorize on a client-signed role alone. See [[Jinja2 SSTI]] [[raw/ssstrickys.com/fortipy-ssti-to-root-writeup-15855|FortiPy]].
### FastAPI / Starlette
- **BadHost (CVE-2026-48710)**: Starlette rebuilds `request.url` from the unvalidated `Host` header plus the path and then re-parses it. A `/`, `?` or `#` in Host shifts the path boundary, so middleware reading `request.url.path` sees a different path than the router dispatches:
```
Host: foo GET /admin -> 403
Host: foo? GET /admin -> 200
```
This affects FastAPI, vLLM, LiteLLM and MCP servers on bare uvicorn, hypercorn or granian. Fixed in Starlette ≥ 1.0.1. Make security decisions on `request.scope["path"]`. nginx, Apache and Cloudflare reject the PoC by default, but verify your own proxy config. See [[Host Header SSRF]] for the broader Host-trust class.
- `/openapi.json`, `/docs` and `/redoc` are on by default and enumerate admin routes and fields like `is_admin`. Disable them in production (`docs_url=None`). See [[API Discovery]] and [[Mass Assignment]].
### aiohttp
- **CVE-2026-34519** (< 3.13.4): CRLF in a user-controlled `Response(reason=...)` causes response splitting (CWE-113), leading to header injection, cache poisoning and XSS.
- **ZDI-26-897 / CVE-2026-91131**: SSRF in Home Assistant's `aiohttp_client` (Pwn2Own).
### Frappe / ERPNext
- **CVE-2026-130069**: unescaped email templates let a portal user inject `<link rel=stylesheet>`. Premailer then fetches internal hosts and inlines the content (full-read SSRF).
- **Frappe Builder** < 1.36.1: the SSRF guard was bypassed via redirect chains and DNS rebinding to `100.100.100.200`. The fix re-checks the address on every hop.
- SSTI via user-controlled message fields. **india-payroll** < 16.0.4 had whitelisted methods with no per-employee authz.
### Auth plugins
- **social-auth-core** SAML login CSRF: an unsigned `RelayState` isn't correlated to the initiating session (GHSA-4pv2-52v7-vrfx for 4.7.0–6.2.0; CVE-2026-126775 fixed in 7.0.0). See [[SAML Attacks]].
- JWT verification in DRF and Flask: see [[Python JWT Library Vulnerabilities]].
## Testing checklist
1. Fingerprint the framework, then pull `/openapi.json` (FastAPI) and look for the debug page (Flask/Werkzeug, Django `DEBUG`).
2. List/search endpoints: add `_connector=OR` and `_negated=True` (Django) and ORM lookups (`field__startswith`).
3. Path-based admin gates: retry with `Host: x?` and `Host: x/` against Starlette apps.
4. File managers: sibling-prefix directories, not just `../`.
5. Anything that fetches or renders (email HTML, reST/Markdown, importers): SSRF and file read, including redirects and rebinding.
For training labs, OWASP **PyGoat** is an intentionally vulnerable Django app covering the OWASP Top 10 (SQL, ORM and OS command injection, sensitive data exposure, debug mode) with fixes.
## Related
- [[Python Security]]
- [[Unsafe Python Functions]]
- [[Python JWT Library Vulnerabilities]]
- [[Python SAST Tools]]
- [[Jinja2 SSTI]]
- [[SQL Injection]]
- [[ORM Injection]]
- [[Cross-Site Request Forgery]]
- [[Broken Access Control]]
- [[Server-Side Request Forgery]]
- [[DNS Rebinding]]
## Sources
- [[raw/endorlabs.com/critical-sql-injection-vulnerability-in-django-cve-2025-64459-4814|Critical SQL Injection Vulnerability in Django (CVE-2025-64459)]]
- [[raw/corgea.com/django-security-best-practices-a-comprehensive-guide-for-software-engi-5253|Django Security Best Practices (Corgea)]]
- [[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/eval.blog/leaking-internal-headers-in-flask-ninja-with-deserialization-10658|Leaking internal headers in Flask Ninja with deserialization]]
- [[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/korben.info/badhost-one-character-and-your-ai-agent-switches-sides-9901|BadHost: one character and your AI agent switches sides]]
- [[raw/sentinelone.com/cve-2026-34519-aiohttp-xss-vulnerability-2982|CVE-2026-34519: AIOHTTP response splitting]]
- [[raw/dedsec-terminal.github.io/zdi-26-897-pwn2own-home-assistant-green-aiohttp-client-ssrf-13895|ZDI-26-897: Home Assistant aiohttp_client SSRF]]
- [[raw/github.com/django-tenants-sql-injection-in-postgresql-backend-14912|django-tenants SQL injection in PostgreSQL backend]]
- [[raw/github.com/djangoblog-stored-xss-14493|DjangoBlog stored XSS]]
- [[raw/github.com/django-docutils-unsafe-defaults-local-file-disclosure-ssrf-and-stored-15320|django-docutils unsafe defaults]]
- [[raw/github.com/pytition-idor-15027|Pytition IDOR]]
- [[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-possibility-of-server-side-template-injection-12640|Frappe possibility of SSTI]]
- [[raw/github.com/frappe-india-payroll-missing-authorization-14670|Frappe india-payroll missing authorization]]
- [[raw/github.com/social-core-login-csrf-in-saml-callbacks-via-relaystate-15352|social-core: login CSRF in SAML callbacks via RelayState]]
- [[raw/github.com/social-auth-core-login-csrf-14377|social-auth-core login CSRF]]
- [[raw/speakerdeck.com/pygoat-learn-django-security-the-hard-way-speaker-deck-2065|Pygoat: Learn Django security the hard way]]
- [[raw/ssstrickys.com/fortipy-ssti-to-root-writeup-15855|FortiPy: SSTI to root writeup]]