Injection is an attack that involves breaking out of a data context and switching into a code context through the use of special characters that are significant in the interpreter being used. - OWASP
Many PHP applications will HTML encode any untrusted data using htmlentities() irrespective of context. This is a problem as htmlentities does not mitigate certain XSS injections. For example, the output of any data that will be used as a URL:
echo '<a href="', htmlentities( 'javascript:alert("xss");' ), '">XSS</a>';
In this instance htmlentities is not sufficient protection, the above outputs
<a href="javascript:alert("xss");">XSS</a>
To prevent this injection URLs should be validated on input, and htmlentites() encoded on output.
$url = 'http://hostname/path?arg=value';
$parsedUrl = parse_url( $url );
if( $parsedUrl['scheme'] != 'http' && $parsedUrl['scheme'] != 'https' ) {
// reject URL
} else {
$url = mysqli_real_escape_string( $mysqli, $url );
$sql = "INSERT INTO table (url) VALUES ('$url')";
// insert query
}
...
echo '<a href="', htmlentities( $url ), '">XSS</a>', "\n";
The URL now stored in the database should still be output using htmlentities() to encode quote marks that could inject further code, such as in this example:
http://www.test.com/" onClick="javascript:alert(\'xss\');"
For further information about XSS, the OWASP XSS (Cross Site Scripting) Prevention Cheat Sheet offers a list of XSS Prevention Rules, while RSnake’s XSS (Cross Site Scripting) Cheat Sheet is the definitive list of XSS injection test strings.
Recent Posts
- Travis CI Chef Cookbooks
- The network is reliable
- Jeremy Ashkenas – Taking JavaScript Seriously with Backbone.js
- Signs that you’re a good programmer
- Signs that you’re a bad programmer
- How to Test Software (or: Teach Yourself to be a QA)
- Know Your Onions (and Antipatterns)
- Clean Code and Clean TDD Cheat Sheets
- The Definitive Guide to Bash Command Line History
- The analogy of print and code reviews
Archives
- June 2013
- May 2013
- April 2013
- March 2013
- February 2013
- January 2013
- December 2012
- November 2012
- October 2012
- September 2012
- August 2012
- July 2012
- June 2012
- May 2012
- April 2012
- March 2012
- February 2012
- January 2012
- December 2011
- November 2011
- October 2011
- September 2011
- August 2011
- July 2011
- June 2011
- May 2011
- April 2011
- March 2011
- February 2011
- January 2011
- October 2010
- April 2010
- March 2010
Pages
Recent Comments


