Wednesday, April 9, 2014

Avoiding XSS Vulnerability With $_SERVER['PHP_SELF']

Hey all,

Just wanted to add this little post to my blog about avoiding an exploit with using $_SERVER['PHP_SELF'].

For the longest time, I would use $_SERVER['PHP_SELF'] in my form action fields when the form parsing code was on the same page.

However, if not properly sanitized this function can easily be exploited.

Demonstration:

Here is a very simple html form with PHP processing on the same page. You will notice that the action of the form is the PHP_SELF server variable included within PHP.

This variable is pulled from the URL. Can you see the exploit?

<!DOCTYPE html>
<html>
<head>
<title>Form Exploit Demonstration</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<input type="text" name="foo">
<br>
<button type="submit" name="submit">Submit</button>
</form>
<?php
if(isset($_POST['submit']))
{
echo htmlspecialchars($_POST['foo']);
}
?>
</body>
</html>

If the user edits the URL, the PHP_SELF variable becomes that edited information.



With this, you can escape the action attribute, end the form, and then execute all sorts of nasty bits of code.

Of course, my favorite being the following...

"</form><div style="position: absolute; top: 0px; bottom: 0px; right: 0px; left: 0px; background-color: black; color: white; text-align: center; font-size: 100px;">Hacked :)</div>

Which results in...



This vulnerability can be patched by simply using htmlspecialchars to sanitize the PHP_SELF variable, or by simply just not using it and just hard coding in index.php.