How to Fix Command Injection in Django
Learn how to prevent and fix Command Injection vulnerabilities in Django applications. Step-by-step guide with code examples, security checklists, and best practices.
What Is Command Injection?
Command Injection (also known as OS Command Injection or Shell Injection) occurs when an application passes user-supplied input to a system shell for execution. An attacker can inject shell metacharacters to append or modify the intended command, executing arbitrary commands on the server with the application's privileges.
The vulnerability typically arises when applications use functions like `child_process.exec()`, `os.system()`, or `Runtime.exec()` with user-controlled input. Shell metacharacters such as `;`, `&&`, `||`, `|`, and backticks allow command chaining or substitution. For example, if an application runs `ping -c 1 <user_input>` and the user provides `google.com; cat /etc/passwd`, both commands execute.
In Node.js applications, command injection is possible through `child_process.exec()` (which spawns a shell) and `child_process.execSync()`. It can also occur indirectly through libraries that shell out to system commands (e.g., image processing tools, PDF generators, or build tools that invoke shell commands). Server-side applications that interact with the operating system for tasks like file conversion, image manipulation, or system monitoring are particularly at risk.
Why It Matters
Command injection is one of the most severe vulnerabilities because it gives attackers direct access to the server's operating system. An attacker can read or modify any file the application has access to, install backdoors and malware, pivot to other systems on the network, exfiltrate data, launch attacks against other targets, and potentially gain root access through privilege escalation. Because the commands execute with the application's permissions, the impact depends on the application's privilege level -- but even unprivileged access can be devastating.
How to Fix It in Django
Avoid executing OS commands based on user input whenever possible. Use language-native libraries instead of shelling out (e.g., use Node.js `dns.lookup()` instead of spawning `ping`). When shell execution is unavoidable, use `child_process.execFile()` or `child_process.spawn()` which do not invoke a shell and pass arguments as arrays. Never pass user input through `child_process.exec()`. Validate input against strict allowlists (e.g., only allow alphanumeric characters for hostnames). Escape shell metacharacters if you must include user input in commands. Run the application with minimal OS privileges. Use containerization and sandboxing to limit the blast radius.
Django-Specific Advice
- Django's template engine auto-escapes HTML by default. Never use the `|safe` filter or `mark_safe()` with unsanitized user input.
- Use Django's ORM for all database queries. When raw SQL is needed, always use parameterized queries: `cursor.execute('SELECT ... WHERE id = %s', [user_id])`.
- Keep Django's CSRF middleware enabled. Use `{% csrf_token %}` in all forms and configure CSRF for AJAX requests.
- Set `DEBUG = False` in production. Debug mode exposes detailed error pages with sensitive information.
Django Security Checklist for Command Injection
Django Security Best Practices
Django's template engine auto-escapes HTML by default. Never use the `|safe` filter or `mark_safe()` with unsanitized user input.
Use Django's ORM for all database queries. When raw SQL is needed, always use parameterized queries: `cursor.execute('SELECT ... WHERE id = %s', [user_id])`.
Keep Django's CSRF middleware enabled. Use `{% csrf_token %}` in all forms and configure CSRF for AJAX requests.
Set `DEBUG = False` in production. Debug mode exposes detailed error pages with sensitive information.
Use Django's built-in password hashing (PBKDF2 by default) and never implement custom password storage.
Configure `SECURE_SSL_REDIRECT`, `SECURE_HSTS_SECONDS`, `SESSION_COOKIE_SECURE`, and `CSRF_COOKIE_SECURE` in production settings.
Use `django-ratelimit` or Django REST Framework's throttling for rate limiting on authentication and API endpoints.
Keep `SECRET_KEY` secret and unique per environment. Rotate it if it is ever exposed.
Scan Your Django App with SafeVibe
Stop guessing if your Django app is vulnerable to Command Injection. Run an automated penetration test in minutes and get actionable results.
Start Free Scan