On the JSON of web security

Source: Internet
Author: User

Objective

JSON (JavaScript Object Notation), can be said to be the fact that the browser, the server Exchange data standard. Visual inspection of other formats such as XML, or other custom formats, will be less and fewer.
Why is JSON so popular?
Seamless interfacing with JavaScript is a reason.
Another important reason is that you can implement cross-domain more easily. If it is XML, or other proprietary format, it is very difficult to implement cross-domain, to be implemented through flash.


Any data format, how to resolve improper processing, there will be a security vulnerability. Let's talk about some of the other JSON-related security stuff.
Before introducing, ask a few questions:

    • Why should XMLHttpRequest adhere to the same origin strategy?
    • Will XMLHttpRequest request a cookie?
    • <script scr= "..." > will the label request bring a cookie?
    • Submit a form to a website of another domain name, will it bring a cookie?
    • Can I bring a cookie with a cors request?
JSON injection sometimes, may be for convenience, someone will manually splicing the JSON, but this handy code, but may bring unexpected security risks.
in the first way, the concatenation of strings is used:
String user = "test01"; String password = "12345 ', admin: ' true"; String json = "{User: '%s ', Password: '%s '}"; System.out.println (String.Format (JSON, user, password))//{user: ' test01 ', Password: ' 12345 ', admin: ' True '}

The user has added administrator privileges.
the second, using parameter pollution, is similar to the HTTP parameter pollution
String string = "{User: ' test01 ', password: ' Hello ', Password: ' World '}"; Jsonobject parse = Json.parseobject (string); String Password = parse.getstring ("password"); SYSTEM.OUT.PRINTLN (password);//world
What happens when the JSON data key repeats? Most JSON parsing libraries are followed by parameters that overwrite the previous one.


The following shows an example of changing someone's password:

user%3dtest01%26password%3d12345%27%2cuser%3dtest02 "//user=test01&password=12345", user= Test02httpservletrequest request = null; String user = Request.getparameter ("user");//Check whether test01 logs on to string password = request.getparameter ("password"); String content = "{User: '" + user + "', Password: '" + Password + "'}"; User user = Json.parseobject (content, User.class),//{"password": "12345", "User": "test02"}updatedb (user);

So, don't manually stitch up the JSON string.

What should the browser side do with JSON data? Like eval this way, nature is not to be used.

Browsers now provide native methods Json.parse (str) to convert to JS objects.
If this is a IE8 browser, use this library to parse: HTTPS://GITHUB.COM/DOUGLASCROCKFORD/JSON-JS
Reference: Http://zh.wikipedia.org/wiki/JSON#.E5.AE.89.E5.85.A8.E6.80.A7.E5.95.8F.E9.A1.8C
The JSON parsing library is built into jquery


JSONP callback Injection provides a brief introduction to JSONP's working principle.
JSONP working principle: Using JS to insert a <script> tag on document, the SRC of the label points to the remote server's API address. The client and server contract the name of a callback function, and the server returns the data that the callback function wraps, and then the browser executes the callback function to get the data.
For example, jquery is implemented like this:
var url = ' http://localhost:8080/testJsonp?callback=? '; $.getjson (URL, function (data) {    alert (data)});
jquery automatically turns into a function with a timestamp special (to prevent caching):
  http://localhost:8080/testJsonp?callback=jQuery1102045087050669826567_1386230674292&_=1386230674293
The equivalent of inserting such a <script> tag:
<script src= "http://localhost:8080/testJsonp?callback=jQuery1102045087050669826567_1386230674292&_= 1386230674293 "></script>
The data returned by the server is this:
jquery1102045087050669826567_1386230674292 ({' name ': ' abc ', ' Age ': 18})
The browser executes the JS function directly.
So, if you do something on the name of the callback function, you can execute arbitrary JS code. Therefore, callback name must be strictly filtered.
Of course, the name of the callback function is usually controlled by the program itself, but it cannot be ruled out by other uses.
So callback the name of the function, how to filter? only legitimate JS functions should be allowed to be named, match with regular to be like this:
^[0-9a-za-z_.] +$
The regular may be slow, you can write a function to judge:
Static Boolean checkjsonpcallbackname (String name) {try {for (Byte c:name.getbytes ("Us-ascii")) {if ((c >= ' 0 ' && Amp C <= ' 9 ') | | (c >= ' a ' && c <= ' z ') | | (c >= ' A ' && C <= ' Z ') | | c = = ' _ ') {continue;} else {return false;}} return true;} catch (Throwable t) {return false;}}

In fact, the callback function name is strictly tested there are other benefits, is to prevent a lot of UTF-7 code attacks.

Because UTF-7 encoded headers are all with special characters, such as "+/v8", "+/v9", so that the request of illegal encoding is filtered out.

Jsonp the authentication of the request Jsonp in use, there are also easy to make errors are not authenticated users.
first, whether the operation is submitted by the user themselves, not other pages with <script> tags, or with <form> submitted
So check the request's refer, or verify the token. This is actually a category of csrf protection, but it is easily overlooked.
second, you want to verify the user's permissions.
Many times, it may just be verifying that the user is logged in. But did not carefully determine whether the user has permissions.
For example, through the JSONP request to modify the data of other users.
Therefore, it must be difficult to source the evidence. Determine refer, verify the identity of the user.
To search the dark clouds, you can find a number of similar vulnerabilities, all because the user's permissions are not strictly verified. Http://www.wooyun.org/searchbug.php?q=jsonp

JSON hijacking can define some setter functions for an object in JS, so there is a loophole that can be exploited.
For example, in the browser's JS console execution:
window.__definesetter__ (' x ', function () {alert (' x is being assigned! ');}); Window.x=1;
Will magically pop up an alert window stating that our defined setter function is working.
In combination with this, when using the <script> tag to request an external JSON API, if the returned array type, you can take advantage of stealing data.
For example, there is an API like this:
Http://www.test.com/friends
The returned data is a JSON Array:
[{' User ': ' test01 ', ' age ': 18},{' user ': ' test02, ' age ': 19},{' user ': ' test03 ', ' Age ': 20}]
Insert the following code on the attack page to get information about all the friends of the user.
<script>  object.prototype.__definesetter__ (' User ', function (obj)      {alert (obj);    }  ); </script><script src= "Http://www.test.com/friends" ></script>
This loophole in the previous years is very popular, such as QQ mailbox A vulnerability: http://www.wooyun.org/bugs/wooyun-2010-046

Now the browser has been fixed, you can download a Firefox3.0 version of the test. The current browser does not trigger the setter function when parsing the JSON array string. However, for a setting such as object.xxx, it will still be triggered.

The vulnerability of IE's UTF-7 code parsing problem has also been very popular. The use of the old version of IE can parse utf-7 encoded strings or files, bypassing the filtering of the server. Example of a dark cloud: http://www.wooyun.org/bugs/wooyun-2011-01293

There is such a jsonp calling interface:
http://jipiao.taobao.com/hotel/remote/livesearch.do?callback=%2B%2Fv8%20% 2badwaaab0ag0apga8agiabwbkahkapga8ahmaywbyagkacab0ad4ayqbsaguacgb0acgamqapadsapaavahmaywbyagkacab0ad4apaavagiabwbkahkapga 8ac8aaab0ag0apg
After the URL decoder is:
HTTP://JIPIAO.TAOBAO.COM/HOTEL/REMOTE/LIVESEARCH.DO?CALLBACK=+/V8 + adwaaab0ag0apga8agiabwbkahkapga8ahmaywbyagkacab0ad4ayqbsaguacgb0acgamqapadsapaavahmaywbyagkacab0ad4apaavagiabwbkahkapga8a C8aaab0ag0apg
Because the JSONP call is the data that is returned directly from the callback wrapper, in fact, the above request directly returns:
+/V8 + adwaaab0ag0apga8agiabwbkahkapga8ahmaywbyagkacab0ad4ayqbsaguacgb0acgamqapadsapaavahmaywbyagkacab0ad4apaavagiabwbkahkapga8a c8aaab0ag0apg-(call result data)
IE did the UTF-7 decoding after the data is such a child:


As a result, XSS is enforced.
It is also possible to use an IFRAME. But I test on IE8, the URL suffix needs to be HTML to trigger.
IE does not declare a request to return Content-type as a "text/html" type, and then parse the problem.as long as the server side explicitly sets the Content-type to "Application/json", IE does not recognize the encoding, it will not trigger the vulnerability. Therefore, the server-side Content-type must be set to. Although debugging after Setup is a bit cumbersome, it greatly improves security.

The JSON format is set to: "Application/json"
JavaScript is set to: "Application/x-javascript"
JavaScript also has some settings: "Text/javascript", etc., are not standard.

Some of the other stuff MongoDB injected

This is actually JSON injection, simple string concatenation, may cause a variety of data to be modified problems.

Problems with JSON parsing libraries

Some JSON library parsing libraries support circular referencing, so is it possible to construct special data that causes parsing to fail? Causing excessive CPU usage, denial of service, and so on?

A stackoverflowerror Bug in Fastjson:

Https://github.com/alibaba/fastjson/issues/76

Some JSON library parsing is problematic:

Http://www.freebuf.com/articles/web/10672.html

Json-p

Some people come up with a json-p specification, but there seems to be no browser to support this at the moment.
The principle is that for JSONP requests, the browser can request that the MIME returned by the server be "application/json-p" so that the JSON data can be strictly verified.

CORS (cross-origin Resource sharing)

In order to solve the security problem of cross-domain calls, the currently available scenario is cors:

Https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
http://www.w3.org/TR/cors/

The principle is that cross-domain calls are allowed through server-side settings, and then the browser allows XMLHttpRequest to be called across domains.

Cors can initiate get/post requests, unlike JSONP, where only get requests are initiated.

By default, Cors requests are not with cookies.

I personally think that this program is also very painful, one is the need for server configuration, the second is the Protocol complex. If the browser is not sure if it can be called across domains, a preflight Request must be made first.

In fact, even if the server does not allow the Cors,xmlhttprequest request is actually sent out, and return the data, but the browser did not let the JS environment to get it.

In addition, I think there is another possibility of data leakage: The hacker may control a route, he can not grab the bag, but he could insert some special head in the response, such as:

Then the XMLHttpRequest request is a cookie.

The initial problem

Back to the original question:

    • Why should XMLHttpRequest adhere to the same origin strategy?
Even if the XMLHttpRequest is not with a cookie, it is possible to cause a data leak. For example, the internal Web site is based on IP restrictions, if XMLHttpRequest does not adhere to the same-origin policy, then the attacker can make a request when the user browses the Web page, access to internal Web site data.
    • Will XMLHttpRequest request a cookie?
In the same domain scenario, the different domain conditions will not. If the server is set to Access-control-allow-credentials:true, it is also possible to take cookies across domains.
    • <script scr= "..." > will the label request bring a cookie?
Yes.
    • Submit a form to a website of another domain name, will it bring a cookie?
Yes. Summarize:
    • It is forbidden to manually stitch JSON strings, which should be output with the JSON library. Nor should you use methods such as Objecttojson, which you have implemented, because there may be a variety of places that are not considered.
    • The callback of the JSONP request is strictly filtered, allowing only "_", 0 to 9,a-z, A-Z, which is the name of the legitimate JavaScript function.
    • Jsonp requests also have to judge legitimacy, such as whether the user is logged on (this is easily overlooked).
    • Set the Content-type (this is inconvenient for debugging, but improves security).
    • Call the third-party interface in JSONP, the actual equivalent of introducing a third-party JS code, be cautious.

Reference:

http://www.json.org/

Http://www.slideshare.net/wurbanski/nosql-no-security

Https://github.com/douglascrockford/JSON-js

http://toolswebtop.com/Online encoding conversion, can convert UTF-7

http://www.thespanner.co.uk/2011/05/30/json-hijacking/

http://www.thespanner.co.uk/2009/11/23/bypassing-csp-for-fun-no-profit/

Http://stackoverflow.com/questions/1830050/why-same-origin-policy-for-xmlhttprequest

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.