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
No, no no no no no.
Use the right function for the right job.
addslashesis not an escape function for any context, it just adds slashes.If you’re printing to HTML use
htmlentities(orhtmlspecialcharsif applicable).If you’re printing to JavaScript use
json_encode.If you’re building a MySQL query use
mysql_real_escape_stringetc.
Oppurtunities for abuse when using
addslashesinstead ofjson_encodeis 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.