7. Prevention

Always avoid using functions that execute system commands - especially if using user input with them.

Instead of using system, use built-in functions

input validation Whether using builtins or system command execution functions, always validate and sanitize user input. Validation is done to ensure it matches the expected format for input such that request is denied if it does not match. must be done on both front-end and back-end to be effective. in php there's builtin filters for a variety of standard formats like emails, urls, even IPs which can be used with filter_var as follows:

if (filter_var($_GET['ip'], FILTER_VALIDATE_IP)) {
    // call function
} else {
    // deny request
}

if we wanted to validate a different non-standard format we can use a regex + preg_match function the same can be achieved with JS for both front/backend

if(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ip)){
    // call function
}
else{
    // deny request
}

just as in PHP, w/ NodeJS


Input sanitization

Most critical part for preventing any injection vulnerability is input sanitization

in example code, we saw that when dealing with character and command filters, it was blacklisting certain words + looking for them in user input. generally this is not a good enough approach to preventing injections - use builtins to remove special characters and preg_replace to remove any special chars from user input.

$ip = preg_replace('/[^A-Za-z0-9.]/', '', $_GET['ip']);

Above allways only alphanumerical characters and allows a dot as required for IPs.

Same thing for JS

var ip = ip.replace(/[^A-Za-z0-9.]/g, '');

DOMPurify library for NodeJS

import DOMPurify from 'dompurify';
var ip = DOMPurify.sanitize(ip);

In certain cases we want to allow special chars, use the same filter_var function used with input validation and use escapeshellcmd filter to escape any special chars so injections are blocked.


Server configurations

We should make sure our back-end server is securely configured to reduce the impact in the event that the webserver is compromised. Some configurations to implement are below:


Ultimately even after all of these security mitigations we have to perform pentesting techniques we learned in this module to see if any webapp functionality may still be vulnerable to command injection.

Some webapps have millions of lines of code and any single mistake in any line of code may be enough to introduce a vulnerability.