neubert
neubert

Reputation: 16782

how to prevent XSS in javascript string

Let's say I have something like this:

<script>
var string = '<?= $_GET['var'] ?>';
</script>

To prevent XSS I'd want to make sure the single quotes are escaped. addslashes could do that but people could still break out of that by setting $_GET['var'] to . eg.

<script>
var string = '</script><script>alert(/test/)</script>';
</script>

Maybe I should escape (with \) single quotes and <? Is that all I'd need to escape?

I suppose attacks like this are harder now that browsers often disable code from being ran that shows up in the GET string but idk I still think it's something that ought to be protected against .

Upvotes: 2

Views: 1211

Answers (2)

Vasiliy Zverev
Vasiliy Zverev

Reputation: 643

<script>
var string = <?= json_encode($_GET['var'], JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS) ?>;
</script>

Please note that no surrounding quotes needed. json_encode() produces quoted string "bla-bla-bla". Parameters JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS convert ", <, >, &, ' to hex like \u003C. This helps against XSS when JS is inline:

<?php
    $_GET['var'] = " '><a href=/test>click me<!--";
?>
<div onmouseover='x = <?= json_encode($_GET['var'], JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS) ?>'></div>

Upvotes: 1

Thomas
Thomas

Reputation: 12637

by

<script>
var string = <?= json_encode($_GET['var']) ?>;
</script>

without the surrounding quotes.

Upvotes: 1

Related Questions