Skip to content

Preventing OS command injection

The reliable way to prevent OS command injection is to stop handing user input to a shell. Run external programs with an argument vector through a shell-free API, so attacker input can only ever be a value — never syntax. This guide gives the pattern and the safe API for each major language and runtime.

One rule above all: don’t build a command string and pass it to a shell. Pass the program name and each argument as separate list elements. Blocklist filtering of “dangerous characters” is not a reliable fix and is not recommended here.

Defense-in-depth principles

  1. 1Don't call a shell at all

    The vulnerability exists because user input reaches a shell (sh -c, cmd.exe, PowerShell) where characters like ; | & $() ` become syntax. Use your runtime's API for launching a process directly with an argv array, and the shell is never in the loop.

  2. 2Pass arguments as data, never build a command string

    Give the program name and each argument as separate list elements. The OS hands your value to the target program as a single argv entry, so it can only be data — a filename, a hostname, a flag value — and can never be re-parsed as a new command.

  3. 3Prefer a native library over shelling out

    Most reasons to run a command (resolve a host, resize an image, read archive metadata, send mail) have a library binding that needs no external process. Removing the exec call removes the bug class entirely.

  4. 4Validate input as a value, with an allowlist

    When a value must match a known shape — an integer ID, an item from a fixed set, a filename under one directory — validate it against an allowlist and reject everything else. This is defense in depth on top of safe exec, not a replacement for it.

  5. 5Guard against argument injection too

    Even with a shell-free API, a user-controlled value that starts with - can be read as an option by the target program. Use a -- separator, pin flags yourself, or validate the value so it can't impersonate one.

  6. 6Drop privileges and constrain the blast radius

    Run the subprocess as an unprivileged user, in a restricted working directory or container, with a minimal PATH and environment. It will not stop injection, but it limits what a successful injection can reach.

Safe APIs by language and runtime

For each runtime: the safe API to use, the unsafe one to avoid, and a vulnerable-vs-fixed pair.

Node.js

Use
child_process.execFile / spawn with an args array (no shell)
Avoid
child_process.exec, execSync, or spawn with { shell: true }

Vulnerable

const { exec } = require("node:child_process");
// host comes from the request — "8.8.8.8; rm -rf /" runs rm
exec("ping -c1 " + host, (e, out) => res.send(out));

Fixed

const { execFile } = require("node:child_process");
// host is a single argv entry; shell metacharacters are inert
execFile("ping", ["-c1", "--", host], (e, out) => res.send(out));
  • exec() and execSync() always run their string through /bin/sh (or cmd.exe) — treat them as unsafe for any value that includes user input.
  • spawn()/execFile() are safe only without shell: true. Setting shell: true re-introduces the shell and the bug.
  • Prefer a library (e.g. dns.lookup instead of shelling out to ping/nslookup) when one exists.

Python

Use
subprocess.run([...]) with a list and the default shell=False
Avoid
os.system, os.popen, subprocess with shell=True, commands.*

Vulnerable

import subprocess
# shell=True sends the whole string to /bin/sh
subprocess.run(f"ping -c1 {host}", shell=True)

Fixed

import subprocess
# list form, shell=False (the default): host is one argument
subprocess.run(["ping", "-c1", "--", host], check=True)
  • shell=False is the default — the danger comes from explicitly setting shell=True or using os.system/os.popen.
  • Never pass a single formatted string as the first argument with shell=True; build the argv list instead.
  • shlex.quote() exists but is a last resort; a shell-free list call is simpler and safer.

PHP

Use
proc_open with an array command (PHP 7.4+), or a native extension
Avoid
system, exec, shell_exec, passthru, popen, backtick operator

Vulnerable

<?php
// $host is attacker-controlled; metacharacters reach the shell
system("ping -c1 " . $host);

Fixed

<?php
// array form skips the shell entirely (PHP 7.4+)
$p = proc_open(["ping", "-c1", "--", $host], $descriptors, $pipes);
  • All of system/exec/shell_exec/passthru/popen invoke a shell. The backtick operator does too.
  • escapeshellarg() on every argument is the fallback when you must build a string, but the array form of proc_open avoids the shell and is preferred.
  • escapeshellcmd() is NOT sufficient — it does not neutralise argument injection and is easy to misuse.

Java / JVM

Use
ProcessBuilder with a String[] / List<String> command
Avoid
Runtime.getRuntime().exec(String) on a concatenated string, or exec("sh -c ...")

Vulnerable

// A single concatenated string handed to sh -c is injectable
Runtime.getRuntime().exec("sh -c 'ping -c1 " + host + "'");

Fixed

ProcessBuilder pb = new ProcessBuilder("ping", "-c1", "--", host);
pb.redirectErrorStream(true);
Process p = pb.start();
  • ProcessBuilder (and exec(String[])) do NOT use a shell: each element is a literal argument. That is the safe path.
  • The danger is wrapping the call in sh -c / cmd /c yourself, or using exec(String) which naively splits on spaces.
  • Do not reach for cmd.exe or /bin/sh just to get redirection or globbing — handle those in Java.

Ruby

Use
system / exec / IO.popen with a multi-argument (array) form
Avoid
backticks, %x{}, or system("...#{var}...") as a single string

Vulnerable

# Single-string form runs through the shell
system("ping -c1 #{host}")

Fixed

# Multi-argument form bypasses the shell
system("ping", "-c1", "--", host)
  • Ruby decides shell-vs-direct by argument count: one string → shell; multiple arguments (or an array) → direct exec.
  • Backticks and %x{} always use the shell and cannot take the safe multi-arg form — avoid them with user input.
  • Open3.capture2/capture3 accept the same safe multi-argument form when you need the output.

Go

Use
exec.Command(name, arg1, arg2, ...) with separate arguments
Avoid
exec.Command("sh", "-c", userString) or "bash", "-c", ...

Vulnerable

// Routing through sh -c makes the string injectable
exec.Command("sh", "-c", "ping -c1 "+host).Run()

Fixed

// Each argument is passed literally; no shell involved
exec.Command("ping", "-c1", "--", host).Run()
  • exec.Command does not invoke a shell on its own — the bug appears only when you explicitly call sh -c / bash -c with a built string.
  • If you need pipes or redirection, wire os/exec Cmd.Stdin/Stdout together in Go instead of asking a shell.

.NET / C#

Use
ProcessStartInfo with ArgumentList and UseShellExecute = false
Avoid
Passing a built string to cmd.exe /c, or Arguments with concatenation

Vulnerable

var psi = new ProcessStartInfo("cmd.exe", "/c ping -n 1 " + host);
Process.Start(psi); // host can inject via & | ^ etc.

Fixed

var psi = new ProcessStartInfo("ping") { UseShellExecute = false };
psi.ArgumentList.Add("-n");
psi.ArgumentList.Add("1");
psi.ArgumentList.Add(host); // added as one argument, quoted by the runtime
  • Use ArgumentList (not the single Arguments string) so each value is escaped and passed as one argv entry.
  • Keep UseShellExecute = false and never route through cmd.exe /c with a concatenated string.
  • On Windows, argument escaping is subtle; ArgumentList handles it for you — do not hand-build the command line.

Perl

Use
system LIST / open with a list-form pipe
Avoid
system("...$var..."), backticks, open("cmd|") on a string

Vulnerable

# Single string goes to the shell
system("ping -c1 $host");

Fixed

# List form execs directly, no shell
system("ping", "-c1", "--", $host);
  • Like Ruby, Perl uses the shell only for the single-string form; the list form execs the program directly.
  • Backticks and qx// always use the shell; avoid them with tainted data. Enable taint mode (-T) to catch leaks.

Fixes by technique

Each technique page carries its own detection signals and remediation.

OWASP-aligned