3

I saw the following comment in Spring JSON messageConverter:

/**
 * Indicate whether the JSON output by this view should be prefixed with "{} &&". Default is false.
 * <p>Prefixing the JSON string in this manner is used to help prevent JSON Hijacking.
 * The prefix renders the string syntactically invalid as a script so that it cannot be hijacked.
 * This prefix does not affect the evaluation of JSON, but if JSON validation is performed on the
 * string, the prefix would need to be ignored.
 */

How does string prefixing work to prevent JSON hijacks?

Maximillian Laumeister
  • 19,884
  • 8
  • 59
  • 78
Chinaxing
  • 8,054
  • 4
  • 28
  • 36
  • Great, I didn't know that Spring supports this. Could you please share which class and package this comment is in? – Sanjay Aug 09 '15 at 07:21
  • @Sanjay it is `org.springframework.http.converter.json.MappingJackson2HttpMessageConverter` - see `setPrefixJson()` method – bedrin Aug 09 '15 at 17:40

2 Answers2

2

Contrived example: say Google has a URL like mail.google.com/json?action=inbox which returns the first 50 messages of your inbox in JSON format. Evil websites on other domains can't make AJAX requests to get this data due to the same-origin policy, but they can include the URL via a tag. The URL is visited with your cookies, and by overriding the global array constructor or accessor methods they can have a method called whenever an object (array or hash) attribute is set, allowing them to read the JSON content.

The {} && prevents this: an AJAX request at mail.google.com will have full access to the text content, and can strip it away. But a tag insertion blindly executes the JavaScript without any processing. Since {} is a falsey value the actual response would never be parsed

Other frameworks add different content to the response, like while(1); (example from Google) which causes an infinite loop for a hacker, but we can strip it out on our own site

bedrin
  • 4,458
  • 32
  • 53
0

The addition of the prefix will invalidate the string.

I think you may want to check this Stackoverflow question and comments to it: Difference between ")]}',\n" and "{} &&" in avoiding json hijacking

Community
  • 1
  • 1
Viorel
  • 337
  • 2
  • 12