19

While working on a project that used the REST API for Gerrit Code Review I noticed that they do something that I thought was strange Source:

To prevent against Cross Site Script Inclusion (XSSI) attacks, the JSON response body starts with a magic prefix line that must be stripped before feeding the rest of the response body to a JSON parser:

)]}'
[ ... valid JSON ... ]

How does prefixing the response body with seemingly random characters work to prevent XSSI?

Anders
  • 64,406
  • 24
  • 178
  • 215
ecnepsnai
  • 347
  • 2
  • 14
  • By the way, Mozilla added support for parsing such responses in dev tools of Firefox 81.0. https://bugzilla.mozilla.org/show_bug.cgi?id=1635835 – Palec Nov 08 '20 at 13:09

1 Answers1

18

XSSI works by trying to evaluate a JSON response as Javascript and the sequence )]}' prevents this by reliably producing a syntax error.

There have been different proposed countermeasures against unwanted script inclusion, but putting an infinite loop (I have seen for(;;) used in Facebook APIs) or producing a syntax error (some Google APIs use )]}' as in your example) has shown to be sufficiently sound and is backward compatible. This article has some additional examples.

If you're unsure about why XSSI is a threat in the first place and violates the same-origin policy, read about it here.

Arminius
  • 43,922
  • 13
  • 140
  • 136
  • '...evaluate your JSON response as Javascript' Is that common? It seems like a really unsafe practice. – ecnepsnai Jan 14 '16 at 17:27
  • 1
    @ecnepsnai It's a concept to overcome cross-origin restrictions and the core idea of JSONP. https://en.wikipedia.org/wiki/JSONP – Arminius Jan 14 '16 at 17:53
  • LOL -- "The browser's security mechanisms won't let me load this JSON data from a foreign source. I know! Embed the data inside javascript and eval() it!". That sounds like a terrible idea.... – Mike Ounsworth Aug 14 '19 at 19:05