Implementing Sub-resource Integrity

2 May 2020 - Articles
Back

Hosting web application content such as dynamic scripts and stylesheets on third parties such as Content Delivery Networks (CDNs) can allow for significant improvements to site performance and can reduce bandwidth costs. However, scripts included within a web application will execute within the user’s browser with the same privileges as the currently logged in user. Therefore if a script is included from an external domain, that domain is trusted with the confidentiality and integrity of data stored within the application.

If the third party is used to host scripting content and is compromised and the script can be modified, then it could perform significant malicious actions such as stealing confidential data, compromising user accounts, or distributing malicious software. The impact of a successful attack of this nature has previously been demonstrated through the “Magecart” attacks.

This can be prevented through Sub-resource Integrity (SRI). SRI can be used to detect if a script or stylesheet has been changed and configure the browser to refuse to execute the script, or include the stylesheet, if a potential compromise has occurred.

Script content should not be included from third-party domains without integrity checking.

Integrity checking can be applied by adding an “integrity” attribute to the script element. The integrity attribute should contain a hash of the script contents. This can be a SHA-256, SHA-384 or SHA-512 hash. For example:

<script src="https://example.com/script.js" integrity="sha384-85fHxv7OLr/hnQ+IFlwKssV/ojArzbPMhLII+LOhQaf8JyvARUclKzfLVI1Q3Gwt" crossorigin="anonymous"></script>

The script must have CORS enabled and the crossorigin attribute must be set. Without the crossorigin attribute the browser will load the resource without integrity checking. If CORS is not enabled, or the CORS request is denied (for example if the Access-Control-Allow-Origin header is not set), the resource will not be included.

To simplify the process of generating a hash of your resources, the following tool is available: https://www.srihash.org/.

That’s it!

Play Cover Track Title
Track Authors