Reputation: 405
<a href='javascript:do_something("<?php echo $untrusted_input; ?>");'>Test</a>
<script>
function do_something(str) {
//...
}
</script>
I am wondering how to encode the variable $untrusted_input
(for instance in PHP) in order to avoid XSS (javascript injections) being executed?
In this case, the htmlspecialchars
function is insecure because it replaces the injected "
with "
, but the HTML parser will still interpret the "
as a valid "
:
If you try this code, you will see that the alert is displayed:
<a href='javascript:do_something(""+alert("injected")+"");'>Test 4</a>
<script>
function do_something(str) {
//...
}
</script>
And the addslashes
function is also insecure because it adds slashes before '
and "
but does not encode "
, so it is possible to escape using the example above.
Please note that I am asking this question as a cyber-security researcher and I would like to know the way we could easily remediate this problem ? As a developer, I never do this way.
Thanks,
Upvotes: 3
Views: 1337