Solutions for homology policy and Cross-domain access

Source: Internet
Author: User
Tags to domain
Cross-domain is a frequently encountered problem, especially when there are two domain names, such as your page in a.test.com, and then need to request data to b.test.com, this time across the domain. If you ask directly, you will find that the browser is an error, and at this point, you need to know what the homology policy is.

1, what is the homologous strategy.


Understanding a Cross-domain must first understand the homology policy. The homology policy is a very important security policy that is implemented on the browser for security reasons.
What is homology.
The URL consists of a protocol, domain name, port, and path, and if the protocol, domain name, and port of the two URLs are the same, they are homologous.
Homology policy: Browser's homology policy, which restricts "document" or script from different sources, and reads or sets some attributes on the current "document". (White Hat Speaking web security [1]): Scripts loaded from one domain do not allow access to document properties for another domain.
As an example:
For example, a malicious Web page through 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 in the user login to the bank when the user gets the username and password.

Tags such as,<script>, , <iframe>, <link>, and so on in the browser can load Cross-domain resources without homology restrictions, but browsers restrict JavaScript permissions so that they are unreadable, Write the loaded content.
In addition, the homologous policy only restricts the HTML document of the Web page, and still believes that other static resources such as JavaScript, CSS, pictures and so on are also homologous.

Code samples (http://localhost:8080/and http://localhost:8081 are not homologous because of different ports):

Http://localhost:8080/test.html

<body>

<iframe id= "test" src= "http://localhost:8081/test2.html" ></iframe>

<script type= "Text/javascript" >

document.getElementById ("Test"). ContentDocument.body.innerHTML = "Write somthing";

</script>

</body>

Http://localhost:8081/test2.html

<body>

Testing.

</body>

In Firefox, you get the following error:
Error:permission denied to access property ' body '

The Document object's Domain property holds the host name of the server on which it is mounted, and 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 are accessible to each other.
For security reasons, it cannot be set to other main domain, such as http://www.csdn.net/cannot be set to Sina.com.


2. Ajax Cross-Domain


Ajax (XMLHttpRequest) requests are limited by the homology policy.

Ajax can interact with remote servers via XMLHttpRequest, and XMLHttpRequest is a pure JavaScript object, which is done in the background and is not easily perceived by users.
As a result, XMLHTTP has actually breached the existing JavaScript security restrictions.

As an example:
Suppose a Web site refers to JavaScript at another site, which is compromise and added to JavaScript to get user input and submit it to other sites via Ajax, so that information can be collected continuously.
Or a Web site that has a vulnerability that could cause XSS to inject JavaScript script, the script can get the user information through Ajax and submit it to other sites via Ajax, so that information can be collected continuously.


If we want to take advantage of the XMLHTTP asynchronous interactive ability, and do not want to blatantly break through the JavaScript security policy, the option is to XMLHTTP plus strict homology restrictions.

Such a security policy is similar to the applet's security policy. The constraints of an IFRAME are simply the inability to access data in Cross-domain Htmldom, while XMLHTTP essentially limits the submission of Cross-domain requests. (It's actually mentioned that Cors has relaxed the limit)

With the development of AJAX Technology and network services, the requirements for Cross-domain are becoming more and more strong. The following is an introduction to the Cross-domain technology of Ajax.

01 2.1, JSONP

JSONP technology is actually not related to Ajax. We know that <script> tags can load cross-domain javascript scripts, and that the loaded script and the current document belong to the same domain.


Therefore, the data and functions in the script can be invoked/accessed in the document. If the data in the JavaScript script is dynamically generated, you can interact with the server-side data as long as the <script> tags are dynamically created in the document.


JSONP is the use of <script> tags across the domain to achieve Cross-domain data access, request dynamically generated JavaScript script with a callback function name as parameters.


Where the JavaScript function of the callback function local document, the server-side dynamically generated script generates data and calls the callback function in code with the resulting data as parameters.


When this script is loaded into the local document, the callback function is invoked.

Test page for 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" >

This shows dynamic script insertion

var script = document.createelement (' script ');

Script.setattribute (' src ', url);

Load the script

document.getElementsByTagName (' head ') [0].appendchild (script);

</script>


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

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

02
2.2. Proxy

The use of proxies is more straightforward across domains because the limitations of the SOP are implemented by browsers. If the request is not initiated from the browser, there is no cross-domain problem.
Use this method to cross domain steps as follows:
1. Replace requests for access to other domains as requests in this domain
2. The request in this domain is the dynamic script on the server side that is responsible for forwarding the actual request
A variety of server reverse proxy functions can be very convenient to implement the request forwarding, such as Apache httpd + mod_proxy.
Eg.

In order to access Http://localhost:8081/api from http://localhost:8080 via Ajax, the request can be sent to Http://localhost:8080/api.
The reverse proxy function of the Apache Web server is then used to configure the following:
Proxypass/api Http://localhost:8081/api



03

2.3, CORS 2.3.1 Cross Origin resource sharing

Cross-origin resource Sharing (CORS) is a mechanism this allows a Web page to make xmlhttprequests to another domain. Such "Cross-domain" requests would otherwise is forbidden by Web browsers, per the same origin security policy. CORS defines a way in which of the browser and the server can interact to determine whether or not to allow the Cross-origin Request. It is more powerful than only allowing Same-origin requests, but it are more secure than simply allowing all such cross-ori Gin requests. "----Wikipedia[3]
by adding an extended field to the HTTP header, the server adds a field to the header of the page that allows access to domain and HTTP method, and the client checks whether its own domain is in the Allow list To decide whether to process the response. The
implementation is based on JavaScript not being able to manipulate HTTP headers. Some browser plug-ins are actually capable of this.

Server-side joins in the response headers of HTTP (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 to provide cross-domain access to the indicated domain name. "*" indicates that cross-domain access is allowed for all domain names.

There are two types of behavior that a client can do:
1. Send the options request, request Access-control information. If your domain name is in the Allowed access list, send a real request or discard the request.
2. Send the request directly, then check the response Access-control information, if your domain name in the Allowed access list, then read response body, otherwise give up.
Essentially, the service-side response content has arrived locally, and JavaScript decides whether to read it.

Support: [Javascript Web applications]
* IE >= 8 (need to install caveat)
* Firefox >= 3
* Safari fully supports
* Chrome full support
* Opera does not support

2.3.2 Test

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

<body>

Testing.

<script src= "Jquery-2.0.0.min.js" ></script>

<script type= ' Text/javascript ' >

$.ajax ({

URL: ' Http://localhost:8000/hello ',

Success:function (data) {

alert (data);

},

Error:function () {

Alert (' Error ');

}

});

</script>

</body>


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 to ' Hello world. '
Run (host= ' localhost ', port=8000)


Test 1:

Test the behavior of normal cross-domain requests.

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


Test 2:
Test Cross-domain request behavior for servers that support Cors.
Make the following changes to the RESTful API and add headers to the response:
def index ():
#Add CORS header#
Response.set_header ("Access-control-allow-origin", "http://localhost:8080")
Return to ' 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 the response
3. Client access to normal data

Test 3:
Test the options request to obtain cors information.

Increase header for Ajax requests to the client:

$.ajax ({

URL: ' Http://localhost:8000/hello ',

Headers: {' content-type ': ' text/html '},

Success:function (data) {

alert (data);

},

Error:function () {

Alert (' Error ');

}

});


Make the following changes to the RESTful API:

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

def index ():

if Request.method = = ' OPTIONS ':

Return ""

Return to ' Hello world. '


Test results:
1. Ajax functions will first send the options request
2. Request Server for options
3. The client does not send a GET request when it discovers that there is no cors header

Test 4:
Increase server-side processing of the options method.
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 to ' Hello world. '


Test results:
1, the AJAX function will first send the options request
2. Request Server for options
3. When the client matches the Allow headers and orgin in the cors header, the GET request is sent correctly and the result is obtained
The test found that access-control-allow-headers was necessary.

The Cors protocol improves the cross-domain capabilities of Ajax, but also increases the risk. Once the site is injected with scripting or XSS attacks, it is very convenient to get user information and pass it on quietly.


4, Cookie homology strategy


The same homology in the cookie is concerned only with domain names, ignoring protocols and ports. So https://localhost:8080/and http://localhost:8081/cookies are shared.


5. Flash/silverlight Cross-domain


The browser's various plug-ins also have cross-domain requirements. Typically, you set up cross-domain access to which domain names this service allows by configuring crossdomain.xml[4 on the server.
The client will first request this file, and if it finds its domain name in the access list, it initiates a real request, otherwise the request is not sent.


<?xml version= "1.0"?>
<! DOCTYPE cross-domain-policy SYSTEM "HTTP://WWW.MACROMEDIA.COM/XML/DTDS/CROSS-DOMAIN-POLICY.DTD" >
<cross-domain-policy>
<allow-access-from domain= "*"/>
<allow-http-request-headers-from domain= "*" headers= "*"/>
</cross-domain-policy>


Usually crossdomain.xml are placed in the site root directory. 6, summary


The development of the Internet has spawned the need for Cross-domain access, and various cross-domain methods and protocols have met the requirements but also increased the risks. In particular, the prevalence of such attacks as XSS and CSRF also benefited.
Understanding these technical backgrounds will help you to be proficient in practical projects and avoid various security risks.



Advertising content

Focus on US

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.