My CDN Was Compromised!

In this lesson, we'll look at some measures you can take to ensure your users' protection in the case of a CDN compromise.

Introduction

Often times, web applications serve some of their content through a content delivery network (CDN), typically in the form of static assets like JavaScript or CSS files, while the main document is rendered by a webserver. This gives developers limited control over the static assets themselves, as they’re usually uploaded to a third-party CDN (e.g., CloudFront, Google Cloud CDN, Akamai).

Now, suppose an attacker gained access to your login credentials on the CDN provider’s portal and uploaded a modified version of your static assets, injecting malicious code. How could you prevent such a risk for your users?

Using integrity hashes to protect users

Browser vendors have a solution for you, called sub-resource integrity (SRI). SRI allows your main application to generate cryptographic hashes of your static files and tell the browser which file is mapped to what hash. When the browser downloads the static asset from the CDN, it will calculate the asset’s hash on-the-fly and make sure that it matches the one provided in the main document. If the hashes don’t match, the browser will simply refuse to execute or render the asset.

This is how you can include an asset with an integrity hash in your document.

...
<script 
  src="https://my.cdn.com/asset.js" 
  integrity="sha256-Y34u3VVVcO2pZtmdTnfZ+7OquEpJj/VawhuWPB4Fwq3ftcFc0gceft1HNZ14eUHT"
></script>
...

The integrity hash can be computed with a simple command.

cat $ASSET_FILE_NAME | openssl dgst -sha384 -binary | openssl base64 -A

A working example can be found below; after you’ve ran the web server by clicking the run button, you can visit https://x6jr4kg.educative.run by replacing the educative.run link with the one generated in your app below to see the SRI in action.

Get hands-on with 1200+ tech skills courses.