Rails and Subresource Integrity
Using checksums for file verification
You might have had an opportunity to verify if a file you downloaded is valid and authentic compared to the original one - the process is called file verification. It is based on the fact that we can take the file content, process it with an algorithm, and generate a unique checksum based on the algorithm. We can then take such a checksum and verify it against our file. When we generate a different checksum, it means the downloaded file is invalid. It might have been corrupted while being transmitted over the internet or by third parties corrupting the original file. A common usage for checksum is, for instance, in the OpenSource world. Software creators usually want to make sure that people get the original file without any modifications to its content. On the other hand, it is often used for films that you can download from the web. All in all, checksums work fairly well - we do not have to compare files bit by bit in order to ensure a file matches the original one.
Checksum verification for web apps
File checksums verification can be used to ensure that original files arrive without any modifications to their content. In 2015, a similar idea was introduced into web applications. Since we usually load a lot of JS code into web pages, there is a possibility that some files will be modified by attackers, who may attempt to execute their own code. Such a case is sometimes very dangerous for web app users, for instance, those using apps for banking and money transfers. There has been an incident in which one person lost about 40.000 pln due to an ill-intentioned page modification. By ensuring that loaded scripts match original files one can help prevent such incidents.
The W3C organization considered the file checksums and decided to add the concept to their web specifications as Subresource Integrity. The latter works in the same way as verifying checksums and the process has the following steps:
- the author adds an integrity attribute to the script or link tag with the value of SHA384 or SHA512 for the file
- the browser verifies the checksum for the file
- the browser runs the file only when it matches the checksum
That is a pretty simple idea and it works well.
Subresource Integrity in Rails
Subresource Integrity is enabled from version 3.x in Rails Sprockets.
It is thus a great idea to use the 3.x version or at least upgrade the gem to this version. It will ensure that the files loaded in your app match exactly the files sent by the server or CDN.
Thanks to Wojtek for feedback!