我应该禁用图像 Content-Security-Policy header 吗?

Should I disable Content-Security-Policy header for images?

因为Content-Security-Policy header主要是用来防止XSS attacks的,我觉得对.png,.jpg,.ico,.webp禁用也无所谓文件。因为它们一般不包含 HTML.

但我注意到的是:

当我不对图像文件禁用 CSP header 时,它不允许浏览器在直接访问图像文件时为图像文件提供 HTML 布局,例如,我的意思是:当您访问 example.com/image.jpg,在 chrome 中,图像后面有黑色背景,并且位于屏幕中央。但是,当我打开 CSP 时,例如 chrome 为用户访问图像提供的每种样式都是无效的,因为 CSP 阻止了它。

现在,我的问题是:

我应该为图像文件禁用 CSP header 吗?我没有看到任何 明确 为图像文件禁用它的缺点,但我只是想在这样做之前确定一下。

CSP 很好。来自 MDN:

https://developers.google.com/web/fundamentals/security/

Instead of blindly trusting everything that a server delivers, CSP defines the Content-Security-Policy HTTP header, which allows you to create an allowlist of sources of trusted content, and instructs the browser to only execute or render resources from those sources.

如果您完全使用 CSP,那么您应该全面使用它们。是的,图像文件可能“不易受攻击”。但它们仍然可以成为“攻击媒介”。例如:https://hackerone.com/reports/964550

与其“禁用 CSP”,不如使用 img-src:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/img-src

The HTTP Content-Security-Policy img-src directive specifies valid sources of images and favicons.

Should I disable CSP header for image files? I do not see any clear disadvantages of disabling it for image files, but I just want to make sure before I do so.

是的,您应该为图像文件禁用 CSP header,它在与 png/jpg/ico 等...文件一起交付时不起作用。
您唯一可以传送带有 frame-ancestors 指令的图像和视频,这可以防止这些文件成为 embedded info <iframe> <object> 标签,但不会进入 <img> / <video> 标签。

CSP 应仅针对 HTML/XSLT 文件发布,对于其他 MIME-types 它不起作用。
注意:要为工作人员指定内容安全策略,您需要 publish CSP header with worker JS-file.

This XSS via images example abt.

不要白白担心

  1. 这个 XSS 不是通过图像文件,实际上图像中的评论被视为 HTML 因为 accounts.shopify.com 服务器在上传文件时没有检查 MIME-types。因此,图像被加载并标记为 text/html,因此服务器将其作为 HTML.
  2. 发送到浏览器
  3. 此类图片无法在<img>标签内使用,只需插入“中毒”图片即可查看。
  4. img-src 指令不能防止此类事情发生。无论如何,此类图像将属于 'self' 令牌限额。不要在 script-src 中使用 'unsafe-inline' 就这样。