Link Search Menu Expand Document

Subresource Integrity

  1. Subresource Integrity
    1. Description
    2. Impact
    3. Prevention
    4. Testing
    5. References

Description

It is common to fetch JavaScript and style sheet libraries from third-party providers as it offers a variety of advantages, not least of which is the ability to leverage someone else’s hosting infrastructure. But this also extends the overall attack surface, in that if the abovementioned provider is compromised, an attacker might inject malicious code into the hosted libraries, thus transforming a single-entity compromise into a massive supply-chain catastrophe, impacting every web application reliant on the tainted libraries in question.

<script src="http://some-cdn.com/some-library.js"></script>

However, this scenario is not a novel concept. Over the years, awareness has fortunately morphed into best-practice doctrine, which in this case emerges from the World Wide Web Consortium (W3C) and is referred to as the Subresource Integrity (SRI) recommendation. This mechanism allows browsers to verify the integrity of an external resource, refusing to evaluate the resource if the check fails.

Impact

Let’s say a third-party provider like a Content Delivery Network (CDN) is compromised. Not checking the SRI could result in an attacker executing arbitrary code on the context of the web application with the impact only limited to what the web application can legitimately do. Indeed, Magecart, one of the most prolific cyber-criminal consortiums of all time, takes advantage of, amongst other flaws, a lack of SRI-implementation in many of their hacks.

Prevention

To enforce SRI, adding two elements to the <script> element is sufficient:

  • integrity a sha384 digest of the content of the external resource;

  • crossOrigin an attribute that must be set to anonymous, indicating that the resource resides on a different origin and that the browser must not send any credentials (cookies) when fetching it.

For example, the above becomes:

<script src="http://some-cdn.com/some-library.js"
        integrity="sha384-+54fLHoW8AHu3nHtUxs9fW2XKOZ2ZwKHB5olRtKSDTKJIb1Na1EceFZMS8E72mzW"
        crossOrigin="anonymous"></script>

Testing

Verify that if application assets, such as JavaScript libraries, CSS or web fonts, are hosted externally on a Content Delivery Network (CDN) or external provider, Subresource Integrity (SRI) is used to validate the integrity of the asset.

References

MDN - Subresource Integrity

SRI Hash Generator