Same-origin strategy-browser security defender

Source: Internet
Author: User
Tags domain server


For software developers, understand the same-origin strategy. Can be very good to overcome a pain point. Read and write resources under different domain names!

The ancient Chu Chu the boundary of the two sides clearly stipulated. Assuming that there are no such boundaries, the world will be in great turmoil. The same, in our browser, there are some boundaries and strategies, so that the Web world can be so beautiful present in front of us. These security policies effectively protect the local security and web security of the user's computer.

Homologous policy

Browsers have a very important concept-the same-Origin strategy (Same-origin policy). The so-called homology refers to the domain name, agreement. Port also. The client foot (JavaScript, ActionScript) of different sources cannot read or write the resources of the other party without understanding the authorization.

Homologous policy, which is determined by the

From_id=2778944&type=syn&fromtitle=netscape&fr=aladdin "target=" _blank "style=" Color:rgb (40,161,197) ; Text-decoration:none "A well-known security strategy proposed by >netscape, which is now used by all JavaScript-enabled browsers.
As a matter of fact. Such a strategy is only a specification, not a mandatory requirement, the browser of the major vendors is only for the same origin of the implementation of the policy.

It is the core of the browser and the most important security features. Assume that the same Origin policy is missing. The normal functionality of the browser may be affected. It is possible to say that the web is built on the same Origin strategy.

Suppose the web world doesn't have a homologous policy when you sign in to a Gmail mailbox and open a website. JavaScript on this site will be able to read your Gmail mailbox data across domains, so there's no privacy in the entire web world.

Cookies in a cookie-hijacking browser become unsafe, and a Web page under a domain name can read all of the cookies in your browser, assuming that the attacker is able to obtain a cookie for the user's login credentials and can even bypass the login process. Directly set the value of this cookie to access the user's account.

Examples Show
    • Examples of different sources

      • Domain name:
        Http://www.bigertech.com, http://bigertech.com, http://bigertech.cn
      • Protocol: HTTP, HTTPS
      • port:http://127.0.0.1:8001, http://127.0.0.1:8002
    • Homologous examples
      http://www.bigertech.com/a, http://www.bigertech.com/b, these two URLs are just different folders under the same domain name, nature is consistent with the same-origin policy

Security Defense

Client attacks are mainly from JavaScript scripts, which are now read and written to unauthorized resources .

There are very many resources on the web. Some have only read permission, some have read and write permission at the same time. For example: The Referer (representing the request source) in the HTTP request header is only readable. Homology and different sources are inferred based on this referer value. The Document.cookie has read and write access.

This distinction is also for security reasons.

Cross-Domain requests

For example, in a page using AJAX to send a request, the requested address is another site,
Note:
Ajax is an abbreviation for asynchronous JavaScript and XML. Let the data be transferred asynchronously in the background. Common usage scenarios are: When updating the local data of a webpage, you do not need to refresh the entire page. To conserve bandwidth resources.

Ajax is also a common technique used by hackers for WebClient attacks, which can be done silently in the background of a browser. Do "Kill invisible."

Click to view the response data: The Mobile attribution API
assumes the use of Ajax to send requests. such as the following

$.ajax(‘http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?

tel=15850781443‘);

Response data, OOP error

XMLHttpRequest cannot load http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=15850781443. No ‘Access-Control-Allow-Origin‘ header is present on the requested resource. Origin ‘http://www.baidu.com‘ is therefore not allowed access.

Because of different sources, the browser intercepts this action and then returns an error to the user.

How to Solve

The target site, if it is http://tcc.taobao.com clear return HTTP response header:

Access-Control-Allow-Origin: http://www.evil.com

or set to *, agree to all sites for the same-origin access, but it is also too insecure.

Using JSONP to solve cross-domain problems

JSONP (JSON with Padding) is an unofficial protocol. It agreed to integrate script tags on the server side to return to the client and implement cross-domain access via JavaScript callback (this is JSONP simple implementation form).

Give me a sample.

client 
The URL Service that provides JSONP support in client invocation. Gets the JSONP format data.
For example, customers want to visit http://www.yiwuku.com/myservice?

jsonp=oncustomerloaded
If the customer expects to return JSON data: [" customername1 "," customername2 "]
then really returns the number of data to the client:

callbackfunction ([" Customername1 "," customername2 "])  
<script type="text/javascript">      function onCustomerLoaded(result, methodName){          conssole.log(result);//  输出结果 ["customername1","customername2"]      }</script><script type="text/javascript" src="http://www.yiwuku.com/myService?jsonp=onCustomerLoaded"></script>

Server side:

String callback = request.getParameter("callback");out.println(callback + "(‘" + data+ "‘)");

Or using jquery's AJAX solution

$.ajax ({url: ' http://localhost:8080/test2/searchJSONResult.action ', type:" GET ", DataType: ' Jsonp ', data: {name: ' Zhanghuihua '}, timeout:5000, Success:function (JSON) {//clientjquery pre-defined     The callback function, which successfully obtains the JSON data on a cross-domain server, dynamically runs the callback function alert (JSON); }, Error:function () {alert ("Request failed!      "); }  });

Script tags in HTML can load and run JavaScript from other domains, so we can dynamically load resources from other domains with the script tag.

JSONP is easy to implement, but there are also some security pitfalls, assuming that third-party scripts run arbitrarily. Then it can tamper with the page content and intercept sensitive data. However, JSONP is the right choice for passing data between trusted parties.

The problems brought by JSONP

JSONP is the same time to facilitate cross-site issues. There is a certain potential risk. The following examples illustrate their risks.

For example, Jsonptest.htm provides a call in JSONP format. Returns data in the following format callBack({"json":"jsonTest"}) .

  • Script Injection
    The function name of the callback and the input have not been made two times.

    For example, user input such as the following request:
    xxx.com/jsonpTest.htm?

    jsonp=alert(‘OK‘);
    If the server is just filtering, the response content isalert("OK");{"json":"jsonTest"}
    Suppose the JSONP request is:

    xxx.com/jsonpTest.htm?jsonp=

    If the server is just filtering, the response is:
    ;{xx}
    Users click on the image, there will be XSS attacks.

  • Malicious attacks
    Safe-escaping filtering of the input, but not qualifying the valid characters of the JSONP callback. The following parameters remain intact after being safely escaped.

    while (true) {alert (Document.cookie)} An attacker can use this parameter to spoof a user.

  • How to Solve
    • Necessary secure escape of output content
    • The safe character range for a JSONP-qualified callback method name is (a-za-z0-9$)
    • Setting the response type is a non-JSON or JavaScript type, for example text/html. Prevents an attacker from entering the URL of the JSONP request directly. The content of the response is executed as JS when the data is received by the browser.

Many other workarounds for cross-domain
  • Suppose it is a simple single communication such as log, a new ,<script>,<link>,<iframe> element, set to the destination URL by the Src,href property. Implementing Cross-Domain requests
  • In modern browsers, multi-form communication uses the HTML5 specification targetWindow.postMessage(data, origin); , where data is the object that needs to be sent, and origin is the origin of the target form. window.addEventListener(‘message‘, handler, false);handler Event.data is the data sent by PostMessage, Event.origin is the form reference that sends the message to the Origin,event.source of the form
  • Internal server Proxy requests cross-domain URLs. And then return the data
  • Cross-domain request data, modern browsers can use the HTML5 specification of the Cors feature, only the target server return HTTP header access-control-allow-origin: Can be like ordinary Ajax access to cross-domain resources
References:
    • Baidu Encyclopedia
    • Browser-Origin policy
    • Jsonp to cross-domain access requests by breaking the same-origin policy
    • 10 ways to share cross-domain resources

Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

Same-origin strategy-browser security defender

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.