Add Subresource Integrity to third-party scripts on WordPress
Why it matters
If a CDN or vendor serving your scripts is compromised, the altered file runs on your pages with full access to them. An integrity hash makes the browser refuse any file that differs from the one you approved.
Staged change. Do this in stages and check each one before the next, so a mistake does not break your site or your mail.
The fix
- Stage 1: find the handles of the third-party scripts and styles your theme and plugins enqueue from fixed-version CDN URLs, and compute their sha384 hashes as in the generic steps.
- Stage 2: add them with the must-use plugin below, which uses the script_loader_tag and style_loader_tag filters. A plugin update that changes the URL or version makes the hash wrong and the browser blocks the file, so update the hash with it.
wp-content/ mu-plugins/ sri.php
<?php /* * Plugin Name: Subresource Integrity */ const SRI_HASHES = array( // 'script-or-style-handle' => 'sha384-...', 'example-cdn-library' => 'sha384-PASTE_THE_HASH_HERE', ); add_filter( 'script_loader_tag', function ( $tag, $handle, $src ) { if ( isset( SRI_HASHES[ $handle ] ) ) { $tag = str_replace( ' src=', ' integrity="' . esc_attr( SRI_HASHES[ $handle ] ) . '" crossorigin="anonymous" src=', $tag ); } return $tag; }, 10, 3 ); add_filter( 'style_loader_tag', function ( $tag, $handle, $href, $media ) { if ( isset( SRI_HASHES[ $handle ] ) ) { $tag = str_replace( ' href=', ' integrity="' . esc_attr( SRI_HASHES[ $handle ] ) . '" crossorigin="anonymous" href=', $tag ); } return $tag; }, 10, 4 );
Related
Scan your domain to see whether this applies to you.