How Subresource Integrity Verifies CDN JavaScript

Subresource Integrity (SRI) is a web security standard that enables browsers to verify that third-party assets, such as JavaScript files fetched from Content Delivery Networks (CDNs), have not been maliciously modified or compromised. By matching a cryptographic hash declared in the web page’s HTML against the hash of the downloaded file, SRI ensures that the browser only executes code that matches the exact version intended by the developer.

The Mechanism Behind Subresource Integrity

Subresource Integrity relies on cryptographic hashing algorithms (typically SHA-256, SHA-384, or SHA-512) to create a unique fingerprint of a JavaScript file.

The verification process follows four primary steps:

  1. Hash Generation: Before deploying code, a developer generates a cryptographic hash of the static JavaScript file using a tool like OpenSSL or an online hash generator.
  2. Declaration in HTML: The developer adds the generated hash to the <script> tag using the integrity attribute, along with the crossorigin="anonymous" attribute to handle Cross-Origin Resource Sharing (CORS) requirements.
  3. Fetching and Hashing: When a user visits the site, the browser downloads the external script from the CDN. Before executing the code, the browser computes the hash of the downloaded file using the algorithm specified in the integrity string.
  4. Comparison and Execution: The browser compares the newly calculated hash with the string in the integrity attribute. If the hashes match bit-for-bit, the browser executes the script. If the hashes differ, the browser blocks execution and throws a network error in the developer console.

Implementation Example

An SRI-enabled script tag includes both the algorithm prefix and the base64-encoded hash:

<script 
  src="https://cdn.example.com/library.js" 
  integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC" 
  crossorigin="anonymous">
</script>

Why CORS is Required

Because the script is fetched from an external origin (the CDN), the crossorigin="anonymous" attribute is mandatory for SRI validation. Without this attribute, the browser cannot read the raw response data needed to compute the hash due to standard cross-origin restrictions, causing the integrity check to fail automatically.

Threats Mitigated by SRI