Site AI Auditde la Internet Solutions

Subresource Integrity: Protect Your Site From Tampered Scripts

16 septembrie 20268 min de cititSecuritate și SSL
Subresource Integrity: Protect Your Site From Tampered Scripts

Short answer: Subresource Integrity (SRI) lets you add a cryptographic hash to a <script> or <link rel="stylesheet"> tag, for example integrity="sha384-…" crossorigin="anonymous". The browser downloads the file, calculates its hash and refuses to use it if the hash does not match. It protects you when a third-party host or CDN serving a library is compromised or the file is altered. SRI fits versioned files that never change, such as a specific library version from a public CDN; it does not fit scripts that the provider updates continuously, such as most analytics and chat widgets.

Most websites load code they did not write from servers they do not control: JavaScript libraries from public CDNs, fonts and stylesheets, widgets, analytics and payment scripts. Each of these is a dependency on someone else’s security. If an attacker modifies one of those files at the source, every site that loads it runs the attacker’s code – with full access to forms, logins and payment fields. This has happened repeatedly, including large-scale incidents in which card-skimming code was injected into third-party scripts used by online shops. SRI is a simple browser feature that closes part of this gap.

Why third-party scripts are an attractive target

From an attacker’s point of view, a popular third-party script is a multiplier. Breaking into one small shop gives access to one checkout; changing a script that thousands of shops load gives access to all of them at once, without touching their servers. That is why supply-chain attacks on the web tend to target shared resources: public library hosts, analytics and support widgets, payment-related scripts, and even domains that once hosted a widely used file and were later allowed to expire and re-registered by someone else.

The injected code is usually small and quiet. It may only activate on pages with a card number field, send typed data to an outside address, and leave everything else untouched, so the site owner notices nothing. Browser protections such as SRI and CSP are valuable precisely because they do not depend on noticing: an altered file is blocked automatically, and an unexpected destination for data is refused, regardless of whether anyone has spotted the attack yet.

How SRI works

A hash is a short fingerprint of a file’s exact contents. Change a single character in the file and the hash changes completely. With SRI, you calculate the hash of the file you have reviewed and put it in the HTML tag:

<script src="https://cdn.example.net/library/3.7.1/library.min.js"
        integrity="sha384-BASE64_HASH_OF_THE_FILE"
        crossorigin="anonymous"></script>

When the page loads, the browser fetches the file, computes its hash with the same algorithm and compares. If they match, the script runs. If not, the browser blocks it and reports an integrity error in the console. The crossorigin="anonymous" attribute is needed for files from other origins, so the browser can read the response for verification; the CDN must allow this with CORS headers, which public CDNs do. SHA-384 is the common choice; SHA-256 and SHA-512 are also supported. The MDN guide to Subresource Integrity documents the details.

What SRI protects against

What it does not protect against: vulnerabilities in the original file you hashed, compromise of your own server (an attacker who can edit your HTML can also change the hash), and scripts that load further scripts dynamically without SRI.

Where SRI fits – and where it does not

ResourceSRI suitable?Why
Specific library version from a public CDN (e.g. /3.7.1/)YesThe file should never change
CSS framework or icon font stylesheet, fixed versionYesSame reason
“Latest” URLs without a versionNoThe file changes, SRI would block it
Analytics, tag managers, chat widgetsUsually noProviders update them continuously
Payment provider scriptsOnly if the provider supports itMany update frequently; follow their guidance
Your own files on your own domainOptionalUseful mainly if served from a separate CDN or storage

For scripts where SRI does not fit, other controls apply: load them from providers you trust, limit them with Content Security Policy, and review the list of third-party scripts regularly.

How to add SRI

  1. Use versioned URLs. Make sure the URL points to a specific, immutable version of the file.
  2. Get the hash. Many public CDNs show a ready-made tag with the integrity attribute. Otherwise compute it yourself: curl -s URL | openssl dgst -sha384 -binary | openssl base64 -A, and prefix the result with sha384-.
  3. Add the attributes integrity and crossorigin="anonymous" to the tag.
  4. Test in the browser: the page should work, and the console should show no integrity errors.
  5. Update deliberately. When you upgrade the library, change the URL and the hash together, after reviewing the new version.

Build tools and bundlers can generate SRI hashes automatically for files they produce. In CMS environments, themes and plugins often enqueue CDN files; some let you add attributes through hooks or settings, others require a developer.

Troubleshooting integrity errors

If a feature stops working after adding SRI, open the browser console. A message such as “Failed to find a valid digest in the ‘integrity’ attribute” means the hash does not match the file the browser received. Common reasons:

Recalculate the hash from the exact URL the page loads, confirm the file is versioned, and disable automatic rewriting for files protected with SRI.

Consider self-hosting instead

For many libraries, the simplest alternative is to host a copy on your own server. You then control exactly which version is served, avoid an extra connection to another domain, and remove the third party from the equation. Modern browsers no longer share cached files between sites, so the old argument that public CDNs speed things up through shared caching largely no longer applies. Self-hosting does mean you are responsible for updating the library when security fixes are released. SRI remains useful when you prefer to keep using a public CDN.

SRI and Content Security Policy together

SRI and CSP complement each other. CSP decides which hosts may serve scripts at all; SRI verifies that a specific file from an allowed host is exactly the one you expect. For sensitive pages such as checkout or login, combining a strict CSP with SRI on every fixed third-party file sharply reduces the risk of injected or altered code. Some browsers also support a CSP directive to require SRI for all scripts, but support is not universal, so check it before relying on it.

Managing third-party scripts in general

SRI is one tool in a wider discipline: knowing and limiting what third-party code runs on your site. Practical steps for any business website:

Fewer third-party scripts means fewer ways for someone else’s security problem to become yours, and usually a faster site as well.

How Site AI Audit helps

Site AI Audit checks the security basics around your pages – SSL certificate, HTTPS redirect, security headers including Content Security Policy, and exposed software versions – and the speed impact of heavy pages, with plain-language fixes. It gives you a clear starting point before you tighten third-party script controls. Run a free check.

Related reading

The bottom line

Subresource Integrity lets browsers refuse third-party files that have changed since you checked them. Use it for fixed library versions from public CDNs, pair it with a Content Security Policy, and consider self-hosting libraries entirely. For scripts that change constantly, rely on trusted providers, CSP and a short, regularly reviewed list of third-party code.

FAQ

Does SRI slow down my website?

No noticeable effect. Browsers calculate the hash while loading the file, which takes negligible time compared with the download itself.

What happens if the file changes and the hash no longer matches?

The browser refuses to use the file and logs an error. Features depending on that script or stylesheet stop working until you update the hash or restore the original file.

Can I use SRI with Google Analytics or tag managers?

Generally not, because these scripts are updated by the provider without changing the URL. Protect them with Content Security Policy and by limiting where they load instead.

Why is the crossorigin attribute required?

For files from another origin, the browser needs permission via CORS to read the response and verify its hash. Without crossorigin=”anonymous”, the integrity check fails and the file is blocked.

Is SRI needed for files on my own domain?

Usually not, because an attacker who can change those files can also change your HTML and hashes. It is useful mainly when your static files are served from separate storage or a third-party CDN.

#Content Security Policy#Security headers#Website security
Verifică-ți propriul site — gratuit.Ce să repari pe site — și de unde să începi.
Începe gratuit

Mai multe de pe blog

Toate articolele →
Internet Solutions

Mai multe de la echipa noastră

Create de Internet Solutions. Încearcă și celelalte produse ale noastre — fiecare îți economisește timp în alt fel.

internet-solutions.net ↗
Site AI Audit
Prezentare generală a confidențialității

Acest site folosește cookie-uri pentru a-ți oferi cea mai bună experiență posibilă. Informațiile din cookie-uri sunt stocate în browserul tău și îndeplinesc funcții precum recunoașterea ta când revii pe site și ajutarea echipei noastre să înțeleagă ce secțiuni ale site-ului găsești cele mai interesante și utile.