Same Origin Policy / 同源策略介绍
在同源策略下,只有当A、B网页的origin相同的情况下,浏览器才会允许A网页的scripts去访问B网页的数据。
这个策略防止了某些恶意script通过DOM (Document Object Model) 访问另一个网页的敏感信息
Origin的定义
Origin被定义为 URI scheme + host name + port number的组合
SOP的作用范围
SOP只会应用到script上。这意味着image, css, 和动态加载scripts可以通过对应的HTML tags被跨域访问。
fonts是一个值得注意的例外。
MDN Web Docs. Retrieved 2018-07-24. Web fonts are subject to the same domain restriction (font files must be on the same domain as the page using them), unless HTTP access controls are used to relax this restriction.
https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face
跨站请求伪造 (Cross-site request forgery, CSRF, XSRF) 就是利用同源策略不适用于HTML标签的缺陷。
Sample
e.g. http://www.example.com/dir/page.html
Compared URL | Outcome | Reason |
---|---|---|
http://www.example.com/dir/page2.html | Success | Same scheme, host and port |
http://www.example.com/dir2/other.html | Success | Same scheme, host and port |
http://username:password@www.example.com/dir2/other.html | Success | Same scheme, host and port |
http://www.example.com:81/dir/other.html | Failure | Same scheme and host but different port |
https://www.example.com/dir/other.html | Failure | Different scheme |
http://en.example.com/dir/other.html | Failure | Different host |
http://example.com/dir/other.html | Failure | Different host (exact match required) |
http://v2.www.example.com/dir/other.html | Failure | Different host (exact match required) |
http://www.example.com:80/dir/other.html | Depends | Port explicit. Depends on implementation in browser. |
同源策略存在的意义
这个机制对现代广泛依赖http cookies去维护用户session的web applications具有一个特殊意义。因为server基于http cookie的信息去暴露敏感信息或做状态改变的动作。client必要要维护在不相关站点提供的信息之间的严格隔离,从而可以防止数据机密性或完整性的缺失。
假设没有同源限制,A网站的API可以被任何来源的AJAX请求访问,包括获取用户的隐私信息,只看用户有没有登录,现在有个坏人做了一个网站B,坏人在B网页中用AJAX访问A网站的API,如果一个用户访问B之前已经登录了A,那这个请求包含A网站的cookie信息,也就会被A网站认为用户已经登录,这样用户在A网站的隐私信息就泄露给了控制B网站的坏人。
不过,如果A网站觉得一些信息跨站访问也无所谓,那就可以通过jsonp或者CORS规则暴露,关键是A网站主动允许不同源的请求。
Relaxing the same-origin policy
- 数据污染 / Data tainting
- document.domain property
- Cross-Origin Resource Sharing
- Cross-document messaging
- JSONP
- WebSockets