flawopen.com/Command Injection/PHP

Command Injection in PHP

Critical CWE-78 Draft — pending review
ELI5

Imagine a form where you enter a website to check if it's online. If someone enters 'google.com; cat /etc/passwd', and PHP runs the whole sentence in terminal, they get to read your server passwords.

Key terms on this page
shell_exec & system
PHP functions that pass input directly to the system shell for execution.
escapeshellarg
PHP function that wraps strings in quotes and escapes existing quotes for shell safety.

What's happening

PHP has multiple built-in shell invocation functions: system(), exec(), passthru(), shell_exec(), and the backtick operator (` `). All of these spawn a shell and execute strings directly.

Real-world impact

Command injection in PHP web apps has caused massive breaches in enterprise file sync services and content management systems, enabling root shell access.

OWASP PHP Top 10 vulnerabilities.

Vulnerable vs. fixed

VULNERABLE
FIXED

Why the fix works

escapeshellarg() encloses the parameter in single quotes and strips/escapes any existing single quotes, preventing shell metacharacters from breaking out of the parameter string.

Gotchas

escapeshellcmd vs escapeshellarg

escapeshellcmd() only escapes shell metacharacters but allows multiple arguments, enabling flag injection. Always use escapeshellarg() for individual parameter values.

Common misconceptions

"Disabling system() in php.ini is enough"

PHP has many execution aliases: exec, shell_exec, passthru, proc_open, popen, and backtick operators. Disabling only one function leaves the others open.

How to check if you're affected

grep -rn "shell_exec(" --include="*.php" . grep -rn "system(" --include="*.php" .
Run PHPStan with the PHPStan-security extension in CI.

Prevention checklist

FAQ

What is the safest execution function in PHP?

proc_open() provides the greatest control over environment, file descriptors, and pipes without passing input through a raw shell.

References

View in: Python JavaScript Go Java PHP C# Ruby C/C++ Rust Kotlin Swift Solidity (N/A)
Also see: SQL Injection XSS Path Traversal Insecure Deserialization