Skip to content
Info disclosure Write-up Advanced

Exploiting CSP in Webkit to Break Authentication & Authorization

WebKit failed to follow the W3C specification for CSP violation events, leaking the final redirect URI in the documentURI attribute. An attacker could steal OAuth authorization codes or tokens from cross-origin redirects, leading to account takeovers.

Sachin Thakuri Follow

Published on threatnix.io

Bounty$100,000 View original

When it comes to the web, browsers are the first line of defence. While built-in security features that come compiled with browsers are responsible for preventing a wide array of attacks, any seemingly trivial mistake in browsers' implementation can have devastating effects.

Guest, on threatnix.io

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.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 12 min read.

Context

WebKit is the browser engine behind Safari, and on iOS every browser, including Chrome, Firefox and Opera, must use WebKit as its core engine because of Apple's App Store rules. The research here concerns the Content Security Policy (CSP) implementation of WebKit: specifically, what a SecurityPolicyViolationEvent reports when a request is redirected from one origin to another.

CSP is a set of rules, delivered through the Content-Security-Policy HTTP response header or a <meta> tag (with exclusions such as report-uri and frame-ancestors), that tells the browser which resources it may load and execute. When a page tries to load a resource that the policy forbids, the browser blocks the request and dispatches a violation report. There are four ways to catch that report:

  1. the report-uri directive
  2. the report-to directive
  3. the ReportingObserver API
  4. the SecurityPolicyViolationEvent

The authors use SecurityPolicyViolationEvent throughout. The event carries fields such as violated-directive, original-policy and blockedURI, and the specification says the report should contain only the origin of the original request, not the redirect target, precisely so that sensitive URLs are not leaked.

The feature that turns this into an authentication problem is Single Sign-On (SSO). SSO provides a centralised authentication service: the user authenticates once against a central domain, and other applications trust that authentication. The authentication token is passed between the applications, and in many OAuth and SSO flows the final step is a cross-origin redirect from the SSO domain back to the application, with a code or token appended to the URL.

From the original on threatnix.io

Setup

The exploit was simple: a page with a CSP policy, an event listener for SecurityPolicyViolation, and a request. The policy whitelists the domain the page sends its request to, and the listener catches SecurityPolicyViolationEvent. The authors also published a playground at https://cm2.pw/csp-playground (source at https://github.com/threatnix/csp-playground): it takes parameters from the query string, sets the CSP policy using the domain from that string, and offers an Exploit button as a workaround for Intelligent Tracking Prevention (ITP). After a short wait it issues a fetch to the URL in the query string, which redirects to another domain and causes a violation; the listener then prints the leaked token on screen.

ITP is a WebKit privacy feature in use since October 2017 that uses a machine learning model to detect cross-site tracking and reduce it through measures such as full third-party cookie blocking, reducing the accessibility and longevity of first-party cookies, LocalStorage capping and deletion, and downgrading third-party referrers. Because the attack relies on third-party requests, ITP made it unusable on the latest WebKit versions. WebKit's documentation says the way around it is a user interaction (a tap, a click or keyboard use) with the attacker's site as first party, so in a real attack the authors open a tab with window.open and keep polling the vulnerable endpoint until the user interacts with it.

Finding it

The starting point is the violation report itself. In the example the authors show, the report discloses the URL the user tried to load, evil.com. That is not sensitive on its own, but it becomes sensitive when the blocked URL is the result of a redirect, as in OAuth. To avoid leaking sensitive information, browsers are supposed to include only the origin of the original request.

From the original on threatnix.io

The history here matters. The CSP1.0 Candidate Recommendation got this wrong and recommended including the origin of the blocked URI, which is still an issue and has a long history of reports.

From the original on threatnix.io

The authors found a few disclosed reports on Chromium's issue tracker that leaked the origin of blocked-uri through CSP in one way or another; all share the same problem, leakage of a cross-origin redirect URL. One was published in 2013, when CSP was still in its infancy, by Egor Homakov, who demonstrated what could be achieved by abusing CSP's blocked-uri directive and wrote that CSP could be used to detect whether a user had authorised certain apps or clients, because authorised apps redirect to their homepage instead of the login or authorisation page. For example, if Instagram had already been authorised on a user's Facebook, a request to the Facebook OAuth endpoint for Instagram would redirect to Instagram instead of Facebook. CSP was subsequently changed to recommend including the URL of the original request instead of the redirected URL.

Exploitation

Step 1: define a policy that turns a cross-origin redirect into a violation

The policy is written so that whenever a redirect goes to a domain with a different origin, a CSP violation occurs and a SecurityPolicyViolationEvent fires. In the authors' example, their domain cm2.pw carries such a policy and makes a fetch request to domain-1.com. The response from domain-1.com contains a Location header redirecting to a different origin, domain-2.com. The policy blocks the request to domain-2.com and the violation event fires.

From the original on threatnix.io

Step 2: read the leaked redirect target from documentURI

When the event fires, the SecurityPolicyViolationEvent interface is used at the target with different attributes. While setting those attribute values, WebKit failed to adhere to the W3C specification and leaked the 30x redirection location in the documentURI attribute.

From the original on threatnix.io

The figure shows fb.com/secret-here redirecting to facebook.com/secret-here, and the difference between the values Safari and other browsers set for documentURI. Browsers that follow the W3C specification set the value to the URI from which the original fetch request was made; Safari set it to the final redirection URI.

Step 3: apply it to an SSO flow

When a user loads example.com, the site first checks whether the user is authenticated. If not, the user is sent to auth.example.com, the SSO domain that provides centralised authentication. After verifying the user, the SSO domain redirects back to example.com with an authentication token. The common practice is to implement SSO on a different subdomain or an entirely different domain, which does not meet the same-origin criteria, so the final redirect from auth.example.com to example.com is cross-origin and the attacker can steal the final redirection URI.

From the original on threatnix.io

Step 4: run the proof of concept

The exploit is simple: set up a page with the CSP shown above, whitelisting the domain the requests are sent to, add an event listener for SecurityPolicyViolation, and send the request. A request to an authorisation endpoint issues a redirect to another domain with the code or token appended to the URL, which is typical for OAuth or SSO, while the policy only allows loading resources from the page itself and from auth.example.com. Any attempt to load from another domain violates the policy and triggers the event. The documentURI then holds the actual blocked URL, not just its origin.

From the original on threatnix.io

Root cause

The defect is in WebKit's handling of the SecurityPolicyViolationEvent attributes. The specification requires the report to carry the URL of the original request, so that a redirect target is not disclosed. WebKit instead populated documentURI with the final redirection URI. The specification requires the report to carry the URL of the original request, and WebKit instead populated documentURI with the final redirection URI.

Impact

The vulnerability was not limited to Safari. Apple's App Store policies state that apps that browse the web must use the iOS WebKit framework and WebKit JavaScript, so browsers cannot ship their own rendering engines and must embed a version of Safari's engine; Firefox, Chrome and Opera on iOS were therefore affected too.

Because of the design of OAuth, almost every OAuth implementation that existed was vulnerable. The authors could take over Facebook, Instagram and WhatsApp accounts. Google's SSO was affected, so Google products relying on the central Google account authentication were vulnerable too, as were crypto-currency, social networking and e-commerce platforms. Applications offering "Login with <third-party>" features, such as Login with Facebook or Google, were affected as well: an e-commerce site with a Login with Facebook feature allowed an attacker to take over its users' accounts by stealing Facebook's OAuth tokens. Different SSO providers were affected for the same reason.

In total the authors harvested more than $100k in bounties. The highest single reward came from Coinbase. Coinbase was also the fastest program to fix the issue. Some programs fixed it in under 21 hours; others took months just to understand it, and some relied on WebKit for a fix. DropBox and Poloniex went further and used their contacts at Apple to ask for a fix. Apple took a total of 457 days to come up with a fix and then decided the bug did not qualify for a bounty because it did not meet the published bounty categories. Apple's own SSO and OAuth implementation was not vulnerable.

Responsible disclosure

The first report went to Safari in February 2020. An automatic acknowledgement arrived on March 16, 2020, after a ping on March 12. A reply came on April 20, 2020, saying the issue did not seem to pose a threat to WebKit users, and explaining that even after a fix an attacker could gather the same information by monitoring WebKit logs while running an attacker-controlled build of WebKit.

From the original on threatnix.io

In January 2021, after waiting almost a year, the authors started targeting bug bounty programs. Apple patched the vulnerability and shipped new WebKit versions on May 24, 2021. The two issues were assigned CVE-2021-30682 and CVE-2021-30888.

Roadblocks

Security teams at several programs shared misunderstandings. One concerned the authorisation code: some believed that without the ability to exchange it for an access token it was useless, since the exchange requires client_id and client_secret. That is true, but where OAuth is used for authentication, access to the authorisation code alone is enough to reach the victim's account: a request to the authorisation endpoint with the stolen code and an attacker-generated state or nonce value authenticates the attacker into the victim's account.

Another concerned the state or nonce value. State is an excellent way to prevent CSRF in OAuth and to send users back to where they were before authentication, but beyond that it provides no additional security. Even if the state is bound to a token, an attacker can generate a fresh state value and attach it to an OAuth endpoint URL sent to the victim; the resulting token can then be used without any issue. The authors' demo showed the nonce or state value doing nothing to prevent the attack.

Fixes

The authors list the following measures for developers and site owners, usable alone or in combination.

  • Use POST instead of GET. This aligns with never sending sensitive information in a URL; SAML already uses POST instead of GET for transporting tokens.
  • Use postMessage. This uses HTML5 postMessage for cross-domain communication.
From the original on threatnix.io

Both are supported by OAuth and OpenID Connect and can be selected through response_mode as long as the authorisation server supports it, but support for query and fragment modes still has to be disabled or removed.

  • Use SameSite cookies. They protect against this vulnerability and make almost all client-side vulnerabilities infeasible; they protected several programs in the authors' campaign.
  • For OAuth, use PKCE for defence in depth. It makes the exploit largely useless because the code_verifier is also needed to use the leaked code.
  • Ask for manual authorisation each time a user logs in. This prompts every time even if the user is already authorised; OpenID supports it through the prompt parameter, and Apple does exactly this.
  • Use client-side redirects (or JavaScript) instead of 30x. This can be combined with X-Frame-Options or CSP's frame-ancestors; Twitter uses this method.
  • Validate referrer/origin against the client (client_id, redirect_uri). Not recommended, because it suffers from the same issues as CSRF protection based on referrer/origin.

Browsers also have mitigations beyond the Same Origin Policy, though these are specific to CSP and do not cover the second issue described below:

  1. Violation reports include only the URL of the original request, not the redirect target, so the attacker only gets what they already know.
  2. Browsers ignore the path component of a source expression if the resource being loaded is the result of a redirect, to prevent leaking path information as demonstrated in Homakov's post.

Bypasses and a new 0day

After the reports, several programs, including Facebook and Coinbase, fixed the issue by checking whether the User-Agent is Safari and using a different approach only in that case; for all other user-agents the workflow stayed the same. Changing the User-Agent therefore seemed an obvious bypass, and an obvious place to try it was on iPhone and iPad, where every browser uses WebKit. Using Chrome did not work, but switching to "Desktop Site" did. The User-Agent change was not inherited by subsequent fetch requests, so the authors tried every request from Cure53's HTTPLeaks project and found that <a ping> (an anchor with the ping attribute) did the job.

While hunting for bypasses they found another 0day, this time in Cross-Origin-Resource-Sharing (CORS) rather than CSP. The finding was as easy as adding a catch handler to the fetch request, which disclosed the destination URL.

From the original on threatnix.io

They shared their plan to disclose the vulnerability with Apple, and it was fixed right before their talk without them being notified.

Variants to test

  • Cross-origin redirect behind a CSP-protected fetch. On any engine, set a policy that allows only the first-party origin and the redirecting domain, then fetch an endpoint that 30x-redirects to a different origin. A positive result is a SecurityPolicyViolationEvent whose documentURI contains the full redirect target, including path and query, rather than the original request URL.
  • SSO and OAuth callback endpoints. Point the same page at an authorisation endpoint that redirects back to the application with a code or token in the URL. A positive result is the code or token appearing in documentURI.
  • User-Agent based fixes. Where a program's fix keys on the Safari User-Agent, try the same request from an iOS browser in "Desktop Site" mode, and try <a ping> for requests whose User-Agent change is not inherited by fetch. A positive result is the leak reappearing.
  • CORS error handling. Add a catch handler to a cross-origin fetch and inspect the error. A positive result is the destination URL being disclosed in the error.
  • Other report channels. Repeat the redirect test against report-uri, report-to and ReportingObserver rather than the event, to see whether any channel carries the redirect target.

Key takeaways

  1. SameSite cookies can be very helpful.
  2. Use defence in depth to mitigate browser flaws.
  3. Browsers do not always follow the spec completely.

Timeline

Date Event
Feb 21, 2020 Initial report sent to Safari
Mar 12, 2020 Sent a ping
Mar 16, 2020 Automatic acknowledgement received
Apr 20, 2020 Apple replied that the vulnerability does not pose a threat
Jan 12, 2021 Started targeting other bug bounty programs
May 24, 2021 Apple patched the vulnerability and shipped new WebKit versions

A recording of the talk as presented at GreHack 2021 is available.

Or watch on YouTube
From the original on threatnix.io

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 21 min read.

What happened, in plain words

Every website you visit is displayed by a program called a browser: Safari, Chrome, Firefox, Edge. Inside the browser there is a second, less visible program called a browser engine. The engine is the part that reads the HTML, CSS and JavaScript a website sends and turns it into the page you see. Most browsers share one engine, but Safari has its own, called WebKit. On an iPhone or iPad, every browser must use WebKit, even Chrome and Firefox, because Apple's App Store rules say so.

Browsers have safety rules built in. One of those rules is called Content Security Policy, or CSP. It is a list of instructions a website gives the browser: "you may load scripts from this address, images from that address, and nothing else". When the browser refuses to load something because of those instructions, it raises a small internal alarm called a violation event. That alarm carries a description of what was blocked.

The researchers found that WebKit failed to adhere to the W3C specification when filling in that description. When a request was redirected from one website to another, WebKit wrote the final address into the alarm, where the rules say it should only write the starting address. That final address can contain a secret: a login code, a token, something that proves who you are. Anyone who can read the alarm can read the secret.

The secret matters because of Single Sign-On, or SSO: the "Log in with Google" or "Log in with Facebook" button you have seen on many sites. In SSO, you log in once at a central service, and that service sends you back to the site you came from with a short-lived code in the address bar. If an attacker can read that code, they can log in as you. The researchers could use this to take over accounts on many large services, and they harvested more than $100,000 in bug bounties.

This article walks through the whole story in the order the researchers told it: what SSO and CSP are, how the leak was found, how it was exploited, what the impact was, how Apple responded, what developers can do about it, and what happened next.

Background: the pieces involved

WebKit and why it matters

WebKit is the engine behind Safari. Because of Apple's App Store policies, apps that browse the web on iOS must use the iOS WebKit framework and WebKit JavaScript. A browser maker cannot ship its own engine on an iPhone. So a bug in WebKit is not a bug in one browser; it is a bug in every browser on every iPhone and iPad. The researchers point out that Safari has roughly 19% of the world's browser market share, which gives an idea of how many people a WebKit flaw can reach.

Single Sign-On (SSO)

From the original on threatnix.io

SSO is a centralised login service. Instead of creating a separate password on every website, you log in once to a central service, and other applications trust that service's word that you are who you say you are. It is convenient, and it is generally considered more secure than letting every site store its own passwords.

How does the trust travel from the central service to the application? Through an authentication token: a short string of characters that acts like a temporary pass. The application receives the token, checks it, and lets you in. Because the token is your proof of identity, keeping it safe is the whole game. If someone else gets your token, they are you, as far as the application is concerned.

A useful comparison: think of a hotel. You check in once at reception (the SSO service) and receive a key card (the token). Your room door (the application) does not check your passport; it only checks that the key card is valid. Copy the key card and you can open the door.

Content Security Policy (CSP)

From the original on threatnix.io

CSP is a set of rules that tells the browser what a page is allowed to load and run: JavaScript, CSS, images, and so on. It is delivered in one of two ways: as an HTTP response header called Content-Security-Policy, or as a <meta> tag inside the page. A few directives cannot be used in the <meta> form, for example report-uri and frame-ancestors.

An HTTP response header is a small piece of text the web server sends along with the page, before the page content. You never see it in the browser window, but it tells the browser how to behave. A <meta> tag is an instruction written inside the HTML of the page itself.

CSP has existed since 2010 and is supported by all modern browsers. It is widely used, but writing a correct policy is hard, because the right rules depend on exactly which resources each page needs. That is probably why there is no such thing as a default policy that suits everyone.

CSP violation reports

Mistakes in a CSP policy are common, so browsers offer a second header, Content-Security-Policy-Report-Only. With this one, the policy is not enforced: nothing is blocked, but violations are reported. That lets a site owner test a policy without breaking the site.

When a policy is enforced and a page tries to load something forbidden, the browser blocks the request and dispatches a violation report. There are four ways to catch that report:

  1. the report-uri directive
  2. the report-to directive
  3. the ReportingObserver API
  4. the SecurityPolicyViolationEvent

An API (Application Programming Interface) is a defined way for one piece of software to talk to another. Here, ReportingObserver is a feature the browser exposes to JavaScript so a page can subscribe to reports.

The researchers use SecurityPolicyViolationEvent throughout the article for easier understanding. It is a JavaScript event: something the browser announces, which page code can listen for, the same way a button can listen for a click. The event carries fields describing the violation, such as violated-directive (which rule was broken), original-policy (the policy text) and blockedURI (the address that was blocked).

From the original on threatnix.io

In the example shown, the report discloses the URL the user tried to load, evil.com. That is not sensitive by itself. It becomes sensitive when the blocked URL is the result of a redirect, as happens in OAuth. To avoid leaking secrets, browsers are supposed to include only the origin of the original request.

An origin is the combination of protocol, host and port: roughly, https://example.com. It is the browser's unit of trust. Two pages with the same origin may read each other's data; two pages with different origins may not. A full URL, by contrast, includes the path and the query string, and that is where secrets often sit.

A short history of the leak

The CSP1.0 Candidate Recommendation got this wrong: it recommended including the origin of the blocked URI, which is still an issue and has a long history of reports.

From the original on threatnix.io

The researchers found a few disclosed reports on Chromium's issues that leaked the origin of blocked-uri through CSP in one way or another. All of them share the same problem: leakage of a cross-origin redirect URL. One was published in 2013, when CSP was still in its infancy, by Egor Homakov. He demonstrated what could be achieved by abusing CSP's blocked-uri directive, and wrote that CSP could be used to detect whether a user had authorised certain apps or clients, because authorised apps redirect to their homepage instead of the login or authorisation page. For example, if Instagram had already been authorised on a user's Facebook account, a request to the Facebook OAuth endpoint for Instagram would redirect to Instagram instead of Facebook. CSP was subsequently changed to recommend including the URL of the original request instead of the redirected URL.

How the vulnerability works

Step 1: a policy that turns a redirect into a violation

From the original on threatnix.io

The policy is written so that whenever a redirect goes to a domain with a different origin, a CSP violation occurs and a SecurityPolicyViolationEvent fires. In the researchers' example, their own domain cm2.pw carries such a policy and makes a fetch request to domain-1.com. The response from domain-1.com contains a Location header redirecting to a different origin, domain-2.com. The policy blocks the request to domain-2.com, and the violation event fires.

A fetch request is JavaScript asking the browser to go and get something from a network address, without navigating the page there. A redirect is a server's way of saying "not here, go there instead": it answers with a Location header naming the new address, and the browser follows it automatically. A 30x status code is the family of HTTP responses that mean a redirect (301, 302 and so on).

Why does the policy block the second hop? Because the policy only allows loading from the page's own origin and from domain-1.com. domain-2.com is neither, so the browser refuses, and refusing is exactly what produces the alarm.

Step 2: reading the leaked address from documentURI

When the event fires, the SecurityPolicyViolationEvent interface is used at the target with different attributes. While setting those attribute values, WebKit failed to adhere to the W3C specification and leaked the 30x redirection location in the documentURI attribute.

From the original on threatnix.io

The W3C is the standards body that writes the specifications browsers are supposed to follow. documentURI is one of the event's attributes: it is meant to say which document the violation happened in. The figure shows fb.com/secret-here redirecting to facebook.com/secret-here, and the difference between the values Safari and other browsers set for documentURI. Browsers that follow the specification set the value to the URI from which the original fetch request was made. Safari set it to the final redirection URI.

That single wrong value is the whole bug. The browser was trying to protect the secret by reporting only the starting point, and instead it reported the destination, secret included.

Step 3: applying it to an SSO flow

From the original on threatnix.io

When a user loads example.com, the site first checks whether the user is authenticated. If not, the user is sent to auth.example.com, the SSO domain that provides centralised authentication. After verifying the user, the SSO domain redirects back to example.com with an authentication token. The common practice is to implement SSO on a different subdomain, or on an entirely different domain, which does not meet the same-origin criteria. So the final redirect from auth.example.com to example.com is cross-origin, and the attacker can steal the final redirection URI.

Why does the subdomain matter? Because auth.example.com and example.com are different origins. The browser treats them as separate trust domains, which is what makes the redirect cross-origin, which is what makes the CSP policy block it, which is what fires the event carrying the secret.

Step 4: running the proof of concept

From the original on threatnix.io

The exploit is simple: set up a page with the CSP shown above, whitelisting the domain the requests are sent to, add an event listener for SecurityPolicyViolation, and send the request. A request to an authorisation endpoint issues a redirect to another domain with the code or token appended to the URL, which is typical for OAuth or SSO, while the policy only allows loading resources from the page itself and from auth.example.com. Any attempt to load from another domain violates the policy and triggers the event. The documentURI then holds the actual blocked URL, not just its origin.

An event listener is a piece of JavaScript that says "when this event happens, run this function". Here it is the function that reads documentURI and prints whatever it finds. An authorisation endpoint is a specific address on the SSO service that handles the login-and-redirect step. OAuth is the open standard behind most "Log in with..." buttons; SSO implementations commonly use it.

Root cause

The defect is in WebKit's handling of the SecurityPolicyViolationEvent attributes. The specification requires the report to carry the URL of the original request, so that a redirect target is not disclosed. WebKit instead populated documentURI with the final redirection URI. The existing defence, the specification change made after Homakov's work, only helps if the engine implements it, and WebKit did not.

Impact

The vulnerability was not limited to Safari. Apple's App Store policies state that apps that browse the web must use the iOS WebKit framework and WebKit JavaScript, so browsers cannot ship their own rendering engines and must embed a version of Safari's engine. Firefox, Chrome and Opera on iOS were therefore affected too.

Because of the design of OAuth, almost every OAuth implementation that existed was vulnerable. The researchers could take over Facebook, Instagram and WhatsApp accounts. Google's SSO was affected, so Google products relying on the central Google account authentication were vulnerable too, as were crypto-currency, social networking and e-commerce platforms. Applications offering "Login with <third-party>" features, such as Login with Facebook or Google, were affected as well: an e-commerce site with a Login with Facebook feature allowed an attacker to take over its users' accounts by stealing Facebook's OAuth tokens. Different SSO providers were affected for the same reason.

In total the researchers harvested more than $100k in bounties. A bug bounty is a program in which a company pays security researchers for reporting flaws responsibly instead of exploiting them. The highest single reward came from Coinbase. Coinbase was also the fastest program to fix the issue. Some programs fixed it in under 21 hours; others took months just to understand it, and some relied on WebKit for a fix. DropBox and Poloniex went further and used their contacts at Apple to ask for a fix. Apple took a total of 457 days to come up with a fix and then decided the bug did not qualify for a bounty because it did not meet the published bounty categories. Apple's own SSO and OAuth implementation was not vulnerable.

Responsible disclosure

The first report went to Safari in February 2020. An automatic acknowledgement arrived on March 16, 2020, after a ping on March 12. A reply came on April 20, 2020, saying the issue did not seem to pose a threat to WebKit users, and explaining that even after a fix an attacker could gather the same information by monitoring WebKit logs while running an attacker-controlled build of WebKit.

From the original on threatnix.io

Responsible disclosure is the practice of telling the vendor privately first, giving them time to fix the problem before it becomes public. In January 2021, after almost a year, the researchers started targeting bug bounty programs. Apple patched the vulnerability and shipped new WebKit versions on May 24, 2021. The two issues were assigned CVE-2021-30682 and CVE-2021-30888.

A CVE is a public catalogue number for a known vulnerability, so that people can refer to the same flaw unambiguously.

Roadblocks

Security teams at several programs shared misunderstandings. One concerned the authorisation code: some believed that without the ability to exchange it for an access token it was useless, since the exchange requires client_id and client_secret. That is true, but where OAuth is used for authentication, access to the authorisation code alone is enough to reach the victim's account: a request to the authorisation endpoint with the stolen code and an attacker-generated state or nonce value authenticates the attacker into the victim's account.

An authorisation code is a short-lived string the SSO service hands back to the application. Normally the application swaps it for an access token, and that swap requires the application's own credentials, client_id and client_secret. The misunderstanding was to think the code is therefore harmless on its own. It is not, when the code is used to prove who you are rather than to call an API.

Another concerned the state or nonce value. State is an excellent way to prevent CSRF in OAuth and to send users back to where they were before authentication, but beyond that it provides no additional security. Even if the state is bound to a token, an attacker can generate a fresh state value and attach it to an OAuth endpoint URL sent to the victim; the resulting token can then be used without any issue. The researchers' demo showed the nonce or state value doing nothing to prevent the attack.

CSRF, or Cross-Site Request Forgery, is an attack where a malicious page makes your browser send a request you did not intend. The state parameter exists to stop that, by making each login attempt carry a value the attacker cannot guess. It does not stop someone from reading a code that was already issued.

Fixes

The researchers list the following measures for developers and site owners, usable alone or in combination.

  • Use POST instead of GET. This aligns with never sending sensitive information in a URL; SAML already uses POST instead of GET for transporting tokens.

GET and POST are two HTTP methods. GET puts data in the URL; POST puts it in the request body, which does not appear in the address bar, in browser history or in logs. SAML is an older standard for exchanging login information between organisations.

  • Use postMessage. This uses HTML5 postMessage for cross-domain communication.
From the original on threatnix.io

postMessage is a browser feature that lets two pages on different origins send each other a message directly, without putting the data in a URL. Both approaches are supported by OAuth and OpenID Connect and can be selected through response_mode as long as the authorisation server supports it, but support for query and fragment modes still has to be disabled or removed. OpenID Connect is a layer on top of OAuth for logging in; response_mode is the setting that chooses how the result is delivered.

  • Use SameSite cookies. They protect against this vulnerability and make almost all client-side vulnerabilities infeasible; they protected several programs in the researchers' campaign.

A cookie is a small piece of data a website stores in your browser and that the browser sends back on later requests. A SameSite cookie is marked so that it is not sent along with requests started by other websites, which removes a whole class of cross-site attacks.

  • For OAuth, use PKCE for defence in depth. It makes the exploit largely useless because the code_verifier is also needed to use the leaked code.

PKCE (Proof Key for Code Exchange) adds a second secret to the login flow: the application sends a hashed value up front and must present the original code_verifier later. A stolen code alone is then not enough. Defence in depth means adding a second lock even when the first one is supposed to work.

  • Ask for manual authorisation each time a user logs in. This prompts every time even if the user is already authorised; OpenID supports it through the prompt parameter, and Apple does exactly this.

  • Use client-side redirects (or JavaScript) instead of 30x. This can be combined with X-Frame-Options or CSP's frame-ancestors; Twitter uses this method.

A client-side redirect is done by the page itself in JavaScript rather than by a server header. It can be combined with headers that stop other sites from embedding the page in a frame, which limits how the redirect can be abused.

  • Validate referrer/origin against the client (client_id, redirect_uri). Not recommended, because it suffers from the same issues as CSRF protection based on referrer/origin.

Browsers also have mitigations beyond the Same Origin Policy, though these are specific to CSP and do not cover the second issue described below. The Same Origin Policy is the browser's core rule that one origin cannot read another origin's data.

  1. Violation reports include only the URL of the original request, not the redirect target, so the attacker only gets what they already know.
  2. Browsers ignore the path component of a source expression if the resource being loaded is the result of a redirect, to prevent leaking path information as demonstrated in Homakov's post.

Bypasses and a new 0day

After the reports, several programs, including Facebook and Coinbase, fixed the issue by checking whether the User-Agent is Safari and using a different approach only in that case; for all other user-agents the workflow stayed the same. The User-Agent is a line of text your browser sends with every request saying what browser and operating system it is. Changing it therefore seemed an obvious bypass, and an obvious place to try it was on iPhone and iPad, where every browser uses WebKit. Using Chrome did not work, but switching to "Desktop Site" did. The User-Agent change was not inherited by subsequent fetch requests, so the researchers tried every request from Cure53's HTTPLeaks project and found that <a ping> (an anchor with the ping attribute) did the job.

A bypass is a way around a fix. <a ping> is an HTML link that, when clicked, quietly sends a small request to a monitoring address; it was useful here because it carried the changed User-Agent in a way fetch did not.

While hunting for bypasses they found another 0day, this time in Cross-Origin-Resource-Sharing (CORS) rather than CSP. A 0day is a flaw that is not yet publicly known or fixed. CORS is the set of rules that decides whether a page on one origin may read a response from another origin. The finding was as easy as adding a catch handler to the fetch request, which disclosed the destination URL.

From the original on threatnix.io

A catch handler is the part of JavaScript that runs when an operation fails. Here, the failure message itself contained the address the request had been redirected to.

They shared their plan to disclose the vulnerability with Apple, and it was fixed right before their talk without them being notified.

Variants to test

  • Cross-origin redirect behind a CSP-protected fetch. On any engine, set a policy that allows only the first-party origin and the redirecting domain, then fetch an endpoint that 30x-redirects to a different origin. A positive result is a SecurityPolicyViolationEvent whose documentURI contains the full redirect target, including path and query, rather than the original request URL.
  • SSO and OAuth callback endpoints. Point the same page at an authorisation endpoint that redirects back to the application with a code or token in the URL. A positive result is the code or token appearing in documentURI.
  • User-Agent based fixes. Where a program's fix keys on the Safari User-Agent, try the same request from an iOS browser in "Desktop Site" mode, and try <a ping> for requests whose User-Agent change is not inherited by fetch. A positive result is the leak reappearing.
  • CORS error handling. Add a catch handler to a cross-origin fetch and inspect the error. A positive result is the destination URL being disclosed in the error.
  • Other report channels. Repeat the redirect test against report-uri, report-to and ReportingObserver rather than the event, to see whether any channel carries the redirect target.

Key takeaways

  1. SameSite cookies can be very helpful.
  2. Use defence in depth to mitigate browser flaws.
  3. Browsers do not always follow the spec completely.

Timeline

Date Event
Feb 21, 2020 Initial report sent to Safari
Mar 12, 2020 Sent a ping
Mar 16, 2020 Automatic acknowledgement received
Apr 20, 2020 Apple replied that the vulnerability does not pose a threat
Jan 12, 2021 Started targeting other bug bounty programs
May 24, 2021 Apple patched the vulnerability and shipped new WebKit versions

A recording of the talk as presented at GreHack 2021 is available.

Or watch on YouTube
From the original on threatnix.io

Glossary

  • 0day: a vulnerability that is not yet publicly known or fixed.
  • API: a defined way for one piece of software to talk to another.
  • Authentication token: a short string that proves who you are to an application, like a temporary pass.
  • Authorisation code: a short-lived string an SSO service hands back to an application, normally exchanged for an access token.
  • Authorisation endpoint: the address on an SSO service that handles the login-and-redirect step.
  • Browser engine: the part of a browser that reads HTML, CSS and JavaScript and turns it into a page.
  • Bug bounty: a program in which a company pays researchers for reporting flaws responsibly.
  • Bypass: a way around a fix.
  • Catch handler: the part of JavaScript that runs when an operation fails.
  • Cookie: a small piece of data a website stores in your browser and that the browser sends back on later requests.
  • CORS: the rules that decide whether a page on one origin may read a response from another origin.
  • CSP (Content Security Policy): a set of rules telling the browser which resources a page may load and run.
  • CSRF: an attack where a malicious page makes your browser send a request you did not intend.
  • CVE: a public catalogue number for a known vulnerability.
  • Defence in depth: adding a second lock even when the first one is supposed to work.
  • Event: something the browser announces, which page code can listen for.
  • Event listener: JavaScript that says "when this event happens, run this function".
  • Fetch request: JavaScript asking the browser to get something from a network address without navigating the page there.
  • GET / POST: two HTTP methods; GET puts data in the URL, POST puts it in the request body.
  • HTTP response header: a small piece of text a server sends along with a page, before the content.
  • ITP (Intelligent Tracking Prevention): a WebKit privacy feature that limits cross-site tracking.
  • OAuth: the open standard behind most "Log in with..." buttons.
  • OpenID Connect: a layer on top of OAuth for logging in.
  • Origin: the combination of protocol, host and port, roughly https://example.com; the browser's unit of trust.
  • PKCE: an OAuth extension that adds a second secret so a stolen code alone is not enough.
  • postMessage: a browser feature that lets pages on different origins send each other messages directly.
  • Redirect: a server's way of saying "not here, go there instead", using a Location header.
  • Responsible disclosure: telling the vendor privately first, giving them time to fix the problem.
  • Same Origin Policy: the browser's core rule that one origin cannot read another origin's data.
  • SameSite cookie: a cookie marked so it is not sent with requests started by other websites.
  • SAML: an older standard for exchanging login information between organisations.
  • SSO (Single Sign-On): a centralised login service that other applications trust.
  • State / nonce: a value used in OAuth to prevent CSRF and to return users to where they were.
  • User-Agent: a line of text a browser sends with every request saying what browser and operating system it is.
  • Violation report: the report a browser dispatches when a CSP rule blocks something.
  • W3C: the standards body that writes the specifications browsers follow.
  • WebKit: the browser engine behind Safari, and the only engine allowed on iOS.
  • 30x: the family of HTTP responses that mean a redirect (301, 302 and so on).

More from Apple

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Information disclosure

The lesson behind this report.

Data the application should keep private (personal data, internal details, other users' records) reaches someone it should not.