JoeCortopassi
JoeCortopassi

Reputation: 5093

Addslashes safe to protect against xss in array?

Came across some code today that had a javascript array, made in php, using only php's addslashes() to sanitize. At first I thought this was an easy XSS vulnerability, but I haven't been able to see it's flaw. Here's an example of what I'm talking about:

foo.php

$itemList = "[";

foreach ($array as $item) 
{
    $itemList .= "'".addslashes($item)."',";
}

$itemList = "'']";

bar.html

<script>
    var a = <?php echo $itemList; ?>
</script>

Obviously something like ']; alert("xss"); b=[' won't be effective because it will be turned into \']; alert(\"xss\"); b=[\'. So is this really safe, and my code smell is non-existent?

`

`

Edit:

Can someone show me how this doesn't work? I know that this is not best practice, and would not use this in my code, but if I want to rewrite the code I need proof to convince others

Upvotes: 4

Views: 951

Answers (1)

Halcyon
Halcyon

Reputation: 57709

No, no no no no no.

Use the right function for the right job.

addslashes is not an escape function for any context, it just adds slashes.

If you're printing to HTML use htmlentities (or htmlspecialchars if applicable).

If you're printing to JavaScript use json_encode.

If you're building a MySQL query use mysql_real_escape_string

etc.


Oppurtunities for abuse when using addslashes instead of json_encode is for instance the string: "</script><iframe src=hxxp://phising.mywebsite.com>"

This will end the script and insert an iframe from an untrustworthy and potentially harmful domain.

Upvotes: 6

Related Questions