DEV Community

Cover image for How to use SRI (Subresource integrtiy) attribute in script tag to prevent modification of static resources ?
Franklin Thaker
Franklin Thaker

Posted on

How to use SRI (Subresource integrtiy) attribute in script tag to prevent modification of static resources ?

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!");
Enter fullscreen mode Exit fullscreen mode
#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>
Enter fullscreen mode Exit fullscreen mode
#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');
});
Enter fullscreen mode Exit fullscreen mode

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:

WORKING OUTPUT IF ABOVE STEPS PERFORM CORRECTLY

Now Let's try to modify script.js

#script.js - modified
console.log("Hello World - Modified!");
Enter fullscreen mode Exit fullscreen mode

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!!

SCRIPT WON'T RUN AFTER MODIFICATION

Top comments (0)