Format String Vulnerabilities, PHP, WEB

Prevent Format String Vulnerabilities in PHP

Format string exploits can be used to crash a program (DoS) or to execute harmful code. The use of unfiltered user input in functions such as printf() or sprintf() are the causes of this vulnerability.

The attacker could use this kind of vulnerability to land Denial-of-service attacks, use the %x format specifier to print sections of memory or use the %d, %u or %x format specifiers to overwrite the instruction pointer.

To prevent it, use format specifiers and always validate user input.

Vulnerable php code:

//other vulnerabilities also arise here, such as XSS, but let's focus on format string vuln only.
if(isset($_GET['username']))
	echo sprintf('Hi, ', $_GET['username']);

Secure php code:

if(isset($_GET['username'])){
	$tainted_username = $_GET['username'];
	$username = validate_username($tainted_username)==1?$tainted_username:'';
	echo sprintf("Hi, %s.", $username);
}
 
function validate_username($username) 
{
    return preg_match('/^\w+$/',$username);
}