Subresource integrity, why you should be hashing your CDN scripts and using SRI
A description of a use case and benefits of Subresource Integrity and how to use it to secure CDN loaded resources from being tampered with.
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
<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.