Subresource Integrity (SRI)
Guide to Subresource Integrity covering hash-based verification, CDN supply chain protection, browser enforcement mechanics, and implementation best practices.
Continue your mission
Guide to Subresource Integrity covering hash-based verification, CDN supply chain protection, browser enforcement mechanics, and implementation best practices.
# Subresource Integrity (SRI)
Subresource Integrity (SRI) is a World Wide Web Consortium (W3C) security standard that allows web developers to cryptographically verify the exact content of external scripts and stylesheets before browsers execute or apply them. Published as a W3C Recommendation in 2016, SRI addresses a fundamental weakness in how modern web applications load third-party code: the implicit trust relationship between a website and every Content Delivery Network (CDN) it relies upon.
SRI exists because web applications routinely load JavaScript libraries, CSS frameworks, and other resources from external origins they do not control. A single compromised CDN can inject malicious code into thousands of websites simultaneously. Traditional transport security (HTTPS) and origin controls (Content Security Policy) verify that content arrives from the expected domain over an encrypted connection, but neither mechanism validates that the content itself matches what the developer intended to load. An attacker who compromises a CDN account or exploits a vulnerability in the CDN's infrastructure can serve modified content over a perfectly valid HTTPS connection from a trusted domain.
SRI interrupts this attack vector by embedding a cryptographic hash directly in the HTML element that requests the resource. When the browser fetches the external file, it computes a hash of the received bytes and compares it to the hash specified by the developer. If the hashes match, the resource loads normally. If they differ, the browser discards the resource entirely and generates a network error. This verification happens at the browser level, making it independent of network infrastructure, proxies, or server-side controls.
The standard applies specifically to resources loaded via and HTML elements. It does not extend to resources loaded through JavaScript APIs like fetch() or XMLHttpRequest, dynamically inserted DOM elements, images, fonts referenced in CSS, or content loaded in iframes. This scope limitation is intentional: SRI targets the highest-risk injection vectors in static HTML markup where developers have explicit control over the resource declarations.
SRI operates through a four-step process: hash generation, hash embedding, resource fetching, and verification enforcement. Each step requires precise execution to ensure the security mechanism functions correctly.
Hash Generation
The developer computes a cryptographic hash of the exact bytes of the external resource using one of three algorithms specified in the W3C standard: SHA-256, SHA-384, or SHA-512. SHA-384 represents the recommended balance between security margin and hash length for most applications. The computed hash is Base64-encoded and prefixed with the algorithm name, producing a string like sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC.
Hash generation must occur against the exact production artifact that will be served to browsers, not a development copy or local version. Even minor differences in file encoding, line endings, or trailing whitespace will produce different hashes and cause verification failures. The openssl command-line tool can generate SRI hashes directly:
openssl dgst -sha384 -binary jquery.min.js | openssl base64 -ASeveral online tools, including the official SRI Hash Generator at srihash.org, automate this process for publicly accessible URLs by fetching the resource and computing its hash in real-time.
Hash Embedding
The developer embeds the Base64-encoded hash string in the integrity attribute of the HTML element that loads the resource. A complete implementation looks like this:
<script
src="https://cdn.example.com/library/3.6.0/jquery.min.js"
integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
crossorigin="anonymous">
</script>The crossorigin="anonymous" attribute is mandatory for cross-origin resources. Without it, the browser fetches the resource in "no-cors" mode, which prevents access to the response body needed for hash computation. The browser requires Cross-Origin Resource Sharing (CORS) headers from the serving origin to enable integrity checking.
Multiple hash values can be specified in a single integrity attribute, separated by spaces. This supports scenarios where a CDN might serve different versions of a file during rollout periods or where multiple valid versions exist temporarily during migrations.
Fetch and Verification
When the browser encounters an element with an integrity attribute, it fetches the resource through the normal network stack. Upon receiving the complete response body, the browser computes the hash of the received bytes using the algorithm specified in the integrity attribute. The browser then performs a byte-for-byte comparison between the computed hash and the expected hash embedded in the HTML.
This verification occurs before any execution or application of the resource. For JavaScript files, the hash check happens before the browser's JavaScript engine parses or compiles the code. For CSS files, verification occurs before the browser applies any styles to the document.
Enforcement
Hash matches result in normal processing: scripts execute and stylesheets apply as expected. Hash mismatches trigger strict enforcement: the browser refuses to execute scripts or apply stylesheets, generates a network error event, and logs a console message indicating the integrity check failure. If a Content Security Policy with a report-uri directive is configured, the browser also sends a violation report to the specified endpoint.
The browser treats integrity failures as fatal errors, not as fallback triggers. There is no mechanism for graceful degradation or alternative resource loading when SRI verification fails. This strict enforcement is intentional: it prevents attackers from bypassing integrity checks through crafted responses designed to cause parsing errors.
Cross-Origin Requirements
SRI verification requires the external origin to serve appropriate CORS headers. For public CDNs serving libraries intended for cross-origin use, this typically means Access-Control-Allow-Origin: *. Most major CDNs including Cloudflare, jsDelivr, and unpkg serve these headers by default. Private CDNs or custom hosting environments may require explicit CORS configuration.
The CORS requirement means SRI cannot protect resources served from origins that do not support cross-origin access. This is a meaningful limitation for applications loading resources from legacy systems or third-party services not designed for browser-based cross-origin access.
Dynamic Content Limitations
SRI is incompatible with resources that change content on each request, such as personalized scripts, analytics beacons with embedded session data, or dynamically generated CSS with user-specific themes. Since the hash is computed against specific byte content, any variation in the response body will cause verification failures. This constraint requires careful architecture decisions about which resources can be statically hashed and which must be served from trusted origins without SRI protection.
Modern web applications face a supply chain security problem that SRI directly addresses. Every external script, CSS framework, and third-party library represents a potential attack vector. Without cryptographic verification, applications implicitly trust not only the CDN's domain and transport security but also every administrative account, deployment pipeline, storage system, and network component between the CDN and the browser.
Real-World Supply Chain Attacks
The event-stream incident of November 2018 demonstrated the scope of supply chain vulnerabilities in practice. A widely used npm package called event-stream was transferred to a new maintainer who injected malicious code targeting the Copay Bitcoin wallet application. While this attack primarily affected Node.js applications through package installation, it illustrates the broader principle: when trusted dependencies are compromised, applications loading those dependencies inherit the compromise. For browser-facing applications loading compiled bundles that include compromised packages, SRI provides the last line of defense between CDN delivery and code execution.
The British Airways breach of 2018 involved attackers injecting a skimming script into the airline's website by compromising a third-party supplier. Approximately 500,000 customers had payment card details stolen through the injected script. Post-incident analysis identified that SRI implementation for all external scripts would have prevented the skimmer from executing, since the malicious script was not the expected content of any legitimate resource.
The HTTPS Misconception
A common misconception treats HTTPS as sufficient protection against content tampering. HTTPS encrypts data in transit and authenticates the server's identity through certificate validation, but it does not verify that the server's owner has not modified the content. A legitimate CDN serving modified content over a valid HTTPS connection with proper certificates presents no transport-layer security violation. SRI fills this gap by validating content integrity regardless of transport security.
The CSP Misconception
Another misconception treats Content Security Policy as redundant with SRI or as a complete alternative. CSP controls which origins can serve resources; SRI controls whether the content from those origins matches developer expectations. These are complementary controls addressing different attack vectors. An application with CSP but without SRI remains vulnerable to malicious content served from trusted origins. An application with SRI but without CSP remains vulnerable to malicious content served from untrusted origins if the attacker can guess or brute-force valid hashes.
Business Impact
Supply chain compromises through CDN manipulation can result in data theft, payment card skimming, cryptocurrency wallet compromise, session hijacking, and regulatory violations. For e-commerce applications, a single compromised JavaScript library can expose every customer transaction. For financial services applications, compromised external resources can violate PCI DSS requirements and result in significant fines. For healthcare applications, compromised scripts can lead to HIPAA violations and patient data exposure.
The reputational impact of supply chain breaches often exceeds the immediate technical damage. Customers lose trust in applications that fail to protect against third-party compromises, particularly when those compromises result in financial losses or identity theft. SRI implementation demonstrates technical competence and security awareness to both customers and regulators.
CDA approaches Subresource Integrity through the Planetary Defense Model (PDM), specifically within the Vulnerability and Surface Defense (VSD) domain. The governing methodology is Continuous Surface Reduction (CSR): every surface exposed is a surface that must be eliminated where possible and hardened where elimination is not feasible.
In the VSD domain, third-party resources loaded into web applications represent an extended attack surface that spans organizational boundaries. CDA does not treat CDN-hosted resources as inherently trusted simply because they arrive over HTTPS or from known domains. Every external script and stylesheet is treated as an untrusted input until cryptographically verified against a known-good hash at load time.
CDA's operational approach to SRI within CSR includes four specific requirements. First, SRI hash generation becomes a mandatory step in the deployment pipeline for any application loading external resources. Hash generation runs against the exact production artifact being referenced, eliminating hash drift between development and production environments. Build systems fail when external resources lack valid integrity hashes.
Second, CDA integrates SRI verification into automated testing suites. Browser automation tests verify that all script and link elements in production HTML carry valid integrity attributes. Missing integrity attributes trigger pipeline failures and generate VSD domain alerts. This automation prevents the common operational anti-pattern of removing SRI hashes to resolve deployment issues rather than fixing the underlying hash management problem.
Third, CDA maintains third-party resource dependencies in a controlled inventory aligned with Software Bill of Materials (SBOM) practices. When CDN vendors update library versions, new hashes are computed, security-reviewed, and deployed through controlled change management before old versions are deprecated. This prevents the operational disruption that sometimes causes development teams to abandon SRI implementation rather than maintain it properly.
Fourth, CDA combines SRI enforcement with CSP reporting to generate real-time alerts when hash mismatches occur in production. This provides detection capability alongside prevention, allowing security operations teams to identify active supply chain manipulation attempts within minutes of occurrence. Hash mismatch alerts receive the same priority as active intrusion alerts.
The CSR principle drives CDA to prefer self-hosting critical JavaScript dependencies over CDN loading where operationally feasible, eliminating the third-party surface entirely. When CDN usage is required for performance or operational reasons, SRI becomes a non-negotiable compensating control. CDA does not permit external resource loading without cryptographic verification.
• Generate SRI hashes against exact production artifacts through automated CI/CD pipeline integration, never through manual processes or against development copies, and treat missing integrity attributes as deployment failures that halt releases.
• Always pair the integrity attribute with crossorigin="anonymous" on cross-origin elements; browsers silently skip integrity checking when the crossorigin attribute is omitted, creating a false sense of security without actual protection.
• Combine SRI with Content Security Policy to achieve defense in depth: CSP restricts which origins can serve resources while SRI verifies that content from permitted origins matches expected bytes, addressing complementary attack vectors.
• Configure CSP reporting endpoints to generate actionable alerts when hash mismatches occur in production, providing detection capability for active supply chain attacks alongside the prevention capability of failed resource loads.
• Maintain an inventory of all third-party resources and their corresponding hashes as part of Software Bill of Materials practices, establishing defined change management processes for hash updates when vendors release new versions.
CDA Theater missions that address topics covered in this article.
COBIT 2019 is ISACA's IT governance framework with 40 objectives across five domains, featuring a flexible design factor system that aligns IT strategy with business goals and maps to standards like NIST CSF and ISO 27001.
CMMC 2.0 requires defense contractors to demonstrate cybersecurity maturity at three levels.
HITRUST CSF harmonizes multiple frameworks into one certifiable standard for healthcare.
Written by CDA Editorial
Found an issue? Help improve this article.