Subresource Integrity (SRI)
While adding resources like jQuery / bootstrap, ever wondered what “ integrity” & “ crossorigin"
attributes are ?
Introduction
When adding libraries like jQuery and bootstrap from the cdn, you would have seen attributes integrity
and crossorigin
. Eg:
The integrity
and crossorigin
attributes are used for Subresource Integrity (SRI) checking. This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. Use of SRI is recommended as a best-practice, whenever libraries are loaded from a third-party source.
How it is different from using secure channel like HTTPS ?
Delivering resources over a secure channel mitigates some of this risk: with TLS, HSTS, and pinned public keys, a user agent can be fairly certain that it is indeed speaking with the server it believes it’s talking to. These mechanisms, however, authenticate only the server, not the content. An attacker (or administrator) with access to the server can manipulate content with impunity. SRI, on the other hand, guarantees that a resource hasn’t changed since it was hashed by a web author.
How to generate Integrity hashes ?
You can generate the Integrity hashes online at https://www.srihash.org/, OR using the following shell command :
openssl dgst -sha384 -binary FILENAME.js | openssl base64 -A
Using sha384 or sha512 or both ?
Multiple sets of integrity metadata may be associated with a single resource in order to provide agility in the face of future cryptographic discoveries. And the authors can use both :
<script src="hello_world.js"
integrity="sha384-dOTZf16X8p34q2/kYyEFm0jh89uTjikhnzjeLeF0FHsEaYKb1A1cv+Lyv4Hk8vHd
sha512-Q2bFTOhEALkN8hOms2FKTDLy7eugP2zFZ1T8LCvX42Fp3WoNr3bjZSAHeOsHrbV1Fu9/A0EzCinRE7Af1ofPrw=="
crossorigin="anonymous"></script>