JS homology policy and cross-domain access

Source: Internet
Author: User

The same Origin policy is a convention that is the most central and basic security feature of the browser, and if the same origin policy is absent, the normal functionality of the browser may be affected. It can be said that the Web is built on the basis of the same origin policy, the browser is only for the same origin of the implementation of the policy.

1. What is a homologous policy

Understanding cross-Domain must first understand the Origin policy. The same-origin policy is a very important security policy that is implemented on the browser for security reasons.

What is homology :

URLs consist of protocols, domain names, ports, and paths, and if the protocol, domain name, and port of the two URLs are the same, they are homologous.

homologous Policy :

The browser's same-origin policy restricts the "document" or script from different sources to read or set certain properties on the current document. (White hat speaks web security [1])

Scripts loaded from one domain do not allow access to the document properties of another domain.

As an example:

For example, a malicious Web page with an IFRAME embedded in the bank's login page (the two different sources), if there is no homologous restrictions, the malicious Web page JavaScript script can be logged in the bank when the user to obtain a user name and password.

In the browser,<script>, , <iframe>, <link> and other tags can load cross-domain resources, regardless of the same-origin restrictions, but the browser restricts the permissions of JavaScript so that it can not read, Writes the contents of the load.

In addition, the same-origin policy only restricts the HTML document of the Web page, and other static resources such as JavaScript, CSS, pictures, etc., are still considered to belong to the same origin.

For example, I want to in the test code iframe Baidu's homepage:

  

<HTML><Head><title>Test same Origin policy</title></Head><Body><iframeID= "Test"src= "https://www.baidu.com/"></iframe><Scripttype= "Text/javascript">document.getElementById ("Test"). ContentDocument.body.innerHTML= "Write somthing";</Script></Body></HTML>

Different protocols, Access denied.

The domain property of the Document object holds the host name of the server on which it is mounted, which can be set.
For example, from "Blog.csdn.net" and pages from "Bbs.csdn.net", the document.domain is set to "Csdn.net", and scripts from two subdomains can be accessed from one another.
For security reasons, it cannot be set to another primary domain, such as http://www.csdn.net/cannot be set to Sina.com

2. Ajax Cross-Domain

Ajax (XMLHttpRequest) requests are limited by the same-origin policy.

Ajax is able to interact with remote servers through XMLHttpRequest, and XMLHttpRequest is a purely JavaScript object, and the interactive process is done in the background, and the user is not easily aware.

As a result,XMLHTTP has actually breached the security limitations of the original JavaScript.

As an example:

Given that a site references JavaScript from other sites, the site is compromise and added to JavaScript to get user input and submit it to other sites via Ajax, so you can collect information continuously.

or a Web site because of a vulnerability causes XSS to inject JavaScript script, the script can be AJAX to obtain user information and through Ajax to other sites, so that the continuous collection of information.

If we want to take advantage of XMLHTTP's non-flush asynchronous interaction capabilities and are reluctant to break through JavaScript's security strategy, the alternative is to give XMLHTTP a strict homology limit.

Such a security policy is similar to the security policy of an applet. The limitations of the IFRAME are also simply the inability to access data in cross-domain htmldom, while XMLHTTP essentially restricts the submission of cross-domain requests. (In fact, it is mentioned below that Cors has relaxed the restrictions)

With the development of AJAX Technology and Network service, the requirement of cross-domain is more and more strong. The following describes the cross-domain technology of Ajax.

2.1 JSONP

JSONP technology is actually not related to Ajax. We know that the <script> tag can load a cross-domain JavaScript script, and that the loaded script and the current document belong to the same domain. The data and functions in the script can therefore be called/accessed in the document. If the data in the JavaScript script is generated dynamically, the data interaction with the server can be implemented as long as the <script> tags are dynamically created in the document.

JSONP is the ability to access cross-domain data using the cross-domain capabilities of <script> tags, requesting dynamically generated JavaScript scripts to take a callback function name as a parameter. The JavaScript function where the callback function is the local document, the server-side dynamically generated script generates the data and calls the callback function in the code with the resulting data as parameters. When this script is loaded into a local document, the callback function is called.

Test page for the first site (http://localhost:8080/test.html):

<script src= "Http://localhost:8081/test_data.js" >   <script>     function  test_ Handler (data) {       console.log (data);      </script>

Server-side JavaScript script (http://localhost:8081/test_data.js):

Test_handler (' {' Data ': ' Something '} ');

To dynamically implement JSONP requests, you can use JavaScript to dynamically insert <script> tags:

<script type= "Text/javascript" >     //    var script = document.createelement (' Script ');     Script.setattribute (' src ', url);      //     document.getelementsbytagname (' head ') [0].appendchild (script);   </script>

The JSONP protocol encapsulates the above steps, and the unity in jquery is now in Ajax (where the data type is JSONP):
Http://localhost:8080/test?callback=test_handler

In order to support the JSONP protocol, the server side must provide special support [2], and the JSONP only support get requests.

2.2Proxy

The use of proxies is more straightforward across domains because the SOP restrictions are implemented by the browser. If the request is not initiated from the browser, there is no cross-domain issue.

Cross-Domain steps using this method are as follows:

1. Replace requests for access to other domains with this domain

2. The request for this domain is the server-side dynamic script responsible for forwarding the actual request
The Reverseproxy functions of various servers can be very convenient to implement the forwarding of requests, such as APACHEHTTPD + Mod_proxy.

Eg.

In order to access HTTP://LOCALHOST:8081/API from http://localhost:8080 through Ajax, you can send the request to HTTP://LOCALHOST:8080/API.

Then use the Apache Web server reverseproxy function to do the following configuration:

Proxypass/api Http://localhost:8081/api

2.3CORS

2.3.1Cross Origin resource sharing

"Cross-origin resource Sharing (CORS) is a mechanism this allows a Web page tomake xmlhttprequests to another domain. Such "Cross-domain" requestswould otherwise is forbidden by Web browsers, per the same Origin securitypolicy. CORS defines a-which the browser and the server can interact todetermine whether or not-to-allow the Cross-origin R Equest. It's more Powerfulthan only allowing Same-origin requests, but it's more secure than simplyallowing all such cross-origi N requests. "----WIKIPEDIA[3]

By adding an extension field to the Httpheader, the server adds fields to the header of the page that represents the domain and httpmethod that are allowed to access, and the client checks whether its domain is in the Allow list and decides whether to process the response.

The implementation is based on JavaScript not being able to manipulate Httpheader. Some browser plugins actually have this capability.

The server side is added in the HTTP Response Header (Page level control mode):

Access-control-allow-origin:example.com
Access-control-request-method:get, POST
Access-control-allow-headers:content-type, Authorization, Accept,range, Origin
Access-control-expose-headers:content-range
access-control-max-age:3600

Multiple domain names are separated by commas that provide cross-domain access to the domain name shown. "*" means that cross-domain access is allowed for all domain names.

clients can have two kinds of behaviors:

1. Send the options request to request Access-control information. If your domain name is in the Allowed access list, the real request is sent, otherwise the request is discarded.

2. Send the request directly, and then check the response Access-control information, if your own domain name is in the Allowed access list, then read responsebody, otherwise discard.

Essentially the response content on the server has arrived locally, and JavaScript decides whether to read it or not.

Support: [Javascript WEB applications]

* IE >= 8 (need to install caveat)

* Firefox >= 3

* Safari fully supports

* Chrome is fully supported

* Opera does not support

2.3.2 Test

Test page http://localhost:8080/test3.html uses jquery to send AJAX requests.

<HTML>     <Head><title>Testing Cross SOP</title></Head>     <Body>testing. <Scriptsrc= "Jquery-2.0.0.min.js"></Script>       <Scripttype= ' Text/javascript '>$.ajax ({URL:'Http://localhost:8000/hello', Success:function(data) {alert (data); }, Error:function() {alert ('Error');       }         }); </Script>     </Body> </HTML>

The test restful API (Http://localhost:8000/hello/{name}) uses bottle.py to host.

From bottle import route, run, response

@route ('/hello ')

def index ():

Return ' Hello world '.

Run (host= ' localhost ', port=8000)

Test 1:

Tests the behavior of a normal cross-domain request.

Test results:

1. Cross-domain GET request has been issued, request header with
Origin http://localhost:8080
2. The server side correctly gives response
3. JavaScript refuses to read data, finds reponse empty in Firebug, and triggers an error callback

Test 2:

Tests the cross-domain request behavior of a server that supports Cors.
Make the following changes to the RESTful API by adding a header to the response:

     def index ():                #Add CORS header#                response.set_header ("Access-control-allow-origin", "http://localhost:8080")                return ' Hello world '.

Test results:

1. Cross-domain GET request has been issued, request header with
Origin http://localhost:8080
2. The server side correctly gives response
3. The client obtains the data normally

Test 3:

Test Options request for cors information.
Add header to the client's AJAX request:

$.ajax ({      ' Http://localhost:8000/hello ',      headers: {' content-type ': ' text/html '},       function (data) {        alert (data);      },      function() {        alert (' error ');      }    } );

Make the following changes to the RESTful API:

@route ('/hello ', method = [' OPTIONS ', ' GET '])

def index ():

if Request.method = = ' OPTIONS ':

Return '

Return ' Hello world '.

Test results:

1. The AJAX function will first send the options request
2. For the Options request server
3. A GET request is not sent when the client discovers that there is no corsheader

Test 4:

Increase server-side handling of the options approach.
Make the following changes to the RESTful API:

@route ('/hello ', method = [' OPTIONS ', ' GET '])

def index ():

response.headers[' access-control-allow-origin ']= ' http://localhost:8080 '

response.headers[' access-control-allow-methods ']= ' GET, OPTIONS '

response.headers[' access-control-allow-headers ']= ' Origin, Accept, Content-type '

if Request.method = = ' OPTIONS ':

Return '

Return ' Hello world '.

Test results:

1. The AJAX function will first send the options request
2. For the Options request server
3. The client correctly sends a GET request and obtains the result after matching the allowheaders and orgin in the cors header

The test found that Access-control-allow-headers is a must.

The Cors protocol improves the cross-domain capabilities of Ajax, but it also increases the risk. Once the website is injected into a script or XSS attack, it is very convenient to get the user information and pass it quietly.

4.Cookie homology strategy

The same origin in the cookie only concerns the domain name, ignoring the protocol and port. So the https://localhost:8080/and http://localhost:8081/cookies are shared.

5.flash/silverlight cross-domain

There are also cross-domain requirements for various plugins in the browser. Typically, you set up cross-domain access to which domain names are allowed by this service by configuring CROSSDOMAIN.XML[4 on the server.
The client first requests this file, and if it finds its own domain name in the access list, it initiates a real request, otherwise it does not send the request

<?XML version= "1.0"?>     <!DOCTYPE cross-domain-policy SYSTEM "Http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">     <Cross-domain-policy>     <Allow-access-fromDomain="*"/>     <Allow-http-request-headers-fromDomain="*"Headers="*"/>   </Cross-domain-policy>

Typically crossdomain.xml are placed in the Web site root directory.

6. Summary

The development of the Internet has spawned the need for cross-domain access, and various cross-domain approaches and protocols have met demand but also increased risk. In particular, the prevalence of attacks such as XSS and CSRF has benefited from this.

Understanding these technical backgrounds helps you to be proficient in practical projects and to avoid various security risks

JS homology policy and cross-domain access

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.