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 .

3

2 Answers 2

1

by

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

without the surrounding quotes.

Sign up to request clarification or add additional context in comments.

6 Comments

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, 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 </script> 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.
json_encode($_GET['var'], JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS) Submitted edit to the answer.
without JSON_HEX_* the following attack is possible: <?php $_GET['var'] = " '><a href=/test>click me<!--"; ?> <div onmouseover='x = <?php echo json_encode($_GET['var']) ?>'></div>
@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.
|
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.