2

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 .

neubert
  • 15,947
  • 24
  • 120
  • 212

2 Answers2

1

by

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

without the surrounding quotes.

Thomas
  • 11,958
  • 1
  • 14
  • 23
  • `htmlspecialchars` would still be needed for the `<` and `>` but I'm thinking that's the best answer. Well that and the fact that the surrounding string delimiters (single quote in this case) shouldn't be present since `json_encode` adds them. – neubert Feb 23 '17 at 17:15
  • @neubert, about `htmlspecialchars` for the html-tags. Just did a quick test on phpfiddle, and it seems that `json_encode()` takes care of that. Although it only escapes the backslash in the injected `` tag, checking the DOM, the Browser seems fine with that. So I'd be more worried that htmlspecialchars may change the string and therefore its meaning. – Thomas Feb 23 '17 at 17:38
  • `json_encode($_GET['var'], JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS)` Submitted edit to the answer. – Vasiliy Zverev Aug 30 '17 at 19:02
  • 2
    without `JSON_HEX_* ` the following attack is possible: `click me – Vasiliy Zverev Aug 30 '17 at 19:21
  • @VasiliyZverev Thanks for pointing this out, again I've learned something I wasn't aware of, but I don't think this applies to the actual question asked. – Thomas Aug 31 '17 at 17:32
  • 1
    @VasiliyZverev `onmouseover`'s value is JavaScript inside HTML, so for that you probably want to use `htmlspecialchars(json_encode($_GET['var']), ENT_QUOTES, 'UTF-8')` instead. – Sumit Jan 02 '19 at 10:13
1
<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>
Vasiliy Zverev
  • 622
  • 5
  • 10