# Audit Django and Python web code for security vulnerabilities

> Find exploitable flaws in Django views, settings, templates and dependencies, with exact lines.

Load this first for ANY security review, code audit, vulnerability scan, pentest, threat model or "find the security issues / bugs" request on Python web code - Django, Django REST framework, or a requirements.txt / pyproject.toml - before reading the code. An expert audit brief - where Django code steps outside its secure defaults, per-view access and ownership, cross-file data flow, token and session lifecycle, settings.py, exposed internals and a PyPI advisory table for Django and 35 common packages - for finding injection (SQL, command, code, template), XSS (|safe, mark_safe, autoescape off), SSRF, XXE, path traversal and unsafe uploads, open redirects, pickle and YAML deserialization, broken auth and sessions, weak reset tokens, IDOR and missing authorization, ModelForm / serializer mass assignment, CSRF (csrf_exempt, state change on GET), DEBUG and data exposure and vulnerable dependencies, with a strict false-positive bar.

- Page: https://ss33.ai/skills/skillstore33/django-security-64834338564
- Publisher: skillstore33
- Category: [Security](https://ss33.ai/skills/category/security-w9g95g) › [Application security](https://ss33.ai/skills/category/security-w9g95g/application-security-6s8pr9)
- License: MIT

## Skill

SKILL.md: https://ss33.ai/api/v1/ss33/download/skillstore33/django-security-64834338564

# Django security audit

The bar: every exploitable flaw, at the exact lines, and nothing that isn't there. You know the vulnerability classes. This brief is about what strong auditors still miss on Django code and how the report is judged.

## References (optional depth)

- `read_skill_file("django-security", "references/patterns.md")`: sink shapes, safe forms and CWE per class in Django, the settings checklist with the CWE per setting. Open it if you are unsure of a CWE or a setting's safe value.
- `read_skill_file("django-security", "references/advisories.md")`: one line per PyPI advisory for Django, its dependencies and 35 common packages. **Open it whenever there is a requirements file**: version ranges are not something to recall from memory.

## The organising idea

Django is secure by default: the ORM parameterises, templates auto-escape, `CsrfViewMiddleware` checks unsafe methods, `login()` rotates the session. Almost every Django vulnerability is a **step outside a default**: raw SQL, `|safe` / `mark_safe`, `@csrf_exempt`, a view without `@login_required`, an object fetched by id without the user in the query, a `ModelForm` with `exclude`, a setting moved off its safe value. Hunt for the steps, then decide whether an attacker can use each one. The same idea sets the false-positive bar: where the default still applies, there is nothing to report.

## Where audits lose findings

**Access is per view, per method, per object.** Build an access table from the URLconf (every `include`, DRF routers), one row per routed view: login, role, object scoped to the user, methods, what it returns. Fill it from the code, not the view name. File upload and download views, exports, API, admin, settings and status views are rows too. Commonly missed:
- Write paths (edit, delete, toggle, upload into a project id) checked less than reads; a download that loads a file record by id and streams it without an owner check.
- "Ownership" checks that only verify two URL ids belong together; the attacker chooses both.
- Role checks on GET only, or only in the template; `has_perm("codename")` without the `app_label.` prefix (always False except for superusers: a broken check).
- `if request.user.is_authenticated:` that wraps one branch and falls through to the action.
- `@csrf_exempt` on state-changing views (one finding listing all of them, even where the view has worse flaws), and state changes on GET, which `CsrfViewMiddleware` never checks.

**Mass assignment hides in deny-lists.** `ModelForm` with `exclude` on `User` leaves `is_superuser`, `is_staff`, `groups` settable; `fields = "__all__"` on models with role or owner fields; `ModelSerializer` with writable `owner` / `is_staff`; `Model(**request.POST.dict())`; `request.POST.get` after `is_valid()` bypasses `cleaned_data`.

**Cross-file flow.** A name a user stores (upload `.name`, title, username) is attacker data at every later step: a path (traversal), a shell command (injection), a template with `|safe` (stored XSS). Each is its own finding. Sanitizers or checks applied in one of two views writing the same field are a finding on the other. `int()` protects SQL, not a file name. `cursor.execute("... '%s'" % x)` versus `cursor.execute("... %s", [x])` is one character: read the line.

**Templates are a sweep, not a sample.** Every `|safe`, `|safeseq`, `{% autoescape off %}`, `mark_safe`, `format_html` with an f-string, global `autoescape: False`, Jinja2 without autoescape, `{{ x }}` in `<script>`, unquoted attributes or `href` / `src`. One finding per mechanism listing every template line, each marked stored or reflected.

**Request and environment dumps.** Views or templates printing `request.META` (under WSGI it carries the server's environment variables, secrets included), `settings`, `os.environ`, `vars(request)` or `{% debug %}` are exposure findings with or without login, at the view and at the template line.

**Settings are line-by-line findings.** Each wrong value is its own finding at its line, and interacting settings are separate findings: `SESSION_SERIALIZER = PickleSerializer` (code execution for anyone holding or forging the key) and `SESSION_ENGINE = signed_cookies` (client-held, unrevocable, replayable sessions) are two. Also `DEBUG`, literal `SECRET_KEY`, `ALLOWED_HOSTS`, cookie flags, weak hashers first in `PASSWORD_HASHERS`, missing `AUTH_PASSWORD_VALIDATORS`, missing security middleware, CORS with credentials, DRF `AllowAny` defaults and no throttles.

**Absence is a finding.** If no rate limiting exists anywhere in the project (axes, ratelimit, DRF throttles, cache counters, lockout fields), "no brute-force protection" is one finding at the login view with the reset-token, OTP and password-change views as further locations, separate from enumeration or injection in the same view.

**Tokens have a lifecycle.** For reset codes, invites, signed links, API tokens, vouchers and sessions: guessable (short numeric codes, `random`, `uuid1`, time or user-id derived), bound to the right user, consumed atomically, expiring, revoked on password change and logout, checked identically on list / export / API / admin paths. Each failure is a separate finding.

**Dependencies.** Judge each requirement by its pin or the oldest version its specifier allows (no specifier: don't report). One finding per package at its requirements line, naming the package, the version and the advisory ids the app actually exercises (redirect bypasses if it redirects on user input, CSRF bypasses, host-header issues when DEBUG is on). An end-of-life Django series is a finding in itself; put it in the same Django finding as its advisories.

## False-positive bar

Report a candidate only when the input is attacker-controlled (including stored data from other users), nothing neutralises it for this sink, and the code is reachable from a routed view. An ORM `filter()` / `get()` with a value, `{{ x }}` in element text with autoescape on, a POST view under `CsrfViewMiddleware` without `@csrf_exempt`, and a query scoped to `request.user` are not findings. **Low impact is not a reason to drop**: enumeration, missing HttpOnly, sessions surviving a reset, verbose errors go in at low or medium.

## Report contract

Use exactly the output format the request asks for, written straight from your findings with no prose report around it. When it asks for a JSON array of `title`, `cwe`, `severity`, `locations` (`[{"file", "lines": [first, last]}]`), `detail`, `fix`, end the answer with that array in one ```json block.

- One finding per distinct flaw, listing every location of that same flaw (every `@csrf_exempt`, every view of one IDOR family). Different flaws at one place are separate findings (SQL injection and missing authorization in one view: two). A broad finding covering several flaws is credited as one.
- Locations: the path exactly as given; tight line ranges at the sink, the view missing the check, the template line, the settings line or the requirements line.
- CWE: the most specific id.
- Severity: critical = code/command execution, authentication bypass, privilege escalation to admin, account takeover; high = other users' data readable or writable, stored XSS, SQL injection, SSRF, XXE, path traversal, guessable reset tokens; medium = reflected XSS, CSRF, open redirect, business-logic abuse, session weaknesses, DEBUG and exposed internals, weak password hashing, vulnerable dependencies; low = headers, user enumeration, information leaks.
- Large codebases have dozens of findings. Keep a running one-line-per-finding list as you go so nothing found during analysis is missing from the final array.
