SiteLint documentation and guidelines

Missing defined INTEGRITY attribute that enables browsers to verify that resources they fetch are delivered without unexpected manipulation.

Description

The subresource-integrity rule verifies that <script> and <link> elements loading external resources include the integrity attribute containing a cryptographic hash of the expected file contents. This check covers <script src>, <link rel="stylesheet">, <link rel="preload">, and <link rel="modulepreload"> elements.

Without the integrity attribute, the browser has no way to verify that a fetched resource has not been tampered with. If a Content Delivery Network (CDN) or third-party server is compromised, an attacker could inject malicious code into a resource that the browser trusts and executes. The W3C Subresource Integrity specification enables browsers to compare a resource’s content against a known hash, rejecting any mismatch before the resource takes effect.

Common impact areas

  • End users: users are the primary victims of supply-chain attacks. Missing SRI on external scripts means a compromised CDN can serve malicious JavaScript that steals credentials, redirects to phishing pages, or installs malware without any visible indication.
  • Site owners: a successful supply-chain attack through an unsigned external resource can lead to data breaches, regulatory penalties under frameworks like PCI DSS, and loss of user trust. The reputational damage from a single incident can far exceed the cost of implementing SRI.
  • Developers and maintainers: without SRI, developers have no automated way to detect that a third-party resource has changed unexpectedly. Debugging becomes harder when external dependencies silently update and introduce behavioral changes or vulnerabilities.
  • Third-party CDN providers: even reputable CDN providers are not immune to compromise. Implementing SRI creates a contractual-like boundary where the provider’s integrity is cryptographically enforced, reducing trust assumptions.
  • Compliance auditors: security audits and penetration tests increasingly expect SRI on external resources. Its absence is a finding in most modern security assessment frameworks, including OWASP ASVS requirements around supply-chain integrity.

Why it matters

Subresource Integrity is a critical defense-in-depth mechanism against supply-chain attacks. An attacker who compromises a CDN, DNS, or upstream server can inject arbitrary JavaScript into every page that loads the compromised resource.

By adding a cryptographic hash to the integrity attribute, the browser refuses to execute any resource whose content does not match the expected digest. This neutralizes man-in-the-middle attacks, CDN compromise, DNS hijacking, and rogue server injection. SRI also supports Content Security Policy (CSP) by providing an additional layer of verification that CSP alone cannot guarantee.

Coding problems and solutions

Common coding problems

  • Missing integrity attribute entirely: external scripts and stylesheets are loaded without any integrity check, leaving the browser vulnerable to tampered resources.
  • Missing crossorigin attribute: for cross-origin resources, SRI requires crossorigin="anonymous" (or use-credentials). Without it, the browser blocks the resource due to CORS restrictions before the integrity check even runs.
  • Wrong hash algorithm: using an outdated or weak algorithm like SHA-1 instead of SHA-256, SHA-384, or SHA-512 weakens the integrity check.
  • Incorrect hash value: using a hash from the provider’s website instead of computing it from the actual fetched file. CDN-provided hashes may be stale or incorrect.
  • Dynamic resource insertion without SRI: JavaScript that injects <script> or <link> elements at runtime without pre-computing the integrity hash.
  • Conflicting CSP require-trusted-types-for: Trusted Types policies may inadvertently strip or reject integrity attributes during DOM insertion.

How to fix it

Add the integrity and crossorigin attributes to external resources

Every external <script> and <link> that loads a resource from a different origin must include both integrity (containing the SHA-256 hash) and crossorigin="anonymous".

Correct example
<script src="https://cdn.example.com/library.min.js"
  integrity="sha384-abc123def456ghi789jkl01mno2rst"
  crossorigin="anonymous"></script>

<link rel="stylesheet"
  href="https://cdn.example.com/styles.min.css"
  integrity="sha384-xyz789ghi01mno2rst"
  crossorigin="anonymous">
Incorrect example
<script src="https://cdn.example.com/library.min.js"></script>

<link rel="stylesheet"
  href="https://cdn.example.com/styles.min.css">

Generate hashes from the actual file, not the provider

Always compute the hash from the file you actually fetch. Never trust a hash displayed on a CDN’s documentation page without verifying it matches the served content.

Correct example
# Download the file and compute its hash locally
curl -o lib.min.js https://cdn.example.com/library.min.js
openssl dgst -sha384 -binary lib.min.js | openssl base64 -A
Incorrect example
<!-- Trusting the hash from the CDN documentation without verification -->
<script src="https://cdn.example.com/library.min.js"
  integrity="sha384-hashFromCDNwebsite"
  crossorigin="anonymous"></script>

Include crossorigin for all cross-origin resources

Without the crossorigin attribute, the browser performs a CORS check before loading the resource. For cross-origin resources without CORS headers, the request fails entirely and the integrity check never runs.

Correct example
<link rel="stylesheet"
  href="https://fonts.googleapis.com/css2?family=Inter"
  integrity="sha384-verifiedhash123"
  crossorigin="anonymous">
Incorrect example
<link rel="stylesheet"
  href="https://fonts.googleapis.com/css2?family=Inter"
  integrity="sha384-verifiedhash123">
<!-- Missing crossorigin attribute; CORS check will block loading -->

Use a build tool to automate hash generation

Manually computing hashes is error-prone. Build tools can automatically inject integrity hashes during the build process, ensuring hashes always match the served content.

Correct example
// webpack.config.js with webpack-subresource-integrity plugin
const { SubresourceIntegrityPlugin } = require("webpack-subresource-integrity");

module.exports = {
  plugins: [
    new SubresourceIntegrityPlugin({ hashFuncNames: ["sha384"] })
  ]
};
Incorrect example
// Manually hardcoding hashes that may become stale after CDN updates
const sriHash = "sha384-oldhash";
const script = document.createElement("script");

script.src = "https://cdn.example.com/lib.min.js";
script.integrity = sriHash;

document.head.appendChild(script);

Known limitations

  • Self-hosted resources: SRI only protects against tampering of the fetched resource. If the server itself is compromised and the file is modified before delivery, the hash must be recomputed. Self-hosted resources require an automated build pipeline to keep hashes in sync.
  • Content Delivery Network caching: CDN edge caches may serve different versions of a resource to different users. If a new version is deployed with a different hash but old cached versions still have the original hash, users may receive mismatched resources during the transition period.
  • Dynamic or hashed URLs: resources loaded with cache-busting query strings or content-hashed filenames (e.g., bundle.a1b2c3.js) require the hash to be updated in the HTML each time the file changes, which adds complexity to deployment pipelines.
  • Web Components with Shadow DOM: scripts dynamically inserted into shadow roots may not be subject to SRI checks in all browsers, reducing the effectiveness of the mechanism for component-based architectures.
  • Browser compatibility: while modern browsers support SRI, older browsers ignore the integrity attribute entirely. SRI is a defense-in-depth measure, not a universal guarantee.
  • Local attacks: SRI does not protect against local system compromise such as a compromised OS, local DNS poisoning, or malware on the user’s machine that modifies network traffic before it reaches the browser.

Resources

Code examples that helps to generate SRI hash from the file

Generating SRI hash using Go Programming Language
package sri

import (
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"io/ioutil"
)

func Generate256(file string) (string, error) {
	body, err := ioutil.ReadFile(file)

	if err != nil {
		return "", err
	}

	hash := sha256.Sum256(body)
	sha := base64.StdEncoding.EncodeToString(hash[:])

	return fmt.Sprintf("sha256-%s", sha), nil
}

// package main
//
// import (
//     "fmt"
//     "sri"
// )
//
// func main() {
//     sha, err := sri.Generate256("./src/sri.go")
//
//     if err != nil {
//         panic(err)
//     }
//
//     fmt.Println(sha)
// }
//
Generating SRI hash using JavaScript Programming Language
const crypto = require('crypto');
var const     = require('fs');

module.exports = function (file) {
    const enc  = 'utf8';
    const body = fs.readFileSync(file, { encoding: enc });
    const hash = crypto.createHash('sha256').update(body, enc);
    const sha  = hash.digest('base64');

    return `sha256-${sha}`;
}

// > const generate256 = require('./sri.js');
// undefined
// > generate256("./sri.js");
// 'sha256-U+9zwgl5Wcs2X0IzBnN/4Ri016f8lkdtvmPZuIytt8Y='
// >
Generating SRI hash using PHP Programming Language
<?php
function generate256($path) {
  $file = fopen($path, 'r');
  $body = @fread($file, filesize($path));

  if ($body === false) {
    return '';
  }

  $hash = hash('sha256', $body, true);
  $sha  = base64_encode($hash);

  return 'sha256-$sha';
}

// php > include './sri.php';
// php > echo generate256("./sri.php");
// sha256-wdToXd37ShQdyh8ljZAJoqvPXdQEiyqGv/IBnbKkg3A=
// php >
?>
Generating SRI hash using Python Programming Language
import base64
import hashlib

def generate256(file):
    with open(file, 'r') as f:
        body = f.read()
        hash = hashlib.sha256(body).digest()
        sha  = base64.b64encode(hash).decode()
        return 'sha256-{}'.format(sha)

# Python 2.7.10 (default, Oct 14 2015, 16:09:02)
# [GCC 5.2.1 20151010] on linux2
# Type "help", "copyright", "credits" or "license" for more information.
# >>> from sri import generate256
# >>> generate256("sri.py")
# 'sha256-ZDTvTHvqQDypoPxKGrkYPNVeXQPvKqnZeAFvRZ1l+ik='
# >>>
Generating SRI hash using Ruby Programming Language
require 'digest'
require 'base64'

def generate256(file)
  body = File.read(file)
  hash = Digest::SHA256.digest(body)
  sha  = Base64.encode64(hash).strip

  "sha256-#{sha}"
end

# irb(main):001:0> require './sri'
# => true
# irb(main):002:0> generate256("sri.rb")
# => "sha256-zna8a/EB5hMXmiyjg+iSy5/Xar/+Cv0EDF1STWr+Mwo="
Generating SRI hash using Shell script
function generate256 {
  echo "sha256-`cat $1 | openssl dgst -sha256 -binary | openssl enc -base64 -A`"
}

# jmervine@laptop:~/sri $ source sri.sh
# jmervine@laptop:~/sri $ generate256 "sri.sh"
# sha256-wS2IFRvHJO0XSkrEvudmfw2nBnNz+E1o4AJ2Cf/HpZs=

Source: GitHub.

Rule

  • Audit: security
  • Standard: SiteLint
  • Level: Best practices
  • Success Criteria: N/A
  • Rule ID: subresource-integrity