GuardAPI Logo
GuardAPI

Fix Command Injection in Django

Command injection in Django is a critical RCE vector that occurs when untrusted user input is passed directly to system shells. If you are using os.system, os.popen, or subprocess.run with shell=True, you are essentially providing a terminal to the internet. Real-world exploitation involves chaining commands via shell metacharacters like semicolon, ampersand, or backticks to hijack the underlying host.

The Vulnerable Pattern

import os
from django.http import HttpResponse

def check_network(request): target_ip = request.GET.get(‘ip’) # VULNERABLE: Direct string interpolation into a shell command # An attacker can send ?ip=127.0.0.1;cat /etc/passwd command = “ping -c 1 ” + target_ip os.system(command) return HttpResponse(‘Check initiated’)

The Secure Implementation

To kill command injection, you must break the shell's ability to interpret input as code. First, avoid os.system entirely; it is legacy and dangerous. Use the subprocess module with shell=False (the default). By passing arguments as a list (e.g., ['cmd', 'arg1']), the operating system treats the input as literal data, not executable instructions. Second, implement strict allow-listing or type-checking (like ipaddress validation) to ensure the input conforms to expected patterns before it ever touches a system call.

import subprocess
from django.http import HttpResponse
from django.core.exceptions import ValidationError
import ipaddress

def check_network(request): target_ip = request.GET.get(‘ip’)

# 1. Strict Input Validation
try:
    ipaddress.ip_address(target_ip)
except ValueError:
    return HttpResponse('Invalid IP', status=400)

# 2. Secure Execution: Use a list and shell=False
# This prevents the shell from interpreting metacharacters
result = subprocess.run(
    ['ping', '-c', '1', target_ip],
    capture_output=True,
    text=True,
    shell=False,
    check=True
)
return HttpResponse('Ping successful')</code></pre>
System Alert • ID: 1012
Target: Django API
Potential Vulnerability

Your Django API might be exposed to Command Injection

74% of Django apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.