Web Application and Django Security MOC
Hub for concepts, labs, runbooks, and case studies on web application security, Django hardening, bot mitigation, and availability protection.
┌────────────────────────────────────┐
│ Web Application & Django Sec MOC │
└─────────────────┬──────────────────┘
│
┌────────────────────────┬────────┴───────────────┬────────────────────────┐
▼ ▼ ▼ ▼
┌──────────────┐ ┌────────────────┐ ┌────────────────┐ ┌────────────────┐
│ Public Form │ │ Bot Mitigation │ │ Rate Limiting │ │ Labs, Posts & │
│ Abuse Risks │ │ & Honeypots │ │ & Proxy IPs │ │ Runbooks │
└──────────────┘ └────────────────┘ └────────────────┘ └────────────────┘
Core concepts
Availability & public endpoint risks
- Unprotected Public Form Risks - Synchronous SMTP DoS and Quota Exhaustion: why unauthenticated
POSTendpoints that trigger synchronoussend_mail()and DB writes risk SMTP quota lockouts, Gunicorn worker starvation (DoS), CRM pollution, and inbox fatigue. - Container Entrypoint Hardening and Gunicorn Worker Configuration: fail-fast
set -emigration checks, eliminating runtimecollectstatic --clearrace conditions, and scaling Gunicorn (--workers 3 --timeout 60 --access-logfile -) to mitigate single-worker starvation. - Non-Root Container Filesystem Ownership and Persistent Media Volumes: non-root
appuserdirectory ownership, persistentmedia_datavolumes forMEDIA_ROOT, and aligningCSRF_TRUSTED_ORIGINSwith host-mapped ports (8080:8000).
Bot mitigation & abuse prevention
- Form Honeypot Design and Silent Rejection: enticing field naming (
website), autofill/accessibility isolation (autocomplete="off",tabindex="-1",aria-hidden="true"), and why silent302redirects prevent bot adaptation. - Per-IP Rate Limiting Behind a Reverse Proxy in Django: taking the client IP from a header the proxy sets (
X-Real-IP) or the trusted proxy'sX-Forwarded-Forentry, never the forgeable first one, an atomic fixed-window counter withcache.add+cache.incr(429 Too Many Requests), and why rate limiting runs before honeypot checks.
Output encoding & XSS
- Rendering Untrusted Markdown with mark_safe Causes XSS: Markdown passes raw HTML and
javascript:links through, andmark_safe()disables Django's auto-escaping, so the pair turns stored text into script running in a staff session. - Sanitizing Markdown Output with an HTML Allowlist: convert, sanitize with
nh3(ammonia,html5ever), thenmark_safe(); what the default allowlist keeps, drops and empties, and what it still lets through (<img>). - Scriptless UI Redressing via Allowed class Attributes: an unrestricted
classlets attackers reuse site CSS (Tailwindfixed inset-0 z-50) for a fake login overlay; allowlist exact Pygments class names instead. - Escape HTML at Render Time, Not When Storing User Input:
escape()on input plus|safeon output holds only while every writer (admin, shell, migrations, APIs) escapes too, and stored entities leak into slugs (tom-amp-jerry) and exports; store raw text and let auto-escaping,format_html()or an allowlist sanitizer encode it.
Browser security model & tokens
- CSRF Works Because Browsers Attach Cookies to Requests Other Sites Trigger: cookies sent on cross-site requests, CSRF tokens,
SameSite,csrf_exemptandCSRF_TRUSTED_ORIGINS. - CORS Lets a Server Relax the Same-Origin Policy, It Does Not Protect the Server: preflights, allowed origins, why CORS isn't access control.
- A JWT Is Signed, Not Encrypted, So Anyone Can Read Its Payload: claims, pinned algorithms, expiry, where to store tokens.
- An App Behind a TLS-Terminating Proxy Builds http URLs Unless It Trusts Forwarded Headers: mixed content and forged
X-Forwarded-Forbehind a proxy.
Labs (02 - Sources/)
- Django Public Contact Form Hardening – Honeypot and Rate Limiting: defense-in-depth hardening of
POST /contact/with awebsitehoneypot, 5/hour per-IP cache rate limiting keyed onX-Real-IP, SMTP errors logged instead of shown, and 7 mockedsend_mailunit tests. - Django Markdown Rendering XSS Fix – nh3 Sanitization:
render_markdownfilter sanitized withnh3beforemark_safe(), class names limited to short Pygments-style tokens by a regex (exact set left as a follow-up), and 4 unit tests covering scripts, event handlers,javascript:links and class abuse. - Docker and Django Build and Runtime Hardening – Entrypoint, Multi-Stage Assets, and Compose Volumes: hardening
entrypoint.sh(set -e, Gunicorn 3 workers), multi-stage Tailwind CSS compilation beforecollectstatic,.dockerignoreisolation, and persistentmedia_datavolumes.
Runbooks (05 - SOPs & Manuals/)
- OWASP Top 10 2021 Reference: the ten risk categories with what to check in a Django or FastAPI app.
- Setup django-debug-toolbar in a dockerized app: configuring
INTERNAL_IPSacross Docker bridge networks without exposing debug tooling in production.
Post-mortems & case studies (06 - Posts/)
- Debugging Django Email with Gmail in a Dockerized App: multi-stage Dockerfile
ca-certificatesroot cause and TLS verification forsmtp.gmail.com:587.
Related maps
- Docker and Container Security MOC: container networking, port binding, and image supply-chain security for the underlying Docker Compose stack.
Open questions
- Should outbound email (
send_mail()) be offloaded from the synchronous HTTP request cycle to a background task queue (e.g., Celery, Django Q, or Django 6 background tasks)? Gunicorn now runs--workers 3 --timeout 60(see Container Entrypoint Hardening and Gunicorn Worker Configuration), which prevents a single slow SMTP response from freezing the site, but 3 concurrent slow SMTP calls can still saturate the worker pool. - Should rate-limit counters move to a shared cache such as Redis? Without a
CACHESsetting Django uses per-processLocMemCache, so each Gunicorn worker counts separately and every deploy resets the counters (see Per-IP Rate Limiting Behind a Reverse Proxy in Django). - Should edge rate limiting (Nginx
limit_req_zoneor Cloudflare WAF rules) be layered in front of Django's application-level cache counter? - Should Markdown-rendered user content allow
<img>at all? Anyhttps:image is a tracking pixel that reveals when staff open a message; droppingimgor proxying images would close it.
References
- OWASP Cross Site Scripting Prevention Cheat Sheet - Output encoding and HTML sanitization controls against XSS.
- Django Documentation: Security in Django - Built-in security protections and deployment hardening guidance for Django.
- OWASP Automated Threats to Web Applications - Ontology of automated bot threats (spamming, credential stuffing, resource exhaustion) and controls.