Skip to main content

Correct Code

It is essential to reserve machine-level command execution as a last resort during application development. However, if necessary, it is crucial to exercise extreme caution with the parameters passed to these commands. This involves exhaustively filtering all data input and thoroughly verifying its validity, especially when it comes from external users.

For example, in the code that handles ping at the highest security level, a cautious approach is taken. First, the IP address provided is broken down into its individual components, known as octets. Each of these octets is then checked separately to ensure that they contain only numerical values. Finally, the IP address is reassembled. This process ensures that the IP address used is valid and reliable data before proceeding with any further operations.

This rigorous approach to data verification is essential to maintain the integrity and security of applications, especially in environments where the execution of operating system commands is a necessity. By following such secure development best practices, the risk of vulnerabilities is significantly reduced and the robustness of the system against possible attacks is strengthened.

If we look at the ping code at the impossible level, the IP address is broken down, each part is checked separately, and then the IP is reassembled. In this way, we ensure that it is valid data.

$target = stripslashes($target);

// Dividir la IP en 4 octetos
$octets = explode(".", $target);

// Verificar si cada octeto es un número entero y si hay exactamente 4 octetos
if (count($octets) == 4 && ctype_digit($octets[0]) && ctype_digit($octets[1]) && ctype_digit($octets[2]) && ctype_digit($octets[3])) {
// Si los 4 octetos son enteros, vuelva a armar la IP.
$target = implode('.', $octets);
} else {
// Si la IP no es válida, manejar el error o tomar medidas apropiadas.
// Por ejemplo, registrar el intento de ataque o mostrar un mensaje de error.
die("Dirección IP no válida.");
}