4

This is my source code:

<!DOCTYPE html>
<html>
  <head>
    <title>XSS</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
    <script>
    var output = "";
    <?php
    if (isset($_GET['q'])) {
      printf('output = "%s";', htmlspecialchars($_GET['q'],ENT_QUOTES, 'UTF-8'));
    }
    ?>

    $(function()  {
      $("#output").html(output);
    });
    </script>
  </head>
  <body>
    <p id="output"></p>
  </body>
</html> 

When I send q=\x3cscript\x3ealert(1)\x3c/script\x3e to my script, the alert is fired. How can I prevent this?

Anders
  • 64,406
  • 24
  • 178
  • 215
Sigi Amon
  • 41
  • 1
  • 5
    Possible duplicate of [PHP functions for preventing XSS](https://security.stackexchange.com/questions/8798/php-functions-for-preventing-xss) – Black Magic Mar 22 '17 at 07:19

1 Answers1

8

Escaping is context sensitive. You are escaping for HTML, but are using the variable in Javascript. Instead, correctly encode for JavaScript using json_encode:

printf('output = %s;', json_encode($_GET['q']));

Also, you are using the html function even though you don't seem to want HTML at all. What you probably want is the text function:

$("#output").text(output);
Sjoerd
  • 28,707
  • 12
  • 74
  • 102