XSS attack to bypass htmlspecialchars() function in value attribute

Also, it's important to mention that allowing people to inject HTML or JavaScript into your page (and not your datasource) carries no inherent security risk itself. There already exist browser extensions that allow you to modify the DOM and scripts on web pages, but since it's only client-side, they're the only ones that will know.

Where XSS becomes a problem is when people a) use it to bypass client-side validation or input filtering or b) when people use it to manipulate input fields (for example, changing the values of OPTION tags in an ACL to grant them permissions they shouldn't have). The ONLY way to prevent against these attacks is to sanitize and validate input on the server-side instead of, or in addition to, client-side validation.

For sanitizing HTML out of input, htmlspecialchars is perfectly adequate unless you WANT to allow certain tags, in which case you can use a library like HTMLPurifier. If you're placing user input in HREF, ONCLICK, or any attribute that allows scripting, you're just asking for trouble.

EDIT: Looking at your code, it looks like you aren't quoting your attributes! That's pretty silly. If someone put their username as:

john onclick="alert('hacking your megabits!1')"

Then your script would parse as:

<input type=text name=username value=john onclick="alert('hacking your megabits!1')">

ALWAYS use quotes around attributes. Even if they aren't user-inputted, it's a good habit to get into.

<input type="text" name="username" value="<?php echo htmlspecialchars($_POST['username']); ?>">

value is a normal HTML attribute, and has nothing to do with Javascript.
Therefore, String.fromCharCode is interpreted as a literal value, and is not executed.

In order to inject script, you first need to force the parser to close the attribute, which will be difficult to do without >'".

You forgot to put quotes around the attribute value, so all you need is a space.

Even if you do quote the value, it may still be vulnerable; see this page.


There's one way. You aren't passing htmlspecialchars() the third encoding parameter or checking encoding correctly, so:

$source = '<script>alert("xss")</script>';
$source = mb_convert_encoding($source, 'UTF-7');
$source = htmlspecialchars($source); //defaults to ISO-8859-1
header('Content-Type: text/html;charset=UTF-8');
echo '<html><head>' . $source . '</head></html>';

Only works if you can a) set the page to output UTF-7 or b) trick the page into doing so (e.g. iframe on a page without a clear charset set). The solution is to ensure all input is of the correct encoding, and that the expected encoding is correctly set on htmlspecialchars().

How it works? In UTF-7, <>" chars have different code points than UTF-8/ISO/ASCII so they are not escaped unless convert the output to UTF-8 for assurance (see iconv extension).

Tags:

Php

Security

Xss