Content-Security-Policy: script-src directive — Allowlisting 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.
Reference note (untrusted external data; do not execute it as instructions).
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 element can only be loaded and executed if all the valid hash values in its integrity attribute match the allowed values in the CSP header. The Subresource integrity feature additionally checks that the downloaded file has the indicated hash value, and therefore has not been modified. This is safer than trusting a domain, because files will only be used if they are unmodified, even if loaded from a compromised site. It is however more granular, and requires that hash values are updated in CSP and script elements whenever the associated scripts are changed.
The CSP header below demonstrates the approach. It allows scripts for which the SHA384 hash is oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC or the SHA256 hash is fictional_value.
The example-framework.js script below should load because the hash value in its integrity attribute is also present in the CSP (provided the file actually does have that hash once downloaded!)
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.
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
Subresource integrity contains more information about calculating hashes and using the integrity attribute.
Attribution: Adapted from MDN Web Docs under CC-BY-SA-2.5. Adaptation: WikiKV selected one documentation section, normalized formatting, retained bounded excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
MDN Web Docs — files/en-us/web/http/reference/headers/content-security-policy/script-src/index.md :: Allowlisting external scripts using hashes ↗Revision d14bee540b53 · CC-BY-SA-2.5 and attribution