The risk of third-party resources

Most sites load resources from CDNs (Content Delivery Networks): jQuery from jQuery CDN, Bootstrap from jsDelivr, fonts from Google Fonts. Each time you write <script src="https://cdn.example.com/lib.js">, you trust that CDN's infrastructure.

CDNs are prime targets for attackers. In 2018, the Polyfill.io library (loaded by millions of sites) was compromised and started serving malicious scripts. These supply chain attacks are particularly dangerous because they are invisible from your own code.

How SRI works

SRI (Subresource Integrity) is a browser mechanism that verifies the cryptographic fingerprint of an external resource before executing it:

  1. You calculate the hash (cryptographic fingerprint, typically SHA-384) of the resource when you choose it
  2. You add this hash in the integrity attribute of your <script> or <link> tag
  3. The browser downloads the resource, recalculates its hash and compares it with the attribute
  4. If the hashes don't match (resource modified), the browser blocks execution

Practical example

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

The crossorigin="anonymous" attribute is required for SRI to work, enabling CORS (Cross-Origin Resource Sharing) verification.

Generating an SRI hash

  • Online: srihash.org — paste the resource URL
  • Command line:
curl -s https://cdn.example.com/lib.js | openssl dgst -sha384 -binary | openssl base64 -A

SRI and changing resources

SRI is incompatible with dynamically-updating resources. If the CDN updates its library without notice, your site will break. For major libraries, update the hash whenever you update the version.

Check your SRI usage

TheSiteFuse detects external resources loaded without an integrity attribute on your site. Run a free audit to identify your CDN dependencies not protected by SRI.