Preventing Command Injection
In this step, we will learn how to prevent command injection attacks.
The most effective way to prevent command injection is to avoid executing user-provided data as part of a command or shell script. Instead, use language-specific mechanisms for executing commands and sanitize user input before using it.
Here's an example of a secure PHP code that sanitizes user input:
<?php
$ip = filter_var($_GET['ip'], FILTER_VALIDATE_IP);
if ($ip !== false) {
$output = shell_exec('ping -c 3 ' . escapeshellarg($ip));
echo "<pre>$output</pre>";
} else {
echo "Invalid IP address";
}
?>
In this code, we first validate the user input using the filter_var
function to ensure it is a valid IP address. Then, we use the escapeshellarg
function to escape any special characters in the input before passing it to the shell_exec
function.
This way, even if an attacker tries to inject malicious commands, they will be properly escaped and treated as literal data, preventing command injection attacks.