DEV Community

Jyoti Prakash Pradhan
Jyoti Prakash Pradhan

Posted on

Script tag integrity attribute

We know that when a website is opened it loads the javascript file in the browser. Most of them are served from CDN servers.

Issue

Suppose one of the CDN server for that website is hacked and the hacker has added some malicious code in one of the JS file, then the client will be at risk of exposing sensitive information to the hacker.

So how to prevent this from happening ?
How browser will know that this JS file is a malicious or tampered one ?

Solution

To address this problem, most of the browsers have started supporting a new attribute in script tag called integrity attribute.

Example:

<script src="main.js" type="text/javascript" integrity="sha265-XU3HpWw3sNnYKqNWosvZyNN7HMyCOJGOrf1t5CLuuBc=" ></>
Enter fullscreen mode Exit fullscreen mode

There are two parts to the integrity attribute, first part is the algorithm (sha256 or sha384 etc.) and second part is the hash generated by the algorithm

integrity="{algorithm}-{hash}"

How to generate this hash ?

Basically this hash is not any random string, it is generated against the JS file. This hash is different for different JS files. The hash for the JS file can be generated by using the command below.

Command:
shasum -b -a 265 main.js | awk '{ print $1 }' | xxd -r -p | base64

The output of this command is appended to the integrity attribute in the script tag. It will generate a new hash every time the JS file is updated.

In real time development we do not have to generate the hash manually. Most of the modern bundlers like webpack or rollup, now a days are supporting generation of hash for JS files and append it to the related script tag.

How does the browser validate ?

When browser is done with downloading the JS file, it uses the same algorithm (sha256 or sha384) to generate the hash for the same file.
Now browser will compare between the hash generated by it and the hash present in the integrity attribute.
If the comparison fails, then browser will not allow that JS file to execute.

Script integrity attribute

This concept can be applied to any rest api, when we want to keep the integrity of the data between server and client.

Discussion (1)

Collapse
satarupadas profile image
Satarupa Das

Well explained