Is json_encode Sufficient XSS Protection?

前端 未结 5 409
挽巷
挽巷 2020-12-25 13:49

I have a stdClass object in PHP, something like

$o = new stdClass;
$o->foo = $bar

The variable $bar contains a

相关标签:
5条回答
  • 2020-12-25 14:21

    What I do is to evaluate the json object before assuming its safe. I think the method is evalJSON(true) in prototype and jquery has a similar implementation. I don't know much about xss standards with JSON but this helps me

    0 讨论(0)
  • 2020-12-25 14:24

    Seems as through the best answer to this question lies in another question.

    To sum up, PHP's JSON encoder escapes all non ASCII characters, so newlines/carriage returns can't be inserted to bollacks up the Javascript string portion of the JSON property. This may not be true of other JSON encoders.

    However, passing in a raw string to JSON encode can lead to the usual litany of XSS attacks, the following combination of constants is suggested.

    var v= <?php echo json_encode($value, JSON_HEX_QUOT|JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS); ?>;
    

    or ensure the variable passed to json_encode is really an object.

    0 讨论(0)
  • 2020-12-25 14:27

    XSS is very broad and it's actually impossible to know at any time whether untrusted data you are emitting is safe.

    The answer is really that it depends on the situation. json_encode does no escaping on its own whatsoever -- you're only using it for serialization purposes. The escape function you want to use would be htmlspecialchars.

    However, whether or not you even want to use htmlspecialchars depends. For example, will you insert the value of o.foo using innerHTML or textContent? The latter would lead to a double-escape, but the former would insert a script. What about if you were going to use eval (in JS)?

    By the way addslashes is not functionally equivalent to mysql escaping.

    I wouldn't mix JavaScript and PHP in this way to begin with, but that's another story.

    0 讨论(0)
  • 2020-12-25 14:31

    this will work ;)

    ...?payload=<img%20src=x%20onerror=alert(document.cookie);>
    

    with json_encode ...

    <?php echo json_encode($_GET['payload']); ?>
    

    ;)

    0 讨论(0)
  • 2020-12-25 14:32

    As other answers have said; json_encode is not built for anti-xss protections. Unless you specifically encode the unsafe string (or sanitize properly) you're going to have a potential issue.

    Furthermore, once that string is extracted from the JSON object, it is still potentially hazardous if injected into the page at any point. For example:

    <?php $a->foo = "<script>alert(1)</script>"; ?>
    var v = <?php echo json_encode($a); ?>
    

    isn't likely to execute (although you can't be certain). But if you were to do:

    $('#some-element').html(v.foo);
    

    you would absolutely encounter a vulnerability.

    0 讨论(0)
提交回复
热议问题