阻止对另一个域的请求?

阻止对另一个域的请求?

问题描述:

我想通过不允许我页面上的任何内容将 XHR/XMLHttpRequest(或其他?)请求发送到其他域而不是托管页面的域,从而在管理上阻止一整类 XSS 攻击.这可能吗?

I want to administratively prevent a whole class of XSS attacks by not allowing anything on my page to send XHR/XMLHttpRequest (or other?) requests to other domains than the domain hosting the page. Is that possible?

我认为我可以通过 跨源资源共享(CORS),但似乎我错了.如果托管在 domain-a.com 上的页面尝试向 domain-b.com 发出 XHR 请求,则可以在 domain-b.com 页面上使用 CORS 来控制是否允许这样做.

I thought I could do that with Cross-Origin Resource Sharing (CORS), but it seems I was wrong. If a page hosted on domain-a.com tries to make an XHR request to domain-b.com, CORS can be used on domain-b.com pages to control whether or not that is allowed.

因此,如果 domain-a.com 页面上的某些内容尝试向hackers-r-us.com 发出XHR 请求,只要hackers-r-us.com 设置了适当的CORS 标头,就将被允许.

So if something on the page at domain-a.com tries to make an XHR request to hackers-r-us.com that will be allowed, as long as hackers-r-us.com sets the appropriate CORS headers.

但是,无论hackers-r-us.com 上的CORS 标头如何,我是否可以在domain-a.com 的页面上设置任何内容来禁止对其他域(例如hackers-r-us.com)的请求?

But is there anything I can set on the page on domain-a.com to disallow requests to other domains such as hackers-r-us.com regardless of CORS headers on hackers-r-us.com?

内容安全政策 (CSP) — 特别是 connect-src CSP 指令.

Content Security Policy (CSP) — specifically the connect-src CSP directive.

CSP 指令使用 Content-Security-Policy HTTP 标头指定,并由浏览器强制执行.指定 connect-src 指令的标头的最简单示例是:

CSP directives are specified using the Content-Security-Policy HTTP header, and enforced by browsers. The simplest example of a header that specifies a connect-src directive would be this:

Content-Security-Policy: connect-src 'self';

如果您使用它在 https://example.com/foo/ 上提供文档,浏览器将阻止文档中的任何前端 JavaScript 向其自身以外的任何来源的 URL 发出请求('self');也就是说,浏览器只会将允许的请求限制为以 https://example.com 开头的 URL.

If you serve a document at https://example.com/foo/ with that, browsers will block any frontend JavaScript in the document from making requests to URLs at any origin other than its own ('self'); that is, browsers will restrict the allowed requests only to URLs starting with https://example.com.

  • https://developer.mozilla.org/docs/Web/HTTP/Headers/Content-Security-Policy/connect-src has more details and examples.
  • https://w3c.github.io/webappsec-csp/#directive-connect-src is the actual spec section where the browser requirements are defined; that section also has some example.