开发者

XSS : Creating a javascript object using PHP's json_encode

开发者 https://www.devze.com 2023-03-03 23:54 出处:网络
Is this 100% safe against XSS? If not, can you please provide example bad string text showing开发者_运维问答 me why it is not.

Is this 100% safe against XSS? If not, can you please provide example bad string text showing开发者_运维问答 me why it is not.

<html>
  <body>
    <script>
      <?php
        $bad = "some bad string.  please give example text that makes the below unsafe";
        echo "var a = ".json_encode($bad).";";
        echo "var b = ".json_encode(array($bad)).";";
      ?>
    </script>
  </body>
</html>

Thanks.


In short, it's safe. Possible XSS would require escaping from the javascript string (") or script (</script>). Both strings are properly escaped:

"          becomes  \"
</script>  becomes  <\/script>

This is the the part about direct injection. Your application should take in account that some array elements may be missing. Another possibility is that an array element is not the type you would expect (e.g., an array instead of a string)


Definitely not!!!

Don't use json_encode to escape javascript.

for example:

json_encode<img src=# onerror=alert(1)>, this will escape nothing and output to brower. This is a xss.

use htmlspecialchars instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号