What Is OS Command Injection?

On this page
  1. How does command injection happen?
  2. Why is avoiding the shell the real fix?

OS command injection is a vulnerability where an application feeds untrusted input into a system shell, letting an attacker run arbitrary operating-system commands. It is among the most severe web flaws because it typically yields direct remote code execution — the attacker’s command runs with the web server’s privileges. Like all injection, its root cause is data being treated as code.

How does command injection happen?#

An app builds a shell command by concatenating input:

Intended:  ping -c 1 <user_host>
Input:     8.8.8.8; cat /etc/passwd
Executed:  ping -c 1 8.8.8.8; cat /etc/passwd

The shell sees the ; as a command separator and runs both. Metacharacters like ;, |, &&, $( ), and backticks all let an attacker append commands. This is the operating-system sibling of SQL injection — same disease, different interpreter.

Why is avoiding the shell the real fix?#

Because the vulnerability only exists when a shell parses your string. Passing arguments directly to a program — as an array, never through a shell — removes the parser that turns metacharacters into commands:

ApproachInjectable?
system("ping " + host) (shell)Yes
execFile("ping", ["-c","1", host]) (no shell)No
Manual escapingFragile, often bypassed

The safe forms exist in every language: subprocess.run([...]) in Python, execFile in Node, ProcessBuilder in Java — all pass arguments as data.

Command injection is the highest-severity member of the injection family. It shares its cure with SQL injection: keep data out of the code channel. More at the Web Security hub.

Frequently asked questions#

What is OS command injection?

OS command injection is a flaw where an application passes untrusted input into a system shell command, letting an attacker run arbitrary operating-system commands. Shell metacharacters like semicolons, pipes, and backticks let the attacker append their own commands, often leading directly to full remote code execution on the server.

How do you prevent command injection?

Avoid calling the shell at all. Use language APIs that execute a program with an argument array directly, so input is passed as data, never parsed as a command. If you must use a shell, use a strict allowlist of permitted values. Escaping shell metacharacters by hand is fragile and error-prone.

Sources & further reading