void
void

Reputation: 405

How to prevent against XSS located in Javascript HREF attribute?

<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 &quot;, but the HTML parser will still interpret the &quot; as a valid ":

If you try this code, you will see that the alert is displayed:

<a href='javascript:do_something("&quot;+alert(&quot;injected&quot;)+&quot;");'>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 &quot;, 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

Answers (1)

Philip F.
Philip F.

Reputation: 1237

You can use a meta-tag and set your content-security-policy to forbid inline javascript:

<meta http-equiv="Content-Security-Policy" content="script-src 'self'">

See CSP for further information.

Upvotes: 9

Related Questions