Weaknesscore
OS command injection
Also called command injection, shell injection, cwe-78.
OS command injection happens when a program puts outside input into a command line that a shell parses, so the shell reads part of the input as more commands or options.
- CWE
- CWE-78
- Abstraction
- base
- OWASP Top 10 (2025)
- A05
- CWE Top 25 (2025)
- rank 9
- Languages affected
- any-that-starts-processes
Description
A program that needs another program can start it in two ways. It can give the operating system the path of the program and a list of arguments. Or it can give a shell one line of text and let the shell parse it. The shell language has its own syntax: ;, &&, | and a newline end a command, $( ) and backquotes run a command, > writes a file, and spaces split arguments. OS command injection happens when the program builds the line from fixed text and input from outside. When the input holds one of these characters, the shell reads it as syntax. The program meant one command with one argument. The shell runs what the line says.
The root cause is again that code and data share one channel. The developer knows that the input is one argument, but the string does not keep this knowledge. The fix is to keep the list of arguments as a list all the way to the operating system (see Fixed code).
The new command runs with the rights of the program, so the attacker can read or change any data that the program can, or stop the system. The commands also appear to come from the program and its owner.1 On a web server, this often means control of the server.
CWE-78 names this weakness. It is a base weakness under CWE-77, command injection, and its alternate terms are shell injection and shell metacharacters.1 CWE-78 describes two forms. In the first, the program runs a fixed program and the input is an argument, as in system("nslookup [HOSTNAME]"). In the second, the input selects the program or the whole command.1 It is rank 9 of the 2025 CWE Top 25, and with 20 CVEs in the CISA catalogue of known exploited vulnerabilities, it has more of them than any other weakness on the list.3 In the OWASP Top 10:2025 it is part of A05:2025 Injection.2
History
On 14 March 1996, AUSCERT published advisory AA96.01 about the example CGI code of the NCSA and Apache web servers, and CERT/CC reprinted it on 20 March as CA-1996-06.4 The code had a function, escape_shell_cmd, that tried to make input safe for system and popen. The advisory said that any program that relied on it could be attacked, and that the phf program, which came with both servers, was being actively exploited.4 A later CERT/CC note explains the bug. phf built a command line with strcat and passed it to popen. escape_shell_cmd put a backslash before &, ;, |, $ and other characters, but not before a newline, and a newline also ends a shell command.5 The note says that phf was widely exploited in 1996 and 1997.5 The lesson is that a list of dangerous characters is never complete.
Argument injection
An argument list stops a second command. It does not stop a value from becoming an option of the program. A value that starts with - can turn on a feature that the program did not mean to use. The OWASP cheat sheet shows curl with the value --help.6 CWE-88 names this weakness. For commands that support it, put -- before the values to end option parsing, and check that a value does not start with -.6
Vulnerable code
The function below builds a shell command line with +. The second call uses the classic demonstration input report.txt; echo INJECTED. The ; ends the first command, and the shell runs echo INJECTED as a second command.
This code runs but gives a wrong answer on purpose.
import subprocess
def look_up(name):
subprocess.run("echo looking up " + name, shell=True)
look_up("report.txt")
look_up("report.txt; echo INJECTED")
looking up report.txt
looking up report.txt
INJECTED
The same weakness appears with os.system, system and popen in C, exec in Node.js, sh -c with a built string in any language, and eval in a shell script. The example files show it in each language.
Fixed code
The program passes a list. The first item names the program, and each other item is one argument. No shell starts, so no character in an argument has a meaning.7
import subprocess
def look_up(name):
subprocess.run(["echo", "looking up", name])
look_up("report.txt")
look_up("report.txt; echo INJECTED")
looking up report.txt
looking up report.txt; echo INJECTED
The input is now one argument, and echo prints it. Go's os/exec "intentionally does not invoke the system shell".8 execFile in Node.js does not spawn a shell by default.9 ProcessBuilder in Java, Command in Rust, ArgumentList in .NET and posix_spawnp in C work in the same way. The example files show each one.
Why escaping is not enough
When a shell is necessary, the program must quote each value for that shell. shlex.quote in Python puts a value in single quotes for a POSIX shell, and the Python documentation says that this works only on some platforms.7 The rules differ between shells, and cmd.exe on Windows has its own. The phf bug shows what happens when one character is missing from the list.5 CVE-2024-24576 shows that the problem is hard even for a standard library. On Windows, a process gets one command line and splits it itself, and cmd.exe splits the arguments of a batch file with its own rules. Rust's Command did not escape arguments to .bat and .cmd files correctly, and the fix makes it return an InvalidInput error when it cannot escape an argument safely.1018
Avoid the command
The OWASP cheat sheet puts first the defence of not calling an operating system command at all.6 A library call cannot run a second command. Use mkdir from the standard library and not system("mkdir ..."). Copy, move and delete files, make archives and send HTTP requests with library functions too. CWE-78 gives the same advice.1
How to detect it
- Static analysis with taint tracking. CodeQL follows input to a process call. Its queries are
py/command-line-injection,js/command-line-injection,java/command-line-injection,go/command-injectionandcs/command-line-injection.11 - Pattern linters. Ruff rule S602 reports
subprocesscalls withshell=True.12 gosec rule G204 reportsexec.Commandwith arguments that are not constants, and G702 follows input to it.13 ShellCheck rule SC2086 reports unquoted variables in shell scripts, which split into many arguments.14 - Code review. Search for
system,popen,shell=True,exec(,sh -c,cmd /c,evalandInvoke-Expression. For each call, check if any part of the string comes from input. - Tests. Put a value with
;, a space, a quote and a leading-through each input that reaches a command. The command must get it as one argument, as it is.
How to prevent it
- Use a library call in place of a command. This removes the weakness.6
- Pass an argument list and start no shell. Use the process API that takes the program and the arguments apart.16
- Choose the program from a fixed set. Never let input name the program or the subcommand.6
- End option parsing. Put
--before values for commands that support it, and reject values that start with-.6 - Validate input as a second layer. Check each argument against an allow-list or a strict pattern, such as
^[a-z0-9]{3,10}$.6 Do not use a denylist of shell characters. It will miss one.15 - Use least privilege. Run the program with only the rights it needs, and in a separate account for each task where possible.6 A sandbox such as a chroot jail, AppArmor or SELinux limits the damage.1
Real cases
| Case | Date | What happened |
|---|---|---|
| CA-1996-06 | 1996-03-20 | The phf example program of NCSA httpd and Apache passed input to popen after an escape function that missed the newline character. It was actively exploited.45 |
| CVE-1999-0067 | published 1999-09-29 | The CVE record for phf: remote command execution through shell metacharacters. CWE-78 calls it the canonical example.151 |
| CVE-2014-6271 | published 2014-09-24 | Shellshock. GNU Bash ran the trailing strings after a function definition in the value of an environment variable. The CVE record names vectors where the environment is set across a privilege boundary, such as the mod_cgi module of the Apache HTTP Server and the ForceCommand feature of OpenSSH.16 |
| CVE-2024-3400 | published 2024-04-12 | Command injection in the GlobalProtect feature of Palo Alto Networks PAN-OS let an unauthenticated attacker run code with root rights on the firewall.17 |
| CVE-2024-24576 | published 2024-04-09 | Rust's Command did not escape arguments correctly for batch files on Windows, so an attacker who controlled an argument could run shell commands.18 |
This code runs but gives a wrong answer on purpose.
import subprocess
def look_up(name):
subprocess.run("echo looking up " + name, shell=True)
look_up("report.txt")
look_up("report.txt; echo INJECTED")
looking up report.txt
looking up report.txt
INJECTED
The shell splits the second command line at ; and runs two commands. The second command is harmless here, but it could be any command that the account of the program may run.
import subprocess
import sys
def look_up(name):
subprocess.run(["echo", "looking up", name])
look_up("report.txt")
look_up("report.txt; echo INJECTED")
# What the child process gets: one argument per list item.
child = [sys.executable, "-c", "import sys; print(sys.argv[1:])"]
subprocess.run(child + ["report.txt; echo INJECTED", "$HOME", "a b"])
looking up report.txt
looking up report.txt; echo INJECTED
['report.txt; echo INJECTED', '$HOME', 'a b']
import shlex
import subprocess
def look_up(name):
subprocess.run("echo looking up " + shlex.quote(name), shell=True)
look_up("report.txt; echo INJECTED")
print(shlex.quote("report.txt; echo INJECTED"))
looking up report.txt; echo INJECTED
'report.txt; echo INJECTED'
- Verdict: stdlib.
subprocesstakes the program and its arguments as a list and does not start a shell unless the call hasshell=True. With a list, no character in an argument has a meaning, because no shell parses it. - With
shell=True, the program must quote every value itself.shlex.quoteputs a value in single quotes for a POSIX shell, as in the third example. The Python documentation says that this works only on some platforms. On Windows,cmd.exehas other quoting rules. os.systemandos.popenalways start a shell. Prefersubprocess.runwith a list.- A list stops a second command. It does not stop argument injection: a value that starts with
-can still be an option of the program. Put--before the value when the program supports it, or check that the value does not start with-. - Ruff rules S602 and S605 report
subprocesscalls withshell=Trueand functions that start a shell. CodeQL querypy/command-line-injectionfollows input to them.
This code runs but gives a wrong answer on purpose.
import java.io.IOException;
public class Main {
static void lookUp(String name) throws IOException, InterruptedException {
new ProcessBuilder("sh", "-c", "echo looking up " + name).inheritIO().start().waitFor();
}
public static void main(String[] args) throws Exception {
lookUp("report.txt");
lookUp("report.txt; echo INJECTED");
}
}
looking up report.txt
looking up report.txt
INJECTED
import java.io.IOException;
public class Main {
static void lookUp(String name) throws IOException, InterruptedException {
new ProcessBuilder("echo", "looking up", name).inheritIO().start().waitFor();
}
public static void main(String[] args) throws Exception {
lookUp("report.txt");
lookUp("report.txt; echo INJECTED");
}
}
looking up report.txt
looking up report.txt; echo INJECTED
- Verdict: stdlib.
ProcessBuildertakes the program and its arguments as separate strings and starts no shell. Runtime.exec(String)does not start a shell either. It splits the string at white space, so a value with a space becomes more than one argument. This is argument injection. The OWASP cheat sheet says to useProcessBuilderorRuntime.exec(String[]).- The weakness comes back with
sh -corcmd /cand a string built from input, as in the first example. - CodeQL query
java/command-line-injectionfollows input from a request toProcessBuilderandRuntime.exec.
This code runs but gives a wrong answer on purpose.
#include <stdio.h>
#include <stdlib.h>
static void look_up(const char *name) {
char command[256];
snprintf(command, sizeof command, "echo looking up %s", name);
fflush(stdout);
system(command);
}
int main(void) {
look_up("report.txt");
look_up("report.txt; echo INJECTED");
return 0;
}
looking up report.txt
looking up report.txt
INJECTED
#define _POSIX_C_SOURCE 200809L
#include <spawn.h>
#include <stdio.h>
#include <sys/wait.h>
extern char **environ;
static int look_up(const char *name) {
char *argv[] = {"echo", "looking up", (char *)name, NULL};
pid_t pid;
fflush(stdout);
int err = posix_spawnp(&pid, "echo", NULL, NULL, argv, environ);
if (err != 0) {
return err;
}
int status;
waitpid(pid, &status, 0);
return 0;
}
int main(void) {
look_up("report.txt");
look_up("report.txt; echo INJECTED");
return 0;
}
looking up report.txt
looking up report.txt; echo INJECTED
- Verdict: stdlib. ISO C has only
system, which passes the string to a command processor,/bin/sh -con POSIX systems. POSIX addsposix_spawn,posix_spawnpand theexecfamily, which take the program and an array of arguments and start no shell. popenalso runs its command through the shell. The phf program of 1996 built a command line withstrcatand passed it topopen.snprintflimits the length of the command, so the first example has no buffer overflow. It does nothing against the;.- The
fflush(stdout)calls keep the output of the parent and the child in order, because the child writes to the same file descriptor.
This code runs but gives a wrong answer on purpose.
using System.Diagnostics;
static void LookUp(string name)
{
var psi = new ProcessStartInfo("sh") { RedirectStandardOutput = true };
psi.Arguments = "-c \"echo looking up " + name + "\"";
using var p = Process.Start(psi)!;
Console.Write(p.StandardOutput.ReadToEnd());
p.WaitForExit();
}
LookUp("report.txt");
LookUp("report.txt; echo INJECTED");
looking up report.txt
looking up report.txt
INJECTED
using System.Diagnostics;
static void LookUp(string name)
{
var psi = new ProcessStartInfo("echo") { RedirectStandardOutput = true };
psi.ArgumentList.Add("looking up");
psi.ArgumentList.Add(name);
using var p = Process.Start(psi)!;
Console.Write(p.StandardOutput.ReadToEnd());
p.WaitForExit();
}
LookUp("report.txt");
LookUp("report.txt; echo INJECTED");
looking up report.txt
looking up report.txt; echo INJECTED
- Verdict: stdlib.
ProcessStartInfo.ArgumentListholds one item per argument, so each value stays one argument. No shell parses the arguments unless the program starts one, as the first example does. ProcessStartInfo.Argumentsis one string, and the string is split into arguments. A space or a quote in a value changes the split, even with no shell. PreferArgumentList.- CodeQL query
cs/command-line-injectionfollows input toProcess.Start.
This code runs but gives a wrong answer on purpose.
const { execSync } = require("node:child_process");
function lookUp(name) {
process.stdout.write(execSync(`echo looking up ${name}`));
}
lookUp("report.txt");
lookUp("report.txt; echo INJECTED");
looking up report.txt
looking up report.txt
INJECTED
const { execFileSync } = require("node:child_process");
function lookUp(name) {
process.stdout.write(execFileSync("echo", ["looking up", name]));
}
lookUp("report.txt");
lookUp("report.txt; echo INJECTED");
looking up report.txt
looking up report.txt; echo INJECTED
- Verdict: stdlib.
execandexecSyncstart a shell and pass it the command as one string. The Node.js documentation says never to pass unsanitized user input to them. execFile,execFileSyncandspawntake the program and an array of arguments, and do not start a shell by default. The optionshell: trueturns the shell back on.- A template literal builds the same string as
+. It is the most common form of the weakness in JavaScript. - CodeQL queries
js/command-line-injectionandjs/shell-command-constructed-from-inputfollow input to these calls.
This code runs but gives a wrong answer on purpose.
package main
import (
"fmt"
"os/exec"
)
func lookUp(name string) {
out, _ := exec.Command("sh", "-c", "echo looking up "+name).Output()
fmt.Print(string(out))
}
func main() {
lookUp("report.txt")
lookUp("report.txt; echo INJECTED")
}
looking up report.txt
looking up report.txt
INJECTED
package main
import (
"fmt"
"os/exec"
)
func lookUp(name string) {
out, err := exec.Command("echo", "looking up", name).Output()
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Print(string(out))
}
func main() {
lookUp("report.txt")
lookUp("report.txt; echo INJECTED")
}
looking up report.txt
looking up report.txt; echo INJECTED
- Verdict: stdlib.
exec.Commandtakes the program and each argument apart. The package documentation says that it intentionally does not invoke the system shell, so it does not expand globs, pipes or redirections. - The weakness comes back when a program passes
sh -corcmd /cwith a string built from input, as in the first example. exec.Commandlooks up the program inPATH. When the name of the program comes from input, the input selects the command. Choose the program from a fixed set in the code.- gosec rule G204 reports
exec.Commandwith arguments that are not constants, and G702 follows input to it. CodeQL querygo/command-injectiondoes the same.
This code runs but gives a wrong answer on purpose.
use std::process::Command;
fn look_up(name: &str) {
let out = Command::new("sh")
.arg("-c")
.arg(format!("echo looking up {name}"))
.output()
.expect("sh runs");
print!("{}", String::from_utf8_lossy(&out.stdout));
}
fn main() {
look_up("report.txt");
look_up("report.txt; echo INJECTED");
}
looking up report.txt
looking up report.txt
INJECTED
use std::process::Command;
fn look_up(name: &str) {
let out = Command::new("echo")
.arg("looking up")
.arg(name)
.output()
.expect("echo runs");
print!("{}", String::from_utf8_lossy(&out.stdout));
}
fn main() {
look_up("report.txt");
look_up("report.txt; echo INJECTED");
}
looking up report.txt
looking up report.txt; echo INJECTED
- Verdict: stdlib.
std::process::Commandtakes the program and each argument apart. Its documentation says that arguments are passed as they are and are not evaluated by a shell. - The weakness comes back when a program runs
sh -cwith a string fromformat!, as in the first example. - Windows has no argument array at the system level. A program gets one command line and splits it itself, and
cmd.exeuses its own rules for batch files. CVE-2024-24576 was a bug in the escaping ofCommandfor.batand.cmdfiles. The fix makesCommandreturn anInvalidInputerror when it cannot escape an argument safely.
This code runs but gives a wrong answer on purpose.
look_up() {
eval "echo looking up $1"
}
look_up "report.txt"
look_up "report.txt; echo INJECTED"
looking up report.txt
looking up report.txt
INJECTED
look_up() {
echo "looking up $1"
}
look_up "report.txt"
look_up "report.txt; echo INJECTED"
name='report.txt; echo INJECTED'
printf '%s\n' "$name"
bash -c 'echo "looking up $1"' look-up "$name"
looking up report.txt
looking up report.txt; echo INJECTED
report.txt; echo INJECTED
looking up report.txt; echo INJECTED
- Verdict: native. A shell script parses each line once. The value of a variable does not go through the parse again, so
;in a variable is a character, not a separator. The weakness comes when the script makes the shell parse the value a second time: witheval, withsh -c "..."that contains the value, or with a command line written to a file and run later. - To pass a value into
bash -c, give it as a separate argument and read it as$1, as in the last line of the second example. The command text stays fixed. - An unquoted
$namedoes not run a second command, but the shell splits it at spaces and expands glob characters, so one value can become many arguments. ShellCheck rule SC2086 reports unquoted variables. Write"$name". - Put
--before values that could start with-, for commands that support it:rm -- "$file".
References
- CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection'), Description; Technical Nuance; Alternate Terms; Common Consequences; Potential Mitigations; Observed Examples
- OWASP Top 10:2025, A05:2025 Injection, List of Mapped CWEs
- 2025 CWE Top 25 Most Dangerous Software Weaknesses, the ranked list, rank 9, CVEs in KEV
- Software Engineering Institute, 1996 CERT Advisories, CA-1996-06: Vulnerability in NCSA/Apache CGI example code, chapter 6, the introduction and 1. Description
- CERT/CC Vulnerability Note VU#20276, phf CGI Script fails to guard against newline characters, Overview; Description
- OWASP Cheat Sheet Series, OS Command Injection Defense Cheat Sheet, Argument Injection; Primary Defenses, options 1 to 3; Additional Defenses; Code examples, Java
- The Python Standard Library, subprocess, Python 3.14, Security Considerations
- Go standard library, package os/exec, Overview
- Node.js documentation, Child process, child_process.exec; child_process.execFile
- Rust Security Response WG, Security advisory for the standard library (CVE-2024-24576), Overview; Mitigations
- CodeQL query help, Uncontrolled command line (py/command-line-injection), the query description
- Ruff rules, subprocess-popen-with-shell-equals-true (S602), What it does
- gosec rules, G204 and G702
- ShellCheck wiki, SC2086: Double quote to prevent globbing and word splitting, Problematic code; Correct code
- CVE-1999-0067, phf CGI program, the description and the publication date
- CVE-2014-6271, GNU Bash, the description and the publication date
- CVE-2024-3400, Palo Alto Networks PAN-OS GlobalProtect, the description and the publication date
- CVE-2024-24576, Rust standard library, the description and the publication date
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag BVNBXN Edit this page History Report an error Markdown