Thursday, 19 August 2010
Securing PHP From XSS Attacks
« Police Force Privatization And Internet Security | Main | Big ColdFusion Vulnerability »In the coming months we will be putting more information onto the security blog in a relevant form for front-line engineers. We're happy to take any suggestions you have for what topics we should cover. In this entry we look at how to secure PHP applications from cross-site scripting.
A very common source of PHP security issues in cross site scripting (XSS) attacks based on using unfiltered user input in PHP driven HTML pages. Here is an example of a simple web form:
<html><body> <form action="showme.php" method="POST"> <textarea name="mytext"></textarea> <input type="submit"> </form> </body></html>
Here is the associated showme.php page with the XSS security issue:
<html><body> <?php echo( $_POST['mytext'] ) ?> </body></html>
This code allows an attacker to put anything he wants on the page, new tags, and of course, Javascript of his own design.
A simple way to secure the code is to use the PHP strip_tags function:
<html><body> <?php echo( strip_tags( $_POST['mytext'] ) ) ?> </body></html>
This will strip any HTML out of posted variable, thus negating any possibility of injected tags or attributes. You can loosen up this filtering by adding a second parameter to strip_tags with a list of allowed tags. However there are issues with the second parameter to strip_tags that you should be aware of.
It is important to understand how to validate input within a context. In this case I've simplified it by outputting HTML. But if you are putting the text into CSS or Javascript, you will need to understand what potential there is for adding malicious scripts in those contexts, and it won't be as easy as simply removing tags. Perhaps more on that in a followup blog.
We have more information on XSS attacks in PHP on our Vulncat site.
[Trackback URL for this entry]







