Skip to main content

Free 30-min security demo  — We'll scan your real code and show live findings, no commitment Book Now

Offensive360
Academy Subresource Integrity
Beginner · 15 min

Subresource Integrity

Learn how CDN script tampering can be prevented with the integrity attribute and cryptographic hash verification.

1 CDN Script Tampering Without SRI

Content Delivery Networks (CDNs) distribute libraries like jQuery, Bootstrap, and analytics scripts. If a CDN is compromised or you load a script from an untrusted source, malicious code can run on your users' browsers.

The attack scenario:

  1. Your page loads: <script src="https://cdn.example.com/jquery-3.6.0.min.js"></script>
  2. Attacker compromises the CDN or performs a MITM attack
  3. Malicious version of jQuery is served
  4. All visitors execute the attacker's code with full browser privileges

This is not theoretical — cdnjs, unpkg, and npm have all had incidents. The 2022 Polyfill.io supply chain attack compromised a widely-used CDN script.

Without SRI, you have no way to detect if the CDN serves a different file than expected.

2 The integrity= Attribute

Subresource Integrity (SRI) lets browsers verify that a loaded resource has not been tampered with by specifying a cryptographic hash of the expected content.

Using SRI:

<script
  src="https://code.jquery.com/jquery-3.7.1.min.js"
  integrity="sha384-1H217gwSVyLSIfaLxHbE7dRb3v4mYCKbpQvzx0cegeju1MVsGrX5xXxAvs/HgeFs"
  crossorigin="anonymous">
</script>

Generate a hash:

# Generate sha384 hash of a resource
curl -s https://example.com/library.js | \
  openssl dgst -sha384 -binary | \
  openssl base64 -A

How it works:

  1. Browser downloads the script
  2. Computes SHA-384 (or SHA-256/SHA-512) hash of the content
  3. Compares with the hash in the integrity attribute
  4. If mismatch: script is blocked and an error is logged

Defense checklist:

  • Add integrity= attribute to all externally-hosted scripts and stylesheets
  • Use SHA-384 as the minimum hash strength
  • Set crossorigin="anonymous" to enable CORS (required for SRI)
  • Self-host critical libraries when possible to avoid CDN dependency

Knowledge Check

0/3 correct
Q1

What does Subresource Integrity protect against?

Q2

Which attribute makes SRI work in HTML script tags?

Q3

Why must crossorigin="anonymous" be set alongside the integrity attribute?

Code Exercise

Add SRI to CDN Script Tag

The script tag loads jQuery from a CDN without SRI. Add the integrity attribute with a SHA-384 hash and the required crossorigin attribute.

html