Blog
Blog copied to clipboard
浅析浏览器同源策略
浅析浏览器同源策略
什么是同源策略(SOP)?
同源:如果两个页面拥有相同的协议,端口和主机,那么这两个页面就属于同一个源。 同源策略:浏览器的一套安全机制(沙箱机制),这些安全机制都以同源为限制条件。
为什么需要同源策略?
同源策略的出发点很简单:浏览器存储着用户数据,比如认证令牌、cookie及其他私有元数据,这些数据不能泄露给其他应用。
读、写、执行模型
SOP中,源A有以下权限限制:
- 从源B读取资源:拒绝
- 向源B写:限制
- 从源B中执行资源:允许
拒绝读:
- May execute a script from “B”
- Must not be permitted to get the raw sourcecode of that script
- May apply (execute) a CSS stylesheet from “B”
- Must not be permitted to get the raw-text of that stylesheet
- May include (execute) a frame pointed at a HTML page from “B”
- Must not be permitted to get the inner HTML of that frame
- May draw (execute) an image from “B”
- Must not be permitted to examine the bits of that image
- May play (execute) a video from “B”
- Must not be permitted to reconstruct the video by capturing images of it ...and so on
写操作包括以下情形:
- Navigating to a URL (especially with a query string parameter)
- Uploading a file or performing a HTTP POST using a web form, XMLHTTPRequest, or XDomainRequest
- Manipulating a property of a frame
- Writing content to a frame’s document or manipulating a DOM object in that document
- Sending a message to another frame using postMessage
由于XSS,CSRF等,浏览器开发人员和标准制定者禁止了一些跨域写操作,或者需要附加一些限制
同源策略对哪些有影响?
- 不允许跨域脚本API访问(iframe.contentWindow,window.parent,window.opener 等)
- 不允许XHR跨域网络”访问“
- 不允许跨域访问存储数据(cooike,localStorage,sessionStorage,IndexedDB)
- 通常不允许跨域网络读操作
- 通常允许跨域网络写(链接,重定向,表单提交)
- 通常允许跨域网络资源嵌入(script,link,img ,video,@font-face 等)
5. 如何绕过同源策略?
- 跨域脚本API访问:window.postMessage,window.name
- XHR跨域网络”访问“:CORS
- 图像Ping,JSONP
- 代理和反向代理
参考链接:
http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy
http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/
http://security.stackexchange.com/questions/8264/why-is-the-same-origin-policy-so-important
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Same_origin_policy_for_JavaScript
http://blogs.msdn.com/b/ieinternals/archive/2009/08/28/explaining-same-origin-policy-part-1-deny-read.aspx
http://usamadar.com/2012/06/24/getting-around-browsers-same-origin-policy-sop-with-proxies-script-injection-jsonp-and-cors/