JavaScript 和第三方 cookie
假设有一个网站 foo.com
,它从网站 bar.com
加载 JavaScript。现在,假设来自 bar.com
站点的 JavaScript 尝试使用 document.cookies
读取 cookie。我的印象是,使用 JavaScript,您可以读取浏览器中设置的所有 cookie,无论其来源如何。但事实证明,来自 bar.com
网站的 JavaScript 只能访问 bar.com
设置的 cookie,而不能访问任何其他网站。如果是这样的话,窃取cookie的脚本注入攻击是如何进行的呢?
Say there is a site foo.com
which loads JavaScript from site bar.com
. Now, say the JavaScript from site bar.com
tries to read cookies using document.cookies
. I was under the impression that using JavaScript, you can read all the cookies set in the browser irrespective of their source. But it turns out that the JavaScript from the site bar.com
can only access cookies set by bar.com
and not any other. If this is the case, how are script injection attacks which steal cookies carried out?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那不是真的。重要的是包含
元素的 HTML 文档在哪里,而不是 src 属性中提到的
的 JS 文件的 URL。
我怀疑您的问题是,当属性名为
document.cookie
(单数!)时,您正在访问document.cookies
That isn't true. What matters is where the HTML document containing the
<script>
element is, not the URL of the JS file that said<script>
mentions in the src attribute.I suspect your problem is that you are accessing
document.cookies
when the property is calleddocument.cookie
(Singular!)他们在受攻击的页面内加载脚本。
例如,当博客系统中的评论受到损害时,它们会包含一个在呈现页面时执行的
script
元素。该脚本可以获取cookie并将其发送到攻击者的服务器。这就是为什么您应该永远相信用户输入,并且至少不允许在评论中使用某些标签(或者将每个
<
翻译为<
)。但不要在客户端这样做,因为这种预防技术很容易被绕过;在服务器端测试(并更改)恶意输入。They load scripts inside the attacked page.
For instance, when comments in a blog system get compromised, they contain a
script
element that is executed when the page is rendered. This script can get the cookies and send it to the attacker's server.That's why you should never trust user input and disallow at least certain tags in comments (or translate every
<
to<
). But don't do this on the client side, as this prevention technique can easily be circumvented; test for (and change) malicious input on the server side.您只能访问为给定域名设置的cookie。来自 关于 cookie 的维基百科文章:
如果
foo.com
发送了一个域名为bar.com
甚至.com
的 cookie,则上的 JavaSCript 代码bar.com
可以读取该 cookie。然而,大多数浏览器被配置为仅在域名匹配时接受 cookie,并且会拒绝此类 cookie。You can only access cookies which have been set for the given domain name. From the Wikipedia article on cookies:
If
foo.com
sent a cookie which had the domain name ofbar.com
, or even.com
, then JavaSCript code onbar.com
could read that cookie. However most browsers are configured to only accept cookies when the domain name matches, and would reject such a cookie.