Understanding OS Command Injection in PHP and How to Prevent It
The article explains how PHP functions like exec(), system(), passthru(), popen(), backtick operator, shell_exec() and pcntl_exec() can be abused for OS command injection, demonstrates vulnerable code examples, and provides practical mitigation techniques to secure web applications.
OS Command Injection (also known as OS Command Injection) occurs when an attacker injects malicious shell commands through vulnerable PHP functions, causing the server to execute unintended commands.
1. Functions prone to command injection
PHP provides several functions for executing system commands, such as exec() , system() , passthru() , popen() , the backtick operator, shell_exec() and pcntl_exec() . Improper use of these functions with unsanitized user input can lead to command injection.
(1) exec() function
The exec() function executes a system command and returns the output in an array.
<?php
echo exec($_GET["cmd"], $output);
foreach($output as $value) {
echo $value;
}
?>(2) system() function
<?php
system($_GET["cmd"]);
?>(3) passthru() function
<?php
passthru($_GET["cmd"]);
?>(4) popen() function
<?php
$handle = popen($_GET["cmd"], 'r');
echo "'$handle';" . gettype($handle) . "\n";
$read = fread($handle, 2096);
echo $read;
pclose($handle);
?>(5) Backtick operator
<?php
$res2 = $_GET["cmd"];
echo `$res2`;
?>(6) shell_exec() function
<?php
$output = shell_exec($_GET["cmd"]);
echo "$output";
?>(7) pcntl_exec() function
<?php
pcntl_exec($_GET["cmd"], $_GET["args"]);
?>2. Defending against command injection
To prevent command injection in PHP, follow these recommendations:
Avoid using these functions whenever possible; never accept commands directly from users.
If usage is unavoidable, ensure command parameters are not controllable by external input.
Enable safe_mode=On in php.ini and disable dangerous functions via disable_functions (e.g., exec,system,passthru,popen,shell_exec,pcntl_exec ).
Replace external command functionality with custom PHP functions or libraries.
Sanitize arguments using escapeshellarg() and escapeshellcmd() .
Configure safe_mode_exec_dir to restrict executable paths.
disable_functions = exec,system,passthru,popen,shell_exec,pcntl_exec safe_mode = on
safe_mode_exec_dir = /usr/local/php/binLaravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.