I'm reading about Subsource Integrity on Mozilla [1]. They analyse the code snippet below and write the following about it:
The anonymous value means that the browser should omit any cookies or authentication that the user may have associated with the domain. This prevents cross-origin data leaks, and also makes the request smaller.
<script src="https://code.jquery.com/jquery-2.1.4.min.js"
integrity="sha384-R4/ztc4ZlRqWjqIuvf6RX5yb/v90qNGx6fS48N0tRxiGkqveZETq72KgDVJCp2TC"
crossorigin="anonymous"></script>
I'm interested in why this prevents cross-origin data leaks [2]. Mozilla writes the following:
Attackers would attempt to load the resource with a known digest, and watch for load failures. If the load fails, the attacker could surmise that the response didn’t match the hash and thereby gain some insight into its contents. This might reveal, for example, whether or not a user is logged into a particular service.
I understand how the integrity attribute can be used to reveal the contents of the resource. This seems interesting if the contents are client-dependent. However, I do not understand two things:
responseText to a malicious website straight away?crossorigin to anonymous so that hackers can not "bruteforce" page info by brute-forcing hashes? If the hackers can control the integrity attribute on the page, they can control the crossorigin attribute too in most cases, so why does this matter?The situation you describe is different from what the authors of that documentation had in mind. The attacker may not be interested in the exact content of the response to an authenticated request triggered by a subresource load; instead, the attacker may simply want to determine, from a malicious origin, whether the victim is logged in to the target.
Imagine a case where the response to GETting https://example.com/1.js depends on whether the request carries some authentication cookie (marked SameSite=None; Secure here, for simplicity):
alert('authenticated');
or
alert('anonymous');
The SHA-256 of alert('anonymous'); (followed by a newline) is a7c873e2f388c05f57d1245cfa0c20e4bf5b064677ba4f959c5dd53668590339. The attacker could set up the following malicious page, which would function as a login oracle:
<script integrity="sha256-a7c873e2f388c05f57d1245cfa0c20e4bf5b064677ba4f959c5dd53668590339"
src="https://example.com/1.js"
crossorigin="use-credentials"
onerror="notifyAttackerVisitorIsLoggedInToExampleDotCom();">
When the victim visits the attacker's malicious page, two cases are possible:
https://example.com, the response to the subresource load contains alert('anonymous');, whose hash value matches the one specified in the attacker's integrity attribute. No error occurs.https://example.com, the response to the subresource load contains alert('authenticated');, whose hash value doesn't match the one specified in the attacker's integrity attribute. Therefore, an error occurs and the onerror event listener fires, notifying the attacker.