Security challenge: is htmlentities enough to prevent XSS?

Consider this example:

[php]<?php

function escape ($unescaped) {
return htmlentities($unescaped, ENT_QUOTES, ‘UTF-8’);
}

$data = !empty($_GET[‘data’]) ? $_GET[‘data’] : null;
?>

<?= escape($data) ?>[/php]

[php]// http://test.local/?data=xss

// Output:
xss<script>alert(document.cookie);</script>[/php]

Seems pretty safe, right? But would you trust htmlentities with all of your output escaping?

You shouldn’t.

What if somewhere on the page, you do this:

[php]<?php

function escape ($unescaped) {
return htmlentities($unescaped, ENT_QUOTES, ‘UTF-8’);
}

$data = !empty($_GET[‘data’]) ? $_GET[‘data’] : null;
?>

[/php]

Is it still safe?

First one with a XSS vector that rick rolls* me, and issues a fix** gets a cookie (karma point).

So htmlentities is safe for XSS everywhere except in Javascript, where you have to escape the data before using it.

So in the second example, potentially this will work.

[php][/php]

I also read this class would work as well

http://owasp-esapi-java.googlecode.com/svn/trunk_doc/latest/org/owasp/esapi/ESAPI.html

Again, I don’t know if these answers are correct and are not off the top of my head, I had to do some research. Thanks for the challenge…

I should have been clearer :slight_smile:

Use this code with no edits:
[php] <?php

function escape ($unescaped) {
return htmlentities($unescaped, ENT_QUOTES, ‘UTF-8’);
}

$data = !empty($_GET[‘data’]) ? $_GET[‘data’] : null;
?>

[/php]

What can you send in as GET[‘data’] in order to trigger XSS?

http://test.local/?data=xss vector here

I’m still trying, I haven’t given up yet!

Good luck :slight_smile:

And to anyone wondering, understanding your enemy is sometimes key :slight_smile:

Sponsor our Newsletter | Privacy Policy | Terms of Service