Command injection

Also known as: OS command injection

On this page 7

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.

MetacharacterShellEffect
;Unix shellsRuns a second command after the first
&& and ||Unix and WindowsRuns a command conditionally on success or failure
|Unix and WindowsPipes output into another command
$( ) and backticksUnix shellsSubstitutes the output of an embedded command
&Windows cmdChains commands unconditionally
Newline (%0a)Unix shellsStarts a new command line
Common shell metacharacters used in command injection

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.

VariantWhat the attacker seesTypical detection technique
In-band injectionCommand output in the HTTP responseInject id or whoami and read the page
Blind time-based injectionOnly a delayed responseInject sleep 10 and measure latency
Out-of-band injectionA DNS or HTTP callbackTrigger nslookup to a controlled domain
Argument injectionChanged behavior of a legitimate binarySupply options such as --output or -o
Second-order injectionEffect occurs later in a background jobStore a payload and wait for batch processing
Main variants and how they are detected

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.

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.

VulnerabilityInterpreter targetedTypical impact
Command injectionOperating system shellArbitrary commands on the host
SQL injectionDatabase query engineData theft or modification
SSTIServer-side template engineOften escalates to code execution
Code injectionLanguage runtime such as evalArbitrary code in the application process
Path traversalFile system path resolutionReading or writing unintended files
Command injection compared with related vulnerabilities

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.

ControlProtection offeredLimitation
Native library callRemoves the shell entirelyRequires refactoring
Argument array, no shellBlocks metacharacter parsingArgument injection still possible
Allowlist input validationRejects unexpected characters and valuesMust be strict and context-specific
Shell escaping functionsQuotes input for one shellError-prone across shells and encodings
Least privilege and sandboxingLimits damage after compromiseDoes not prevent the injection
Defensive controls ranked by effectiveness

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.