PHP: htmlEntities() and Cross Site Scripting

When printing user input in an attribute of an HTML tag, the default configuration of htmlEntities() doesn’t protect you against Cross Site Scripting (XSS), when using single quotes to define the border of the tag’s attribute-value. XSS is then possible by injecting a single quote:

<?php
$_GET[‘a’] = “#000′ onload=’alert(document.cookie)”;
?>

XSS possible (insecure):

<?php
$href = htmlEntities($_GET[‘a’]);
print “<body bgcolor=’$href’>”; # results in: <body bgcolor=’#000′ onload=’alert(document.cookie)’>
?>

Use the ‘ENT_QUOTES’ quote style option, to ensure no XSS is possible and your application is secure:

<?php
$href = htmlEntities($_GET[‘a’], ENT_QUOTES);
print “<body bgcolor=’$href’>”; # results in: <body bgcolor=’#000&#039; onload=&#039;alert(document.cookie)’>
?>

The ‘ENT_QUOTES’ option doesn’t protect you against JavaScript evaluation in certain tag’s attributes, like the ‘href’ attribute of the ‘a’ tag. When clicked on the link below, the given JavaScript will get executed:

<?php
$_GET[‘a’] = ‘javascript:alert(document.cookie)’;
$href = htmlEntities($_GET[‘a’], ENT_QUOTES);
print “<a href=’$href’>link</a>”; # results in: <a href=’javascript:alert(document.cookie)’>link</a>
?>

About Sijmen Ruwhof

Independent IT Security Researcher / Ethical Hacker
This entry was posted in cross site scripting, PHP security. Bookmark the permalink.