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:
- 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.
- Declaration in HTML: The developer adds the
generated hash to the
<script>tag using theintegrityattribute, along with thecrossorigin="anonymous"attribute to handle Cross-Origin Resource Sharing (CORS) requirements. - 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
integritystring. - Comparison and Execution: The browser compares the
newly calculated hash with the string in the
integrityattribute. 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
- CDN Compromises: If an attacker breaches a CDN and injects malicious code (such as keyloggers or form-jackers) into a hosted library, the file’s hash changes, causing browsers with SRI enabled to block the compromised file.
- Man-in-the-Middle (MitM) Attacks: Even if traffic is intercepted or redirected, modified scripts will fail hash verification and be discarded.
- Accidental File Alterations: Any accidental updates or modifications made by the CDN provider that alter the file will be prevented from silently breaking application behavior.