Description
Loading an external script or stylesheet without comparing it with a trusted hash can allow altered content to run when its host is compromised. Subresource Integrity (SRI) checks the file contents against a specified hash on supported script and link elements. A matching hash does not mean the file itself is safe.
Potential impact
- A modified external resource may introduce malicious code into the page.
Remediation
- Set
integrityto a hash calculated from the trusted file for external scripts and stylesheets that support SRI. Update the hash when the file changes. - Cross-origin resources also need a
crossoriginsetting and an appropriate CORS response from the resource server.
Examples
Before
html
<script src="https://example.com/script.js"></script>
After
The URL and hash illustrate the format. Replace the hash with one calculated from the actual file you deploy.
html
<script
src="https://example.com/script.js"
integrity="sha384-OgVRvuATPupdUSgWVsKllsZZAgvFiTpjlPdSdj0eGVcI/A5efowlBbInEKwdsA5l"
crossorigin="anonymous"
></script>
Explanation:
- Before: The external script is loaded without checking an expected content hash.
- After: A supporting browser blocks execution if the file's hash differs. Copying the example URL and hash does not verify your actual resource.