Skip to main content

Command Injection

Command Injection

Table of Contents

Quick Answer

Command injection is a vulnerability in which untrusted input changes an operating system command that an application runs. It usually happens when code builds a command line from strings and hands it to a shell, which reads spaces and special characters as instructions. A related form, argument injection, needs no shell: a value that starts with a hyphen is read as an option. Prevent it by using a library instead of a command where you can, and otherwise by starting a fixed program with separate arguments, no shell, and input checked against an allow-list.

This defensive guide explains what command injection is, how input crosses from data into a command, and how it led to some of the most exploited flaws of recent years. Three Java examples each show the fault, a harmless test that detects it, and the fix, followed by the risky and safer calls in Python, Node.js and PHP. There are no attack strings here: the test values are a space, a leading hyphen and a Windows variable name.

What is command injection?

Applications start other programs all the time: to convert a file, query a network tool, run a backup or call a script someone wrote years ago. Command injection, also called OS command injection or shell injection, happens when input from outside the application changes what that command does. MITRE catalogues it as CWE-78, and it ranks ninth in the 2025 CWE Top 25. OWASP places it under A05 Injection in the Top 10:2025.

The injected part runs with the identity of the application, so the attacker can do whatever the application's account can do: read its files and secrets, change its data and connect to the systems it can reach. When the input arrives over a network, the result is remote code execution.

TermWeaknessWhat changes
Command injectionCWE-78The command line: input adds a command, or changes how the shell splits and expands it
Argument injectionCWE-88The meaning of an argument: input that should be data is read as an option of the program
Code injectionCWE-94Code evaluated by the application's own language or expression engine
Remote code executionAn outcomeThe attacker can run code of their choice over a network, through any of the above or other flaws

How command injection works

A program receives its arguments as a list of separate strings. The danger is in how that list is produced from what the application wrote.

Through a shell

When an application passes a whole command line to sh -c, bash -c or cmd /c, or calls a function that does so, such as system(), the shell decides where one argument ends and the next begins. It also reads characters that separate commands, redirect output, substitute values and expand variables. Any of those inside the input becomes an instruction to the shell, not part of the data. Quoting helps only if it exactly matches the rules of that shell, and those rules are different on Unix and Windows.

Through the program's own options

Even without a shell, the program you start interprets its arguments. Many tools treat a value beginning with - as an option, and some options write files, read configuration or run other programs. A file name, branch name or host name chosen by a user can turn into such an option. OWASP's cheat sheet puts it simply: every OS command injection is also an argument injection.

Through Windows batch files

On Windows, a .bat or .cmd file is run through cmd.exe even when the application did not ask for a shell. The language runtime quotes the arguments for an ordinary program, but cmd.exe parses them by its own rules and expands %VARIABLE% references first. In April 2024, the researchers at Flatt Security who disclosed this as BatBadBut found it in many languages. Several runtimes released patches; their status table lists Java as "won't fix", so Java applications have to avoid the pattern themselves.

Java examples with fixes

The three examples below were compiled and run on Java 21, with imports left out for length. Each test uses a harmless value that only shows whether the input is interpreted. Run such tests only against code you own or are authorised to test.

Input passed to a shell

The fault. A log search feature builds a grep command line from the search term and gives it to sh -c. The shell, not the developer, decides what the term means.

static String countMatchesUnsafe(String term) throws IOException {
    // term comes from the request
    var p = new ProcessBuilder("sh", "-c", "grep -c " + term + " app.log")
        .redirectErrorStream(true).start();
    return new String(p.getInputStream().readAllBytes()).trim();
}

How to detect it. Look for a shell as the first element of a ProcessBuilder or Runtime.exec call, followed by a string built from variables. Find Security Bugs reports these calls as COMMAND_INJECTION. In a test, a search term containing a space is enough. If the shell splits it, the input is being parsed as part of the command.

Test input: the search term "two words", in a log where it appears once

countMatchesUnsafe -> grep: words: No such file or directory
                      app.log:1     the shell split the input into two arguments
countMatchesFixed  -> 1             the term reached grep as one argument

The fix. Start the program directly and pass each argument as its own string, so no shell is involved. Check the term against an allow-list of the characters a search needs. -F makes grep treat the term as text, -e marks it as the pattern even if it starts with a hyphen, and -- ends the options before the file name. Better still, search the file in Java and start no process at all.

static final Pattern SEARCH_TERM = Pattern.compile("[\\p{L}\\p{N} ._-]{1,64}");

static String countMatchesFixed(String term) throws IOException {
    if (!SEARCH_TERM.matcher(term).matches()) {
        throw new IllegalArgumentException("Unsupported search term");
    }
    var p = new ProcessBuilder("grep", "-c", "-F", "-e", term, "--", "app.log")
        .redirectErrorStream(true).start();
    return new String(p.getInputStream().readAllBytes()).trim();
}

Argument injection without a shell

The fault. A report feature counts the lines in an uploaded file with wc. There is no shell, and each argument is separate. The user still chooses an argument, and wc reads any argument starting with a hyphen as an option.

static String lineCountUnsafe(Path uploads, String name) throws IOException {
    // name comes from the request; there is no shell here
    var p = new ProcessBuilder("wc", "-l", name)
        .directory(uploads.toFile()).redirectErrorStream(true).start();
    return new String(p.getInputStream().readAllBytes()).trim();
}

How to detect it. For every process call, list which arguments a user can influence and check what the program does with a value beginning with -. In a test, pass the name --version. A harmless option is enough to show the value is read as an option. Here wc printed its version instead of a line count.

Test input: the file name "--version"

lineCountUnsafe -> wc (GNU coreutils) 8.32 ...   the value was read as an option
lineCountFixed  -> IllegalArgumentException      Unknown file

The fix. Do not let the client name files at all: store uploads under names the server generates, and accept only that format. Put -- before values the program should treat as operands, for tools that support it. Not every program does, and some options still apply after it, so the allow-list is the main control.

static final Pattern STORED_NAME =
    Pattern.compile("[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}\\.csv");

static String lineCountFixed(Path uploads, String name) throws IOException {
    if (!STORED_NAME.matcher(name).matches()) {
        throw new IllegalArgumentException("Unknown file");
    }
    var p = new ProcessBuilder("wc", "-l", "--", name)
        .directory(uploads.toFile()).redirectErrorStream(true).start();
    return new String(p.getInputStream().readAllBytes()).trim();
}

A Windows batch file

The fault. An older reporting script is a batch file, and the application passes it the customer value from the request. The code looks like the safe form above: a fixed program and separate arguments.

// report.bat contains one line:  @echo Report for %1

static String reportUnsafe(Path scripts, String customer) throws IOException {
    // customer comes from the request; no shell is requested here
    var p = new ProcessBuilder(scripts.resolve("report.bat").toString(), customer)
        .redirectErrorStream(true).start();
    return new String(p.getInputStream().readAllBytes()).trim();
}

How to detect it. Search for .bat and .cmd in process calls and configuration, and remember that a command name without an extension may resolve to a batch file on the path. On Windows, test with the value %OS%. If the output shows Windows_NT, cmd.exe interpreted the value instead of passing it through.

Test input: the customer value "%OS%", on Windows

reportUnsafe -> Report for Windows_NT          cmd.exe expanded the value
reportFixed  -> IllegalArgumentException       Unknown customer

The fix. The best fix is to stop passing request data to batch files: move the logic into the application, or call the real program the script wraps, by its full path and extension. Where the script must stay, accept only values from a strict allow-list. Here a customer ID is a letter and six digits, so %, quotes and spaces never reach cmd.exe. Do not rely on escaping in this case.

static final Pattern CUSTOMER_ID = Pattern.compile("C[0-9]{6}");

static String reportFixed(Path scripts, String customer) throws IOException {
    if (!CUSTOMER_ID.matcher(customer).matches()) {
        throw new IllegalArgumentException("Unknown customer");
    }
    var p = new ProcessBuilder(scripts.resolve("report.bat").toString(), customer)
        .redirectErrorStream(true).start();
    return new String(p.getInputStream().readAllBytes()).trim();
}

Risky and safer calls in other languages

The same two forms exist in every language: one hands a command line to a shell, the other starts a program with a list of arguments. The safer column still needs an allow-list and, for tools that support it, --, because it removes the shell but not argument injection.

LanguageGoes through a shellStarts the program directlyNote
JavaProcessBuilder("sh", "-c", line), or cmd /cProcessBuilder with each argument separateRuntime.exec(String) uses no shell but splits on spaces. It is deprecated since Java 18.
Pythonos.system(), subprocess.run(line, shell=True)subprocess.run([...]) with a listPython's documentation warns that Windows may run batch files in a shell whatever the arguments.
Node.jschild_process.exec()execFile() or spawn() without the shell optionThe documentation says never to pass unsanitized input to exec().
PHPexec(), system(), shell_exec(), a string to proc_open()proc_open() with an array, PHP 7.4 and laterOn Windows, escapeshellarg() replaces %, ! and double quotes with spaces.

Real incidents

Shellshock, 2014

CVE-2014-6271 was in GNU Bash itself. Bash through version 4.3 processed text that followed a function definition stored in an environment variable, and ran it. Web servers using CGI pass request details to scripts as environment variables, so a request header could reach Bash through Apache's CGI modules, and NVD also lists OpenSSH and DHCP clients as routes. NVD scores it 9.8, the first fix was incomplete and needed a second CVE, and CISA lists it as known to be exploited.

The lesson is that the shell is a sink even when your code never builds a command. A process that starts any shell, for any reason, inherits that shell's flaws.

Palo Alto Networks PAN-OS, 2024

CVE-2024-3400 was a command injection in the GlobalProtect feature of PAN-OS 10.2, 11.0 and 11.1, reached through arbitrary file creation. It needed no login and ran commands with root privileges on the firewall. It scored 10.0, and CISA added it to its Known Exploited Vulnerabilities catalog on 12 April 2024, the day it was published. The vendor reported an increasing number of attacks.

Ivanti Connect Secure, 2024

CVE-2024-21887 was a command injection in the web components of Ivanti Connect Secure and Policy Secure, versions 9.x and 22.x. On its own it needed an authenticated administrator. It was disclosed together with CVE-2023-46805, an authentication bypass in the same products, and Ivanti reported active exploitation of both. CISA added both to the catalog on 10 January 2024.

"Requires administrator access" lowered the score to 9.1. It did not stop the attacks, because a second flaw removed the login. Treat every command injection as urgent, whatever stands in front of it.

In July 2024, CISA and the FBI published a Secure by Design alert on eliminating OS command injection. It cites the PAN-OS and Ivanti flaws and a Cisco NX-OS one from the same year, and asks software makers to use built-in library functions that keep commands and arguments apart.

How to detect command injection

In code

Process calls are rare in most applications, so an inventory is quick. This search finds the usual Java entry points, shells named as programs and batch files:

grep -rnE "ProcessBuilder|Runtime\.getRuntime\(\)\.exec|\"(sh|bash|cmd|cmd\.exe|powershell)\"|\.(bat|cmd)\"" src/

For each result, ask two questions: does any part of the command come from outside the application, and is there a shell anywhere in the chain? Add static analysis that follows data from source to sink, such as Find Security Bugs' COMMAND_INJECTION rule, and check other languages for the risky calls in the table above. Our guide to SAST and DAST explains where each kind of testing fits.

In tests

Keep the three harmless tests from the examples as regression tests: a value with a space, a value starting with a hyphen and, on Windows, a %VARIABLE% name. Assert that the program receives exactly the arguments you intended. For a running application, the OWASP Web Security Testing Guide has a test procedure for command injection, for authorised testers working on systems in scope.

At runtime

SignalWhy it mattersWhere to see it
A shell or interpreter started by the application processMost web services never start one. A shell under a Java, Node.js or PHP process is one of the clearest signs.Endpoint detection, process creation logs, container runtime security
Programs or arguments the service has never usedInjected commands, and options added by argument injection, show up as new command lines.Process creation logs that record the full command line
New outbound connectionsInjected commands often download tools or call back, as in a reverse shell.DNS, proxy and firewall logs
New files in application or temporary directoriesDownloaded tools and web shells have to be written somewhere.File integrity monitoring

MITRE ATT&CK records the activity that follows as T1059, Command and Scripting Interpreter, which helps when you map these signals to existing alerts.

How to prevent command injection

OWASP's first defence is to avoid calling operating system commands at all. The rest of this list applies when you cannot.

1. Use a library instead of a command

Creating directories, copying and compressing files, resizing images, resolving host names and searching text all have library APIs. A library call has no command line to inject into, and it is usually faster and easier to test.

2. Start a fixed program with separate arguments

Name the program yourself, by full path where you can, and pass every argument as its own element. Never pass input to sh -c, cmd /c, system() or another function that builds a shell command line. CISA suggests blocking the risky calls at code review.

3. Validate against an allow-list

Let the user choose from fixed values, and map each choice to an argument in code. Where free input is unavoidable, accept only the characters and length it needs, and use names the server generated for files. Validation is covered in more depth in input validation attacks, and the principle is the same one that stops SQL injection: keep data and instructions apart.

4. End the options

Put -- before values the program should treat as data, or use the program's own way of marking a value, such as grep -e. Check each tool's documentation, because some do not support it and some options still apply afterwards.

5. Keep request data away from batch files

On Windows, do not pass untrusted values to .bat or .cmd files. Call the program by its full name with the extension, so a batch file on the path is never chosen by accident.

6. Limit what an injected command can do

Run the service as an unprivileged user, keep shells and tools out of production images where you can, restrict outbound traffic and give each service only its own secrets. These controls do not fix the flaw, but they decide whether a missed one becomes a contained incident or a privilege escalation into everything else.

Escaping comes last. Use the escaping function for the exact shell involved only when a shell truly cannot be avoided, and still validate. Process calls like these are common in older Java systems, which are often on unsupported Java releases too. If that is your position, Pashyaa's fixed-price Java upgrade work covers getting back onto a supported line. If you suspect a command injection has already been used, follow the steps in what to do if you suspect RCE.

Developer review questions

  • Where does this application start another program, and could a library call replace it?
  • Is a shell involved anywhere, including sh -c, cmd /c, system() or a batch file?
  • Which arguments can a user influence, directly or through stored data?
  • Can any of those arguments start with a hyphen, and what would the program do if one did?
  • Is every free-text value checked against an allow-list before it reaches the command?
  • Are file names generated by the server rather than taken from the client?
  • Is each program named by full path, with its extension on Windows?
  • What could this process read, write and reach if an attacker chose its commands?
  • Would a shell started by this service raise an alert?
  • Are these tests run only on systems we are authorised to test?

FAQs

Command injection is one of the most common ways to get remote code execution. The weakness is the command built from input. The result, when an attacker can reach it over a network, is RCE: they choose what runs on your server. RCE can also come from unsafe deserialization, expression evaluation, file upload or memory corruption, none of which involves a shell.

In command injection (CWE-78), input changes an operating system command that the application starts, so the shell or another program does the damage. In code injection (CWE-94), input becomes part of code that the application's own language or expression engine evaluates, for example through eval or an expression language. The fixes are related: do not let data become instructions in either case.

It removes the shell, which is the biggest source of the problem, when you pass the program and each argument as separate strings. It does not stop argument injection, where a value starting with a hyphen is read as an option. It also gives no protection if the program you start is itself a shell, such as sh -c or cmd /c, or a Windows batch file, which Windows runs through cmd.exe.

It is the weakest of the defences. OWASP lists escaping after avoiding commands altogether, and it only works if you use the exact rules of the shell that will read the command. Those rules differ between Unix shells and Windows, and the researchers behind the 2024 BatBadBut disclosure found that the usual escaping does not work for % in arguments to Windows batch files, and were unsure even of their own workaround. Avoid the shell and validate the value instead.

It is command injection where the application does not show the command's output. Testers then infer the result indirectly, for example from timing or from a network request the server makes. It is just as serious, because the command still runs, and the fix is the same. It also explains why "nothing came back" in a test is not evidence that a feature is safe.

It can block some common patterns and buy time while you fix the code. It cannot be the fix. Shell syntax has many equivalent forms, the firewall does not know which program will read the value, and input that arrives through a file, a queue or an internal service never passes the firewall at all.

Every language that can start another program: Java, Python, Node.js, PHP, Ruby, Go, C# and the rest. Memory safety makes no difference, because the flaw is in how the command is built, not in how memory is used. What differs is how easy each language makes the safe form, which the table of risky and safer calls on this page shows.

Sources and further reading