What’s the proper way to encode untrusted data for HTML attribute context? For example:
<input type="hidden" value="<?php echo $data; ?>" />
I usually use htmlentities() or htmlspecialchars() to do this:
<input type="hidden" value="<?php echo htmlentities($data); ?>" />
However, I recently ran into an issue where this was breaking my application when the data I needed to pass was a URL which needed to be handed off to JavaScript to change the page location:
<input id="foo" type="hidden" value="foo?bar=1&baz=2" />
<script>
// ...
window.location = document.getElementById('foo').value;
// ...
</script>
In this case, foo is a C program, and it doesn’t understand the encoded characters in the URL and segfaults.
I can simply grab the value in JavaScript and do something like value.replace('&', '&'), but that seems kludgy, and only works for ampersands.
So, my question is: is there a better way to go about the encoding or decoding of data that gets injected into HTML attributes?
I have read all of OWASP’s XSS Prevention Cheatsheet, and it sounds to me like as long as I’m careful to quote my attributes, then the only character I need to encode is the quote itself (") – in which case, I could use something like str_replace('"', '"', ...) – but, I’m not sure if I’m understanding it properly.
Your current method of using
htmlentities()orhtmlspecialchars()is the right approach.The example you provided is correct HTML:
The ampersand in the value attribute does indeed need to be HTML encoded, otherwise your HTML is invalid. Most browsers would parse it correctly with an
&in there, but that doesn’t change the fact that it’s invalid and you are correct to be encoding it.Your problem lies not in the encoding of the value, which is good, but in the fact that you’re using Javascript code that doesn’t decode it properly.
In fact, I’m surprised at this, because your JS code is accessing the DOM, and the DOM should be returning the decoded values.
I wrote a JSfiddle to prove this to myself: http://jsfiddle.net/qRd4Z/
Running this, it gives me an alert box with the decoded value as I expected. Changing it to
console.logalso give the result I expect. So I’m not sure why you’re getting different results? Perhaps you’re using a different browser? It might be worth specifying which one you’re testing with. Or perhaps you’ve double-encoded the entities by mistake? Can you confirm that’s not the case?