Use SRI hashes to secure CDNs
When you include sources from third-parties, you lose control of the contents. If the CDN is compromised and sends malicious content, your site will be compromised too.
This is where SRI (Subresource Integrity), an emerging security standard, can help. If you define a hash as part of a script
or link
tag and the CDN sends unmatching content, the browser refuses to load the resource.
This way your site might be down but is not compromised.
Instead of using a script
tag with only the src
set:
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
define also the integrity
attribute:
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js" integrity="sha256-8E6QUcFg1KTnpEU8TFGhpTGHw5fJqB9vCms3OhAYLqw=" crossorigin="anonymous"></script>
Generate the hash
Use srihash.org, input the URL, and use the script tag.
Some CDNs also offer to copy the script tag with SRI. For example, when using cdnjs.org, use Copy Script Tag with SRI
.
If the files are not public, use openssl dgst -sha384 -binary FILENAME.js | openssl base64 -A
from the command line.
Browser support
The standard is supported by all major browsers. It is also backwards-compatible, so that older ones just ignore the attribute and load the resource.