子资源完整性对内联 JavaScript 有用吗?

Is Subresource Integrity any useful for inline JavaScript?

我正在阅读有关 Subresource Integrity 的内容并了解它用于验证外部文件。我想我在 MDN or W3C.

中找不到任何对内联 JavaScript 的引用也就不足为奇了

那么,可以肯定地说 SRI 相关属性 integritycrossorigin 对内联 JavaScript 完全没用吗?

是的,可以这么说,因为当 <script> 没有 "src" 属性时,<script> 标签的 integrity 属性将被忽略。 SRI 只有在通过单独的 HTTP 请求获取资源时才会出现。

So, is it safe to say that the SRI-related attributes integrity and crossorigin are completely useless for inline JavaScript?

是的,因为这些属性仅对具有 src 属性的 script 元素有用:

https://html.spec.whatwg.org/multipage/scripting.html#attr-script-integrity

The integrity attribute represents the integrity metadata for requests which this element is responsible for. The value is text. The integrity attribute must not be specified when embedding a module script or when the src attribute is not specified. [SRI]

同样如问题中所述,MDN 中的描述也清楚地表明了这一点:

https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity

Subresource Integrity (SRI) is a security feature that enables browsers to verify that files they fetch (for example, from a CDN) are delivered without unexpected manipulation. It works by allowing you to provide a cryptographic hash that a fetched file must match.

如果您正在寻找保护内联脚本文件的方法,您可以在 CSP headers 中使用 nonce 属性并在脚本标签中指定

nonce-base64-value
A whitelist for specific inline scripts using a cryptographic nonce (number used once). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide an unguessable nonce, as bypassing a resource’s policy is otherwise trivial. See unsafe inline script for an example. Specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support.

我知道线程有点老了,但是W3C现在支持完整性哈希检查。在以下情况下执行脚本:

  • 已设置 src,完整性属性正确且匹配 CSP 策略
  • 未设置 src,完整性属性正确或与 CSP 策略匹配

Pull request

WebAppSec Subresource Integrity


编辑: 似乎实际上只有 Chrome 支持此功能