Command injection is one of the simpler defender problems — just don’t pass user input to shell functions. The right answer is almost always “use a safe API instead of the shell.”

Primary Defense — Don’t Use Shell at All

The single biggest win: use language APIs that don’t invoke a shell.

Instead of Shell Commands

# bad
os.system(f"ping {user_ip}")
 
# better — Python's subprocess with argument list (no shell=True)
subprocess.run(["ping", "-c", "1", user_ip], check=True)

With subprocess.run() and a list argument, there’s no shell interpretation — user input is passed as a literal argument, not a parsed string.

// bad
exec(`ping ${userIp}`)
 
// better
execFile('ping', ['-c', '1', userIp])
// bad
system("ping " . $_GET['ip']);
 
// better — use a library
$socket = fsockopen($_GET['ip'], 80);

If you’re building a web app and you reach for system(), exec(), shell_exec(), popen(), stop and ask whether there’s a language-native API for whatever you’re trying to do.

Input Validation (If Shell Is Unavoidable)

When you must call a shell (legacy integration, specific tools), validate input strictly:

Allowlist, Not Blacklist

# bad — blacklist can be bypassed
if any(c in user_input for c in [';', '&', '|']):
    reject()
 
# good — allowlist only expected characters
if not re.match(r'^[0-9a-fA-F.:]+$', user_ip):
    reject()

Allowlists define what’s allowed; everything else is rejected. Blacklists try to enumerate what’s dangerous and always miss something.

Per-Context Validation

Validate for the specific type of input:

  • IP address — ^(\d{1,3}\.){3}\d{1,3}$
  • Hostname — ^[a-zA-Z0-9][a-zA-Z0-9.-]*$
  • Filename — ^[a-zA-Z0-9._-]+$ (reject .., /, \)
  • Integer — parse with int() and catch exceptions

Escape Properly (If Shell Call Is Unavoidable)

If you absolutely must concatenate user input into a shell string, use the language’s shell-escape function:

import shlex
cmd = f"ping {shlex.quote(user_ip)}"
os.system(cmd)
$cmd = "ping " . escapeshellarg($_GET['ip']);
system($cmd);
cmd = "ping #{Shellwords.escape(user_ip)}"
system(cmd)

Caveat: escapeshellarg wraps in single quotes. If your target is Windows CMD, this doesn’t do what you expect — Windows uses different quote semantics. Use escapeshellcmd for CMD, or avoid shell calls entirely on Windows.

Run the Web Server as a Low-Privilege User

Even if command injection succeeds, it should run as a low-privilege user:

  • Not root
  • Not a user with sudo privileges
  • With restricted filesystem access
  • In a container with no outbound network (or tightly filtered egress)

This limits what the attacker can do with a successful injection — turning full system compromise into “the attacker can only run basic commands as www-data.”

Monitoring and Detection

  • Log all shell invocations from the web app — alert on unexpected commands
  • Monitor for outbound connections from the web server to unusual destinations (reverse shell indicator)
  • Watch for process spawns from the web server user (web servers shouldn’t spawn curl, nc, bash -i)
  • Use SELinux / AppArmor policies to block forbidden syscalls

Environment Hardening

# Set PATH so arbitrary commands can't be found
export PATH=/usr/local/bin:/usr/bin
 
# Chroot or container the web process
# Mount /tmp with noexec,nosuid,nodev

Attackers rely on common tools being in $PATH. A restricted PATH and nothing-executable /tmp cripples most reverse-shell payloads even if injection succeeds.

WAF as Secondary Defense

Web Application Firewalls catch common patterns (;, &&, $()), but they’re bypassable (see the Obfuscation section — most techniques defeat WAFs). WAF is a tripwire, not a wall. Use it to detect attempts, not to prevent exploitation.

Checklist Summary

  1. Use language-native APIs instead of shell calls whenever possible
  2. If shell is required, use argument lists (subprocess.run([cmd, arg, arg])) not strings
  3. If string concatenation is required, validate with allowlist regex
  4. If concatenation is required, use shlex.quote() / escapeshellarg()
  5. Run the web server as the lowest-privilege user possible
  6. Isolate in container with restricted network egress
  7. Monitor for unusual process spawns and outbound connections
  8. Deploy WAF as detection layer, not prevention

Any single layer breaks the attack. All together make command injection extremely hard to exploit meaningfully even if a vulnerability exists.