How to use SRI (Subresource integrtiy) attribute in script tag to prevent modification of static resources ?
Franklin Thaker
Posted on June 29, 2024
Understanding Supply Chain Attacks
Supply chain attacks involve compromising a third-party service or library to inject malicious code into websites that rely on it.
How Could This Be Prevented?
One effective way to mitigate such risks is by using the Subresource Integrity (SRI) attribute in your HTML scripts and link tags. SRI allows browsers to verify that the fetched resources (like scripts or stylesheets) are delivered without unexpected manipulation.
Demonstration
#script.js
console.log("Hello World - Secured!");
#index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script
src="script.js"
integrity="sha384-[YOUR-GENERATED-HASH]"
crossorigin="anonymous"
></script>
<title>SUBRESOURCE INTEGRITY EXAMPLE</title>
</head>
<body>
Hello World
</body>
</html>
#app.js - to serve above files
const express = require('express');
const app = express();
app.use(express.static("./"));
app.listen(80, () => {
console.log('Server is running on http://localhost');
});
Generating the Integrity Hash
openssl dgst -sha384 -binary script.js | openssl base64 -A
Now if we perform all the above steps correctly then the following working output should appear:
Now Let's try to modify script.js
#script.js - modified
console.log("Hello World - Modified!");
Now try to open http://localhost/index.html, you should see following error:
None of the sha384 hashes in the integrity attribute match the content of the resource.
SO THE MODIFIEFD SCRIPT WON'T RUN AT ALL!!
💖 💪 🙅 🚩
Franklin Thaker
Posted on June 29, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
cybersecurity How to use SRI (Subresource integrtiy) attribute in script tag to prevent modification of static resources ?
June 29, 2024