Insecure PHP Coding

While testing a web application today, I noticed an unusual 302 HTTP response. Normally a 302 response just has a header and no HTML code, because it's meant to be redirecting you to the page cited in the 'Location' field of the HTTP header. The 302 response had the HTML code which will be presented to the authenticated admin user, but we didn't have the admin credentials. So, how are we seeing this code? After analyzing the 302 redirect response, we concluded that this was the result of insecure coding. The following example explains this issue in PHP.

Insecure Code:

<?
session_start();

include ("../config.php");

echo $loggedin;

if ($loggedin != "1"){

header("Location: http://www.google.com"); /* Redirect browser */

}

{

echo "Will this code Get executed?";
}
?>

In this example, the code echo "Will this code Get executed?"; will indeed get executed irrespective of the value of $loggedin. This is a characteristic of PHP, and you won’t see this behavior in ASP.NET.

To secure this code, follow this:

<?
session_start();

include ("../config.php");

echo $loggedin;

if ($loggedin != "1"){

header("Location: http://www.google.com"); /* Redirect browser */

}

else
{

echo "Will this code Get executed?";
}
?>

Alternatively, this code can be secured by:

<?
session_start();

include ("../config.php");

echo $loggedin;

if ($loggedin != "1"){

header("Location: http://www.google.com"); /* Redirect browser */

die;
}

{

echo "Will this code Get executed?";
}
?>

It is very easy for a pentester to miss out this issue because in most cases you get redirected so fast that this page is not rendered by your browser. Unless you go through each 302 request manually, I don’t think you will be able to spot it. In this case, even WebInspect wasn't able to spot it. :)