Command injection, also called OS command injection, is a vulnerability in which an application passes untrusted input to an operating system shell, allowing an attacker to append or substitute commands that then run with the privileges of the application. In application security, it is classed as an injection flaw alongside SQL injection and SSTI, and it sits in the injection category of the OWASP Top 10.
The consequences are usually severe because the attacker does not merely read data through the application: they execute code on the host. A single vulnerable parameter can lead to full server compromise, credential theft, lateral movement inside the network and persistent backdoors.
How command injection reaches the shell
Command injection occurs when a program builds a command string by concatenation and hands it to a shell interpreter such as /bin/sh or cmd.exe. The shell does not know which characters came from the developer and which came from the user, so it interprets metacharacters in the input as syntax rather than as data.
A typical vulnerable pattern is a diagnostic page that runs ping -c 4 followed by a host name taken from a form field. If the user submits example.com; cat /etc/passwd, the semicolon terminates the intended command and the shell runs the second one. The output may be returned in the response, or the attack may be blind, producing no visible output at all.
The following table lists the shell metacharacters most often abused and what each one does to the command line.
| Metacharacter | Shell | Effect |
|---|---|---|
; | Unix shells | Runs a second command after the first |
&& and || | Unix and Windows | Runs a command conditionally on success or failure |
| | Unix and Windows | Pipes output into another command |
$( ) and backticks | Unix shells | Substitutes the output of an embedded command |
& | Windows cmd | Chains commands unconditionally |
Newline (%0a) | Unix shells | Starts a new command line |
Variants of command injection
Command injection appears in several forms that differ mainly in how the attacker observes the result. Recognizing the variant matters because it determines which detection techniques work during testing and which signals appear in logs.
| Variant | What the attacker sees | Typical detection technique |
|---|---|---|
| In-band injection | Command output in the HTTP response | Inject id or whoami and read the page |
| Blind time-based injection | Only a delayed response | Inject sleep 10 and measure latency |
| Out-of-band injection | A DNS or HTTP callback | Trigger nslookup to a controlled domain |
| Argument injection | Changed behavior of a legitimate binary | Supply options such as --output or -o |
| Second-order injection | Effect occurs later in a background job | Store a payload and wait for batch processing |
Argument injection deserves special attention because it survives some naive defenses. Even when no shell is involved, an input beginning with a hyphen can be parsed as an option of the called program, for example a tar or git flag that writes files or executes helpers. Placing -- before user-supplied arguments tells most utilities to stop option parsing.
How it differs from related injection flaws
Command injection shares its root cause with other injection flaws: data and code mixed in one string. The interpreter that receives the string, however, defines the impact. The table compares it with the neighboring vulnerabilities that are often confused with it.
| Vulnerability | Interpreter targeted | Typical impact |
|---|---|---|
| Command injection | Operating system shell | Arbitrary commands on the host |
| SQL injection | Database query engine | Data theft or modification |
| SSTI | Server-side template engine | Often escalates to code execution |
| Code injection | Language runtime such as eval | Arbitrary code in the application process |
| Path traversal | File system path resolution | Reading or writing unintended files |
The distinction between command injection and code injection is subtle but practical. Code injection runs attacker input as source code of the application language, while command injection runs it as separate operating system processes. Both frequently end in remote code execution, which is why scanners and advisories sometimes group them together.
Preventing command injection in code
The most reliable defense is to avoid calling the shell at all. Most tasks that developers delegate to command-line tools, such as resizing images, resolving host names or compressing files, have native library equivalents that accept structured parameters and never invoke an interpreter.
When an external program is unavoidable, it should be started through an API that takes an argument array instead of a string, such as subprocess.run([...], shell=False) in Python, execFile in Node.js or ProcessBuilder in Java. The operating system then passes each argument directly to the program, so metacharacters lose their special meaning. The table below summarizes the layered controls in order of strength.
| Control | Protection offered | Limitation |
|---|---|---|
| Native library call | Removes the shell entirely | Requires refactoring |
| Argument array, no shell | Blocks metacharacter parsing | Argument injection still possible |
| Allowlist input validation | Rejects unexpected characters and values | Must be strict and context-specific |
| Shell escaping functions | Quotes input for one shell | Error-prone across shells and encodings |
| Least privilege and sandboxing | Limits damage after compromise | Does not prevent the injection |
Input validation should be an allowlist, for example a regular expression that accepts only a host name or an IPv4 address, never a denylist of dangerous characters. Denylists routinely miss encoding tricks, alternative separators and platform differences between Unix shells and Windows cmd.exe.
Detection, testing and common mistakes
Command injection is found through code review, static analysis and dynamic testing. Static analysis tools trace tainted data from request parameters to sinks such as system(), exec(), popen() or Runtime.exec(). Dynamic scanners send time-based and out-of-band payloads, because blind injection produces no visible error.
At runtime, defenders look for unexpected child processes spawned by web servers, such as a PHP or Java process launching sh, curl or powershell. Endpoint detection rules, RASP agents and container security policies can block or alert on this behavior. The most frequent developer mistakes are listed below.
- Escaping instead of separating: quoting input for one shell and then running it under another.
- Trusting internal sources: file names, uploaded metadata and queue messages can all carry payloads.
- Forgetting argument injection: a value starting with a hyphen still changes program behavior.
- Running as root: an injected command inherits every privilege of the application account.
- Relying on a web application firewall alone: encoding and obfuscation regularly bypass signature rules.
Explained without jargon
Imagine a receptionist who reads written notes aloud to a building manager. A visitor is supposed to write only a room number, but writes “Room 12, and also open the safe”. If the receptionist reads everything without thinking, the manager obeys the whole note.
Command injection works the same way. A website asks for a small piece of information and passes it to the computer’s command system. If the website does not keep the visitor’s words separate from its own instructions, the visitor can give the server orders. The fix is to keep user data and commands strictly apart, so typed text is always treated as data and never as an instruction.
A typical use case
A network equipment vendor ships a router with a web administration panel that includes a ping test. The panel builds the command ping -c 3 plus the address typed by the administrator and runs it through /bin/sh. During a penetration test, the tester submits 8.8.8.8; sleep 10, and the page takes about ten seconds longer to respond, confirming blind time-based injection.
The tester then triggers a DNS lookup to a controlled domain to prove out-of-band execution and reports the issue as critical, since the web service runs as root. The vendor rewrites the feature to validate the input as an IP address and to call the ping binary with an argument array and no shell. A retest with the same payloads shows no delay and no callback, and the firmware update closes the path that would have allowed full device takeover.