Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to avoid homologous Policy in javascript

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "how to avoid the homologous strategy in javascript". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

In javascript, the same origin policy is an important security metric for client script (especially Javascript), that is, two pages with the same protocol (protocol), port, and host (domain name) belong to the same source.

The operating environment of this tutorial: windows7 system, javascript1.8.5 version, Dell G3 computer.

What is a homologous strategy?

The same origin policy is an important security metric for client script, especially Javascript. It originated from Netscape Navigator2.0 and was designed to prevent a document or script from being loaded from multiple different sources.

The same origin policy, that is, has the same protocol (protocol), port (if specified), and two pages of the host (domain name) belong to the same source.

For example, the URL http://www.example.com/dir/page.html

The protocol is http://.

The domain name is www.example.com

Port is 80 (the default port can be omitted). Its homology is as follows.

Http://www.example.com/dir2/other.html: homologous http://example.com/dir/other.html: different sources (different domain names) http://v2.www.example.com/dir/other.html: different sources (different domain names) http://www.example.com:81/dir/other.html: different sources (different ports)

Essence:

Its essence is simple: it considers trusted content loaded from any site to be insecure. When sceptical scripts run in the sandbox by browsers, they should only be allowed to access resources from the same site, not those from other sites that may be malicious.

Why should there be homologous restrictions?

Let's give an example: for example, a hacker program uses IFrame to embed the real bank login page into his page. When you log in with a real user name and password, his page can read the contents of input in your form through Javascript, so that the user name and password can be easily obtained.

The purpose of the same origin policy is to ensure the security of user information and prevent malicious websites from stealing data.

Imagine such a situation: website An is a bank, and users log in and then visit other sites. What happens if other sites can read the Cookie of site A?

Obviously, if Cookie contains privacy (such as total deposits), this information will be leaked. More frightening is that Cookie is often used to save the login status of users, if the user does not log out, other sites can pretend to be users and do whatever they want. Because the browser also stipulates that the submission of the form is not subject to the same origin policy.

Thus it can be seen that a "homologous policy" is necessary, otherwise the Cookie can be shared and the Internet will have no security to speak of.

Limit the scope

With the development of the Internet, the "homologous policy" is becoming more and more strict. At present, there are three behaviors that are restricted if they are not of the same origin.

(1) Cookie, LocalStorage and IndexDB cannot be read. (2) DOM cannot be obtained. (3) Ajax request cannot be sent.

Although these restrictions are necessary, they are sometimes inconvenient and reasonable use is also affected. Next, I will explain in detail how to circumvent the above three restrictions.

Evading method

1 、 Cookie

Cookie is a small piece of information written by the server to the browser, and only homologous web pages can be shared. However, the first-level domain name of the two web pages is the same, but the second-level domain name is different, and the browser allows you to share Cookie by setting document.domain.

For example, page An is http://w1.example.com/a.html and page B is http://w2.example.com/b.html, so as long as the same document.domain is set, the two pages can share Cookie.

Document.domain = 'example.com'

Now, the A page sets up a Cookie through a script

[xss_clean] = "test1=hello"

You can read this Cookie on the B web page.

Var allCookie = [xss_clean]

This method is only suitable for Cookie and iframe windows. LocalStorage and IndexDB cannot use this method.

Avoid the same origin policy and use the PostMessage API described below.

In addition, when setting up Cookie, the server can specify that the domain name of Cookie is a first-level domain name, such as .example.com.

Set-Cookie: key=value; domain=.example.com; path=/

In this way, the second-level domain name and the third-level domain name can read the Cookie without any settings.

2 、 iframe

If two web pages come from different sources, you won't be able to get each other's DOM. Typical examples are iframe windows and windows opened by the window.open method, which cannot communicate with the parent window.

For example, if the parent window runs the following command, if the iframe window is not of the same origin, it will report an error

Document.getElementById ("myIFrame"). ContentWindow.document / / Uncaught DOMException: Blocked a frame from accessing a cross-origin frame.

In the above command, the parent window wants to get the DOM of the child window, because cross-source causes an error.

Vice versa, the child window getting the DOM of the main window will also report an error.

Window.parent.document.body / / error report

If the first-level domain name of the two windows is the same, but the second-level domain name is different, you can set the document.domain attribute described in the previous section to circumvent the same origin policy and get the DOM.

For websites of completely different sources, there are three ways to solve the communication problem of cross-domain windows.

Fragment Identifier (fragment identifier)

Window.name

Cross-document communication API (Cross-document messaging)

2.1 fragment identifier

The fragment identifier (fragment identifier) refers to the part after the # sign of URL, such as # fragment of http://example.com/x.html#fragment. If you just change the fragment identifier, the page will not be refreshed.

The parent window can write information into the fragment identifier of the child window.

Var src = originURL +'#'+ data;document.getElementById ('myIFrame'). Src = src

The child window is notified by listening for hashchange events.

_ window.onhashchange = checkMessage; function checkMessage () {var message = _ window.location.hash; / /.}

Similarly, child windows can also change the fragment identifier of the parent window.

Parent.location.href= target + "#" + hash

2.2 window.name

The browser window has a window.name property. The most important feature of this property is that, regardless of whether it is of the same origin or not, as long as the previous page sets this property in the same window, the latter page can read it.

The parent window first opens a child window and loads a web page from a different source that writes information to the window.name property.

Window.name = data

Next, the child window jumps back to a URL in the same domain as the main window.

Location = 'http://parent.url.com/xxx.html';

The main window can then read the window.name of the child window.

Var data = document.getElementById ('myFrame'). ContentWindow.name

The advantage of this method is that the window.name has a large capacity and can place very long strings; the disadvantage is that you must listen for changes in the window.name properties of the child window, which affects the performance of the web page.

2.3 window.postMessage

Both of the above methods belong to cracking. In order to solve this problem, HTML5 introduced a new API: cross-document Communication API (Cross-document messaging).

This API adds a window.postMessage method to the window object that allows communication across windows, regardless of whether the two windows are of the same origin or not.

For example, the parent window http://aaa.com sends a message to the child window http://bbb.com and calls the postMessage method.

Var popup = window.open ('http://bbb.com',' title'); popup.postMessage ('Hello Worldwaters,' http://bbb.com');

The first parameter of the postMessage method is the specific information content, and the second parameter is the source of the window that receives the message (origin), that is, "protocol + domain name + port". It can also be set to *, which means that the domain name is not restricted and is sent to all windows.

The child window sends a message to the parent window in a similar way.

Window.opener.postMessage ('Nice to see you',' http://aaa.com');

Both parent and child windows can listen to each other's messages through the message event.

Window.addEventListener ('message', function (e) {console.log (e.data);}, false)

The event object event for the message event provides the following three properties.

Event.source: the window to send the message event.origin: the URL to which the message is sent event.data: message content

In the following example, a child window references the parent window through the event.source property, and then sends a message.

Window.addEventListener ('message', receiveMessage); function receiveMessage (event) {event.source.postMessage (' Nice to see YouTube,'*');}

The event.origin property can filter messages that are not sent to this window.

Window.addEventListener ('message', receiveMessage); function receiveMessage (event) {if (event.origin! = =' http://aaa.com') return; if (event.data = 'Hello World') {event.source.postMessage (' Hello', event.origin);} else {console.log (event.data);}}

2.4 LocalStorage

Through window.postMessage, it is also possible to read and write the LocalStorage of other windows.

Here is an example where the main window writes the localStorage of the iframe child window.

_ window.onmessage = function (e) {if (e.origin! = = 'http://bbb.com') {return;} var payload = JSON.parse (e.data); localStorage.setItem (payload.key, JSON.stringify (payload.data));}

In the above code, the child window writes the message from the parent window to its own LocalStorage.

The code for the parent window to send the message is as follows.

Var win = document.getElementsByTagName ('iframe') [0] .contentWindow; var obj = {name:' Jack'}; win.postMessage (JSON.stringify ({key: 'storage', data: obj}),' http://bbb.com');

The code for the enhanced child window to receive messages is as follows.

_ window.onmessage = function (e) {if (e.origin! = = 'http://bbb.com') return; var payload = JSON.parse (e.data); switch (payload.method) {case' set': localStorage.setItem (payload.key, JSON.stringify (payload.data)); break; case 'get': var parent = window.parent; var data = localStorage.getItem (payload.key); parent.postMessage (data,' http://aaa.com');) Break; case 'remove': localStorage.removeItem (payload.key); break;}}

The enhanced parent window sends the message code as follows.

Var win = document.getElementsByTagName ('iframe') [0] .contentWindow; var obj = {name:' Jack'}; / / store object win.postMessage (JSON.stringify ({key: 'storage', method:' set', data: obj}), 'http://bbb.com'); / / read object win.postMessage (JSON.stringify ({key:' storage', method: "get"}), "*") _ window.onmessage = function (e) {if (e.origin! = 'http://aaa.com') return; / / "Jack" console.log (JSON.parse (e.data) .name);}

3 、 Ajax

According to the homology policy, AJAX requests can only be sent to homologous URLs, otherwise an error will be reported.

In addition to setting up a server proxy (the browser requests the same origin server, which requests external services), there are three ways to circumvent this limitation.

JSONP WebSocket CORS

3.1 JSONP

JSONP is a common method of cross-source communication between server and client. The biggest feature is simple and applicable, all the old browsers support it, and the server modification is very small.

Its basic idea is that the web page requests JSON data from the server by adding an element, which is not restricted by the same origin policy; when the server receives the request, it sends the data back in a callback function with a specified name.

First, the web page dynamically inserts elements that make requests to cross-source URLs.

Function addScriptTag (src) {var script = document.createElement ('script'); script.setAttribute ("type", "text/javascript"); script.src = src; document.body.appendChild (script);} _ window.onload = function () {addScriptTag (' http://example.com/ip?callback=foo');} function foo (data) {console.log ('Your public IP address is:' + data.ip) }

The above code makes a request to the server example.com by dynamically adding elements. Note that the query string for this request has a callback parameter that specifies the name of the callback function, which is required for JSONP.

After the server receives this request, it returns the data in the parameter location of the callback function.

Foo ({"ip": "8.8.8.8"})

Because of the script requested by the element, it runs directly as code. At this point, the foo function is called immediately as soon as the browser defines it. JSON data as a parameter is treated as a JavaScript object rather than a string, thus avoiding the step of using JSON.parse.

3.2 WebSocket

WebSocket is a communication protocol that uses ws:// (unencrypted) and wss:// (encrypted) as protocol prefixes. The protocol does not implement the same origin policy, and cross-source communication can be carried out through it as long as the server supports it.

Here is an example of the header information of a WebSocket request sent by a browser (extracted from Wikipedia).

GET / chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDwang = Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 Origin: http://example.com

In the above code, one field is Origin, which indicates the request source (origin) of the request, that is, the domain name from which it originated.

It is because of the Origin field that WebSocket does not implement the same origin policy. Because the server can use this field to determine whether or not to authorize this communication. If the domain name is on the whitelist, the server will respond as follows.

HTTP/1.1 101 Switching ProtocolsUpgrade: websocketConnection: UpgradeSec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=Sec-WebSocket-Protocol: chat

3.3 CORS

CORS is an abbreviation for cross-source resource sharing (Cross-Origin Resource Sharing). It is the W3C standard and is the fundamental solution to cross-source AJAX requests. Compared to JSONP, which can only send GET requests, CORS allows any type of request.

This is the end of the content of "how to avoid the homologous Strategy in javascript". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report