From 77f614fdd62646d36ca63e1409e9b4f07a4421a7 Mon Sep 17 00:00:00 2001 From: Hamish Willee Date: Tue, 18 Jul 2023 01:58:45 +1000 Subject: [PATCH] FF116 CSP script-src can specify hash for external files (#27876) * FF116 CSP script-src can specify hash for external files * Update files/en-us/web/http/headers/content-security-policy/script-src/index.md * Update files/en-us/web/http/headers/content-security-policy/script-src/index.md --- .../script-src/index.md | 52 ++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/files/en-us/web/http/headers/content-security-policy/script-src/index.md b/files/en-us/web/http/headers/content-security-policy/script-src/index.md index c574ca12e63ab14..57dc0cfe46ce796 100644 --- a/files/en-us/web/http/headers/content-security-policy/script-src/index.md +++ b/files/en-us/web/http/headers/content-security-policy/script-src/index.md @@ -46,7 +46,7 @@ Note that this same set of values can be used in all {{Glossary("fetch directive ## Examples -### Blocking resources from untrusted domains +### Whitelisting resources from trusted domains Given this CSP header that only allows scripts from `https://example.com`: @@ -75,6 +75,56 @@ document.getElementById("btn").addEventListener("click", doSomething); If you cannot replace inline event handlers, you can use the `'unsafe-hashes'` source expression to allow them. See [Unsafe hashes](#unsafe_hashes) for more information. +### Whitelisting external scripts using hashes + +Allowing trusted domains, as shown in the section above, is a broad-brushed approach for specifying the locations from which code can safely be loaded. +This is a pragmatic approach, in particular when your site uses many resources and you have confidence that the trusted site will not be compromised. + +An alternative method is to specify allowed scripts using file hashes. +Using this approach an external file in a ` +``` + +The `integrity` attribute can have multiple values, each providing a hash for the file calculated using a different algorithm. +In order for an external script to be loaded, CSP requires that _all_ valid hash values in the attribute must also be in the CSP `script-src` declaration. +Therefore the script below would not load, because the second hash is not present in the CSP header above. + +```html + +``` + +This rule only applies to _valid_ hash values. +Values that are not recognized as hashes by the browser are ignored, so the following script should load: + +```html + +``` + +[Subresource integrity](/en-US/docs/Web/Security/Subresource_Integrity) contains more information about calculating hashes and using the `integrity` attribute. + ### Unsafe inline script > **Note:**