How SRI Prevents Malicious Third-Party Scripts

Subresource Integrity (SRI) is a security mechanism that allows web browsers to verify that fetched external resources, such as third-party JavaScript files, have not been altered or compromised. By providing a cryptographic hash in the integrity attribute of a <script> tag, developers ensure that the browser will only execute a file if its content matches the expected signature. This article explains how SRI works, how it mitigates supply chain attacks, and how to implement it correctly in web applications.

The Problem: Vulnerabilities in Third-Party Scripts

Modern web development relies heavily on Content Delivery Networks (CDNs) and external repositories to serve common libraries like jQuery, React, or analytics tools. While this improves delivery speed and caching, it introduces significant security risks:

Without SRI, the browser treats any valid JavaScript received from a trusted domain as safe and executes it with the full privileges of the hosting application.

The SRI Verification Process

Subresource Integrity solves this by enforcing content-based verification rather than domain-based trust. The process operates in four main steps:

  1. Hash Generation: The website developer generates a cryptographic hash of the known, unmodified script using a secure algorithm such as SHA-256, SHA-384, or SHA-512.
  2. Declaration: The developer places this hash value into the integrity attribute of the script tag in the HTML source.
  3. Download and Calculation: When a user visits the site, the browser downloads the external file and independently computes the hash of the incoming content in real time before execution.
  4. Validation and Execution Decision:
    • Match: If the computed hash matches the integrity attribute, the script runs normally.
    • Mismatch: If the file has been modified—even by a single byte—the hashes will not match. The browser blocks the script from executing and logs a network/security error in the developer console.

Implementation Example

To implement SRI, add the integrity and crossorigin attributes to your script tags:

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

Key Components:

Limitations to Consider

While SRI is an effective defense against compromised third-party files, it has specific constraints: