Imagine a scenario where thousands of websites embed the same external javascript file from a CDN, what would be easiest way for an attacker to compromise all of those websites? Attacking the CDN itself, gaining control of the CDN and injecting malicious code into the resource will compromise all of the websites using that resource without having to hack into them individually. Every single website loading that specific javascript file from the CDN is now embedding a tampered with and potentially malicious file.

The above scenario is exactly what happened a couple of months ago when a popular script which helps websites assist visually impaired users was compromised. In this instance the attacker was able to inject cryptomining code into the script which was embedded across 1000s of domains including UK government websites. Any visitor to the infected website was helping mine a crypto currency for the attacker via the browser without even knowing it.

The worst part of the above situation is that it could of been avoided by utilising Subresource Integrity. SRI is a method of checking a file that is to be loaded against a cryptographic hash that you would generate from the original unmodified version, if the file has changed then the hash will be different from the original and your browser will stop the file from being loaded.

If the file doesn't match the expected hash then you will see an output similiar to this in your browsers console window "None of the "sha384" hashes in the integrity attribute match the content of the subresource.", completely nullifying the tampered file from being loaded.

Setting up SRI

Below is an example of how a javascript file loaded from a CDN will look with an SRI hash.

<script async src="/link/to/cdn/resource" integrity="sha384-paYjEtNXu9X/q6SBQB9EivI88vKEc/TiZWUaaH5j2Hi4vAOnVYmcahbzUELr3LHw" crossorigin="anonymous"></script>

What about hash collision attacks?

At the time of this post, there have been no known collision attacks against sha256, sha384 or sha512 so you should be able to confidently use this and know that the resource you're loading hasn't been tampered with.

You can generate the hashes yourself if you have access to OpenSSL or you can use an online tool here, the W3C specification for SRI can be found here.