Skip to content
Misconfiguration Write-up Intermediate

Dodging OAuth origin restrictions for Firebase spelunking

The post describes a technique to bypass Google OAuth origin restrictions when testing Firebase apps that only allow Google sign-in. By hosting a local web server on the Firebase project's domain over HTTPS, the author obtained a valid OAuth token and used it to query the Firebase database, revealing misconfigured security rules that allowed unauthorized data access.

Aditya Saligrama Follow

Published on saligrama.io

In my last post, I covered the marvelous world of Firebase database spelunking: when app developers misconfigure their Firestore security rules, the resulting ability to perform unauthorized data accesses can lead to terrifying data breaches for those apps. Thanks to tools like Baserunner, testing apps for such…

Aditya Saligrama (@saligrama_a), Glen Husman, on saligrama.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

This write-up is about testing Firebase-backed single-page applications (SPAs) that only allow Google sign-in through Firebase authentication. Tools such as Baserunner make it easy to query a Firestore database once you have saved an authorization state, but they historically supported only email/password and phone/OTP sign-in. When a client app accepts only a Google account, you need the Google OAuth token that the app would normally obtain in the browser, because that token is what Firebase consumes to build the authorization header for database requests.

The motivation was a security inspection that Glen Husman and I conducted in February 2022 on a Stanford student-created website that stored some moderately sensitive user data. The site was a JavaScript SPA backed by a Firebase database that only allowed Google sign-in via Firebase authentication. We found minor issues relating to Firebase security rule misconfigurations leading to some unauthorized data accesses. We disclosed these vulnerabilities on February 27, 2022 and received confirmation that they had been fixed on March 28, 2022. To respect the student's and app's request for anonymity, the engagement itself is not described further here; the examples below relate to a demo app I created solely for this post.

Setup

To make requests against a Firebase database you need a set of API tokens found on the client side, plus an authorization header. For an SPA the API tokens are easily found by inspecting the minified JavaScript source code of the page. The authorization header depends on the sign-in method: with email/password the credentials go directly to Firebase's authentication server, which returns the header; with phone/OTP the phone number is passed to Firebase's authentication server, which sends an OTP, and the entered OTP is passed back to obtain the header.

Google OAuth sign-in is more involved:

  1. The client makes a request to Google's OAuth server including the site's Google client ID.
  2. The Google OAuth server conducts the user-facing sign-in flow, either listing Google accounts already logged in on the browser to use, or requesting email/password/MFA (if applicable).
  3. The Google server then checks if the requesting client's origin is registered under the Google developer project for Google sign-in. If not, an origin mismatch error is shown to the user.
  4. An OAuth token is then returned to the client. For SPAs, these tokens typically expire after one hour.
  5. The Firebase app consumes the OAuth token to create an authorization header for the corresponding database.

I created a demo Firebase project that only accepts Google sign-in. It has since been taken down, so hitting the endpoint now gets you nowhere. The API tokens were as follows, and again you can find these from the JS source code of an SPA:

JSON
{
  "apiKey": "[redacted]",
  "authDomain": "saligrama-oauth-demo.firebaseapp.com",
  "projectId": "saligrama-oauth-demo",
  "storageBucket": "saligrama-oauth-demo.appspot.com",
  "messagingSenderId": "915380107062",
  "appId": "1:915380107062:web:39f937f22655442c46a597"
}

I then created a user account for the project backed by my Google account ([redacted]), as well as some test data in Cloud Firestore to be queried for.

Demo user
Demo user From the original on saligrama.io

Demo user

Test data
Test data From the original on saligrama.io

Test data

The objective is to get the Google OAuth token for [redacted] corresponding to the demo app, which can then produce a Firebase authorization header usable in a Node.js script to query the database.

Finding it

The obstacle is the origin restriction. OAuth is a communication protocol between web applications, so you need to actually be running a web server to try to get the token. The identity provider enforces a restriction on what origin the sign-in flow request can come from, and those origins are configurable when setting up OAuth with the identity provider. An origin is a unique scheme://domain:port tuple. To illustrate, the following are different origins:

Text
http://saligrama.io
http://www.saligrama.io
http://saligrama.io:8080
https://saligrama.io

And the following are the same origin:

Text
https://saligrama.io
https://saligrama.io:443
https://saligrama.io/blog

This is what stops a phishing site https://b4nk.com from identifying itself to Google as https://bank.com using the latter's public client ID and obtaining a token for the victim's account on the legitimate site. The identity provider can block the request rather than responding with an access token. The same mechanism stands between a researcher and the token when the app is a Firebase SPA whose registered origin is its own Firebase domain.

Exploitation

Attempt 1: running a local web server

The simplest option is Python's http.server module, serving a simple HTML and JavaScript page.

HTML
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <meta name="google-signin-cookiepolicy" content="single_host_origin">
    <meta name="google-signin-scope" content="openid https://www.googleapis.com/auth/userinfo.email profile">

    <script src="googleauth_import.js"></script>
</head>
<body>
    <!-- Script providing the Google sign-in functionality -->
    <!-- Note: callback function for Google sign-in needs to be in a separate file -->
    <!-- Contains Client ID for saligrama-oauth-demo -->
    <script src="https://accounts.google.com/gsi/client" async defer></script>
    <div id="g_id_onload"
         data-client_id="915380107062-[redacted].apps.googleusercontent.com"
         data-callback="onSignIn">
    </div>
    <div class="g_id_signin" data-type="standard"></div>
</body>
</html>
JavaScript
// googleauth_import.js
function onSignIn(googleUser) {
  console.log(googleUser);
}

The page loads Google's client library, sets the demo project's client ID on the sign-in widget, and registers onSignIn as the callback, which prints the sign-in info to the console when sign-in succeeds. The callback has to live in a separate file.

Run the server:

Text
❯ python3 -m http.server -d http-root -b [redacted] 8080
Serving HTTP on [redacted] port 8080 (http://[redacted]:8080/) ...

This loads a page with a Google sign-in button, as expected:

Google sign-in basic page
Google sign-in basic page From the original on saligrama.io

Google sign-in basic page

Clicking on the button yields a pop-up with the Google sign-in flow; after successfully signing in with [redacted], the pop-up abruptly closes. Checking the console, we see the following:

Google sign-in failure due to origin mismatch
Google sign-in failure due to origin mismatch From the original on saligrama.io

Google sign-in failure due to origin mismatch

The issue was the domain we were loading: http://localhost:8080 is not a registered origin for the demo app. This is the origin restriction in action.

Attempt 2: domain-jacking

The next idea is to use saligrama-oauth-demo.firebaseapp.com as the domain. That host has its own public IP address ([redacted] at the time of writing), but you can tell your local machine to point the hostname to any IP address of your choosing, including the local host, [redacted]. This is done by editing the hosts file and adding a line containing the following:

Text
[redacted] saligrama-oauth-demo.firebaseapp.com
  • On Linux and macOS: /etc/hosts
  • On Windows: C:\Windows\system32\drivers\etc\hosts

Since an origin is a scheme, a host and a port, we should probably also run the web server on port 80, which requires administrator permissions on Linux:

Text
❯ sudo python3 -m http.server -d http-root -b [redacted] 80
Serving HTTP on [redacted] port 80 (http://[redacted]:80/) ...

Now we load this in the browser, conduct the sign-in flow, and check the console:

Google sign-in basic page
Google sign-in basic page From the original on saligrama.io

Google sign-in basic page

Google sign-in failure due to origin mismatch
Google sign-in failure due to origin mismatch From the original on saligrama.io

Another failure. Another failure. Maybe changing the scheme and port, using HTTPS over port 443, will help.

Attempt 3: HTTPS, where the S stands for Success

Running an HTTPS server requires a little more legwork. First, generate a self-signed SSL certificate:

Text
❯ openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes \
  -keyout server.pem -out server.pem \
  -subj "/CN=saligrama-oauth-demo.firebaseapp.com" \
  -addext "subjectAltName=DNS:saligrama-oauth-demo.firebaseapp.com"

This creates a certificate and key in a single server.pem, valid for the Firebase project's hostname via the subject alternative name. We then need to allow the Python HTTP server to serve over HTTPS; a light modification to a GitHub Gist suffices:

Python
import http.server
import ssl

server_address = ("[redacted]", 443)

class CORSHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    extensions_map = {
        "": "application/octet-stream",
        ".manifest": "text/cache-manifest",
        ".html": "text/html",
        ".png": "image/png",
        ".jpg": "image/jpg",
        ".svg": "image/svg+xml",
        ".css": "text/css",
        ".js": "application/x-javascript",
        ".wasm": "application/wasm",
        ".json": "application/json",
        ".xml": "application/xml",
    }

    def end_headers(self):
        # Include additional response headers here. CORS for example:
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Cross-Origin-Opener-Policy", "same-origin-allow-popups")
        self.send_header("Cross-Origin-Embedder-Policy", "require-corp")
        http.server.SimpleHTTPRequestHandler.end_headers(self)

httpd = http.server.HTTPServer(server_address, CORSHTTPRequestHandler)
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.check_hostname = False
ctx.load_cert_chain(certfile="../server.pem")  # with key inside
httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)
httpd.serve_forever()

The handler serves the static files and adds the response headers set in the code, including Cross-Origin-Opener-Policy: same-origin-allow-popups and Cross-Origin-Embedder-Policy: require-corp. The server binds to port 443 and wraps the socket with the self-signed certificate.

Run the server:

Text
❯ sudo python3 simple-https-server.py

Naturally, as the certificate is self-signed, Firefox throws a warning that can be bypassed. In some cases, if you have already navigated to https://PROJECT_ID.firebaseapp.com, your browser will refuse to let you see the self-hosted page due to HSTS settings. HSTS is a policy that stores HTTPS certificates associated with websites and prevents users from accessing those websites again if the certificate does not match the stored one. In that case you need to clear HSTS settings by clearing all data associated with the site from your browser.

Self-signed cert warning
Self-signed cert warning From the original on saligrama.io

Self-signed cert warning

We again go through the Google sign-in flow and check the console, which yields the token!

Auth success
Auth success From the original on saligrama.io

Auth success

Some projects follow Firebase default settings to allow http://localhost (port 80) as an origin, which would shortcut the hostname and certificate process. However, some projects remove localhost as an acceptable origin once in production, so using the actual Firebase project's domain over HTTPS as above is more reliable.

Querying for data

With the token in hand, query the Firebase database using a Node.js script, similar to the example from the previous post:

JavaScript
// oauth-demo.mjs
import { initializeApp } from 'firebase/app';
import { getFirestore, doc, getDoc } from 'firebase/firestore/lite';
import { getAuth, signInWithCredential, GoogleAuthProvider } from "firebase/auth";

const firebaseConfig = {
    apiKey: "[redacted]",
    authDomain: "saligrama-oauth-demo.firebaseapp.com",
    projectId: "saligrama-oauth-demo",
    storageBucket: "saligrama-oauth-demo.appspot.com",
    messagingSenderId: "915380107062",
    appId: "1:915380107062:web:39f937f22655442c46a597"
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const auth = getAuth();

const id_token = "PASTE_OAUTH_TOKEN_HERE";

const credential = GoogleAuthProvider.credential(id_token);

signInWithCredential(auth, credential)
    .then((_) => {
        let docRef = doc(db, "test", "EsjmpXTOSnAb9o6JZufF");
        getDoc(docRef).then(x => {
                console.log(x.data());
            }
        );
    })
    .catch((error) => {
        console.error(error);
    });

The script initialises the app with the same config found in the SPA, wraps the captured OAuth token in a GoogleAuthProvider credential, signs in to Firebase with it, and reads a document from the test collection. Running it returns the desired data:

Text
❯ node oauth-demo.mjs
{ message: 'Spooky scary user data, send shivers down your spine' }

Root cause

The barrier is the origin check that the identity provider performs on the sign-in request. A Firebase SPA has no application server that can hold a client secret, so the two-legged flow relies on the registered origin to authenticate the application. A page served from http://localhost:8080, or from the Firebase hostname over plain HTTP on port 80, was rejected with an origin mismatch. The check is working as designed; the bypass comes from making the browser believe it is on the registered origin, by pointing the hostname at the local machine and serving the page over HTTPS on port 443 with a certificate for that hostname. The self-signed certificate warning can be bypassed in the browser, and HSTS can get in the way if the real site was visited before.

Impact

For an attacker, the technique makes it possible to sign into a Google OAuth-only Firebase database for exploratory purposes outside the official app context, and then query it with the resulting authorization header. What that yields depends entirely on the database's security rules: in the engagement described, minor Firebase security rule misconfigurations led to some unauthorized data accesses, which were disclosed and fixed. The token obtained is scoped to the app and, for SPAs, typically expires after one hour. The report does not describe any wider impact.

Fix

On the Baserunner side, the lack of Google sign-in support had been an open issue for nearly 18 months. Using what I learned from this engagement, I added the support: a way to set the Google client ID on the frontend, dynamically generating a Google sign-in button based on that input client ID, then plumbing the resulting credential through to the saved Firebase state for login. My pull request was merged in August 2022, and Baserunner can now be used to query the data.

Succesful query using Baserunner
Succesful query using Baserunner From the original on saligrama.io

Successful query using Baserunner

Variants to test

  • Check whether the project still allows http://localhost (port 80) as an origin. A positive result is a completed Google sign-in from a local server without any hostname or certificate work.
  • If localhost has been removed, point the Firebase project hostname at [redacted] in the hosts file and serve over HTTPS on port 443 with a certificate for that hostname. A positive result is the sign-in callback printing the token instead of an origin mismatch.
  • If the browser refuses the self-hosted page because of HSTS, clear all data for the site and retry. A positive result is the self-signed certificate warning appearing and being bypassable.
  • Once a token is captured, feed it to a Node.js script as a GoogleAuthProvider credential and read a known document. A positive result is the document's data being returned, which indicates the security rules permit the access.

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

What happened, in plain words

A website can store its data in a database run by a company called Firebase (a Google service). To keep that data safe, the database is supposed to check who is asking before it hands anything over. Sometimes the app's settings are wrong, and the database lets people read data they should not see. This post is about how two researchers tested such an app, and how they got past a roadblock that made the normal testing tool useless.

The roadblock: the app only let people sign in with a Google account. The usual testing tool, Baserunner, could sign in with an email and password, or with a phone number and a one-time code, but not with Google. So the researchers had to obtain the Google sign-in token themselves, the same token the app would normally get in a browser, because that token is what Firebase turns into the pass that opens the database.

The interesting part is that Google refuses to hand out that token to just any web page. It only hands it to pages served from an address the app owner has registered with Google. The researchers worked around that by making their own computer pretend to be the registered address, serving a page over a secure connection with a certificate they made themselves. Once the token came through, they used it in a small script to read data from the database.

The work started as a security inspection that Glen Husman and I did in February 2022 on a Stanford student-created website that stored some moderately sensitive user data. The site was a JavaScript single-page application backed by a Firebase database that only allowed Google sign-in via Firebase authentication. We found minor issues relating to Firebase security rule misconfigurations leading to some unauthorized data accesses. We disclosed these vulnerabilities on February 27, 2022 and received confirmation that they had been fixed on March 28, 2022. To respect the student's and app's request for anonymity, the engagement itself is not described further here; the examples below relate to a demo app I created solely for this post.

Background: what all these words mean

Before the steps, a short tour of the pieces involved, because the rest of the post leans on them.

Firebase and Firestore

Firebase is a set of services from Google that lets someone build an app without running their own servers. One of those services, Cloud Firestore, is a database: a place where the app keeps its data, organised into collections of documents. Think of a filing cabinet: a collection is a drawer, a document is a folder inside it, and the fields inside the document are the papers.

A single-page application (SPA) is a website built as one page that loads once and then updates itself in the browser as you click around, instead of loading a fresh page from the server each time. Because everything happens in the browser, the browser has to talk to Firebase directly.

API tokens and the authorization header

An API (application programming interface) is simply a way for one piece of software to ask another piece of software to do something, over the network. When the browser talks to Firebase, it sends requests, and each request carries a little bundle of text called a header. One particular header, the authorization header, is the request's proof of identity, like showing a membership card at the door.

To build that header, the app needs some identifying values that Firebase gave it when the project was set up. These are often called API tokens or config values. They are not secret in the way a password is: they sit in the app's code, which the browser downloads, so anyone can read them. The post calls them API tokens and notes they can be found by inspecting the minified JavaScript source code of the page. Minified means the code has been squashed and shortened to make the file smaller, which makes it hard to read but does not hide anything.

OAuth and OpenID Connect

OAuth is a protocol, a set of rules for how two programs talk to each other, meant to delegate access between applications. It separates two questions: who you are (authentication) and what you are allowed to do (authorization). The identity and authorization provider, for example Google, can be a different entity from the application the user is actually logging into, for example Notion. OAuth usage can also be scoped, meaning the requesting application is only allowed to access certain data owned by the identity provider.

A few vocabulary words from the post:

  • Client Application / Relying Party: an application which receives delegated authorized access from another server, or relies on another server for authentication. In this case, the Firebase database.
  • Authorization Server / Identity Provider (IdP): the server that conducts a sign-in flow that allows the user to authenticate, and on which the user consents to authorizing the app. In this case, Google.
  • OAuth 2.0: an authorization standard. Client apps prompt for authorization and receive an opaque access token to access a resource, identified by scopes. Opaque here means the token is just a string; you are not meant to read meaning out of it.
  • OpenID Connect (OIDC): an authentication standard built on OAuth 2, used by Sign In With Google and other protocols. It extends OAuth to return a verifiable ID token making authentication claims (for example, that user Aditya Saligrama owns email address [redacted]), in addition to the access token.

In the simplest terms: a client application asks the identity provider to run a sign-in, usually in a popup window or a new browser tab. The user signs in there. The identity provider then gives the client a scoped token that identifies the user and, if needed, lets the client fetch data from the identity provider. The client passes that token, or something derived from it, to the user's browser, and the browser includes it on later requests so the client knows who is asking.

The phishing problem OAuth has to solve

Here is a potential security problem with OAuth. Suppose a banking site, https://bank.com, supports logging in with OAuth using Google as an authentication provider. When a user, Alice, goes through the Google sign-in flow on bank.com, bank.com is provided a token used to authorize access to Alice's data on bank.com, which is then passed to her browser.

Now suppose Alice receives a phishing email leading her to click on https://b4nk.com, a phishing site that looks exactly the same as bank.com. Just like the legitimate bank site, Alice is asked to sign in with Google. If b4nk.com uses its own client ID for Google sign-in, then all is well, as the scoped token that is returned only allows access to data on b4nk.com.

But suppose b4nk.com identifies itself to Google as bank.com using the latter's public client ID. If the flow completes successfully, then b4nk.com has successfully obtained a token for Alice's account on bank.com, which can then be used to access Alice's banking data. That is a clear security violation and should not be allowed to happen. So applications themselves must have some way of authenticating themselves to the identity provider, such that only legitimate applications can request access tokens for their sites.

Two ways to prove you are the real app

A traditional web application typically has a client and a dedicated application server. The three legs of the flow are the user's browser (and therefore the frontend client), the application server, and the authorization (IdP) server. This means the application server is capable of holding secrets that can be used to authenticate the application itself to the identity provider. When an OAuth sign-in flow is conducted, the application passes along its client secret to the identity provider, which only returns the access token if the client secret can be verified. This is the three-legged flow.

A JavaScript SPA is different: all requests are made from the user's browser, so there is no application server that can hold a client secret. But such an application can still fall prey to the phishing attack mentioned earlier. So, to ensure that only legitimate applications can obtain a user access token, the identity provider can enforce a restriction on what origin the sign-in flow request can come from. These origins are configurable when setting up OAuth with the identity provider. This is the two-legged flow.

What an origin is

An origin is a unique scheme://domain:port tuple. The scheme is the part before the ://, such as http or https. The domain is the site name. The port is a numbered door on the server; browsers use defaults when you do not type one, 80 for http and 443 for https. Two addresses are the same origin only if all three parts match.

To illustrate, the following are different origins:

Text
http://saligrama.io
http://www.saligrama.io
http://saligrama.io:8080
https://saligrama.io

And the following are the same origin:

Text
https://saligrama.io
https://saligrama.io:443
https://saligrama.io/blog

Notice the last one: a path like /blog does not change the origin. Only scheme, domain and port matter. This is what stops the phishing attack: https://b4nk.com is a different origin than https://bank.com, so the identity provider can block the request rather than responding with an access token.

The Firebase sign-in flow, step by step

To make requests against a Firebase database, you need a set of API tokens found on the client side, plus an authorization header. For an SPA, the API tokens are easily found by inspecting the minified JavaScript source code of the page.

The authorization header depends on the sign-in method. With email/password authentication, the email and password are passed directly to Firebase's authentication server, which then returns the authorization header. With phone/OTP authentication, the phone number is passed to Firebase's authentication server, which then sends an OTP (a one-time password, a short code sent to the phone) to the phone. This OTP is then entered on the client side, passed back to the Firebase authentication server, which then returns the authorization header.

Google OAuth sign-in is a little more complicated:

  1. The client makes a request to Google's OAuth server including the site's Google client ID.
  2. The Google OAuth server conducts the user-facing sign-in flow, either listing Google accounts already logged in on the browser to use, or requesting email/password/MFA (if applicable). MFA means multi-factor authentication: more than one proof of identity, such as a password plus a code.
  3. The Google server then checks if the requesting client's origin is registered under the Google developer project for Google sign-in. If not, an origin mismatch error is shown to the user.
  4. An OAuth token is then returned to the client. For SPAs, these tokens typically expire after one hour.
  5. The Firebase app consumes the OAuth token to create an authorization header for the corresponding database.

The client ID in step 1 is the public name the app uses when talking to Google, a bit like a shop's name on a sign. It is not a secret. The origin check in step 3 is the lock that keeps other sites from borrowing that name.

Setting up a demo

To demonstrate this process, I created a demo Firebase project that only accepts Google sign-in. Note that I've taken this down by now, so trying to hit this endpoint will get you nowhere. The API tokens were as follows; again, you can find these from the JS source code of an SPA:

JSON
{
  "apiKey": "[redacted]",
  "authDomain": "saligrama-oauth-demo.firebaseapp.com",
  "projectId": "saligrama-oauth-demo",
  "storageBucket": "saligrama-oauth-demo.appspot.com",
  "messagingSenderId": "915380107062",
  "appId": "1:915380107062:web:39f937f22655442c46a597"
}

This is a JSON object, a way of writing labelled values. Each line is a name and a value. apiKey is the key Firebase uses to recognise the project. authDomain is the web address Firebase uses for sign-in. projectId is the project's internal name. storageBucket is where files would go. messagingSenderId and appId identify the app to Google's services. None of these are passwords; they are the public labels the app ships to every visitor.

I then created a user account for the project backed by my Google account ([redacted]), as well as some test data in Cloud Firestore to be queried for.

Demo user
Demo user From the original on saligrama.io

Demo user

Test data
Test data From the original on saligrama.io

Test data

The objective here is to get the Google OAuth token for [redacted] corresponding to the demo app, which can then produce a Firebase authorization header. That header can then be used in a Node.js script to query the database. Node.js is a program that runs JavaScript outside a browser, on your own computer.

Attempt 1: running a local web server

As OAuth is a communication protocol between web applications, we need to actually be running a web server to try to get the OAuth token. A web server is a program that hands out web pages when a browser asks for them. The simplest possible option is Python's http.server module, serving a simple HTML and JavaScript page. HTML is the language web pages are written in; JavaScript is the language that makes them interactive.

HTML
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <meta name="google-signin-cookiepolicy" content="single_host_origin">
    <meta name="google-signin-scope" content="openid https://www.googleapis.com/auth/userinfo.email profile">

    <script src="googleauth_import.js"></script>
</head>
<body>
    <!-- Script providing the Google sign-in functionality -->
    <!-- Note: callback function for Google sign-in needs to be in a separate file -->
    <!-- Contains Client ID for saligrama-oauth-demo -->
    <script src="https://accounts.google.com/gsi/client" async defer></script>
    <div id="g_id_onload"
         data-client_id="915380107062-[redacted].apps.googleusercontent.com"
         data-callback="onSignIn">
    </div>
    <div class="g_id_signin" data-type="standard"></div>
</body>
</html>

Line by line:

  • <!-- index.html --> is a comment naming the file. Comments are notes for humans; the browser ignores them.
  • <!DOCTYPE html> tells the browser this is an HTML page.
  • <html>, <head>, <body> are the page's skeleton: the whole document, its settings, and its visible content.
  • The two <meta> lines set options for Google's sign-in.
  • <script src="googleauth_import.js"></script> loads our own small file, described below.
  • <script src="https://accounts.google.com/gsi/client" async defer></script> loads Google's sign-in library from Google's own servers. async and defer change when the browser executes the downloaded script.
  • The <div id="g_id_onload" ...> block is a placeholder that Google's library fills in. data-client_id is the demo project's client ID, the public name mentioned earlier. data-callback="onSignIn" names the function to call once sign-in succeeds.
  • <div class="g_id_signin" data-type="standard"></div> is where the actual sign-in button appears.
JavaScript
// googleauth_import.js
function onSignIn(googleUser) {
  console.log(googleUser);
}

This file defines onSignIn, the function Google calls when sign-in finishes. It receives the sign-in information as googleUser and prints it to the browser's console with console.log. The console is a panel in the browser's developer tools where a page can write messages; it is where we will look for the token. The callback has to live in a separate file, which is why it is not inline in the HTML.

When the sign-in is successful, we should expect to see the Google sign-in info printed in the console. Run the server:

Text
❯ python3 -m http.server -d http-root -b [redacted] 8080
Serving HTTP on [redacted] port 8080 (http://[redacted]:8080/) ...

This command starts Python's built-in web server. -d http-root says to serve files from a folder called http-root, where the two files above live. -b [redacted] says to listen only on the local machine; [redacted] is the address a computer uses to refer to itself, often called localhost. 8080 is the port, a spare door so it does not clash with anything else. The second line is the server telling us it is running.

This loads a page with a Google sign-in button, as expected:

Google sign-in basic page
Google sign-in basic page From the original on saligrama.io

Google sign-in basic page

Clicking on the button yields a pop-up with the Google sign-in flow; after successfully signing in with [redacted], the pop-up abruptly closes. Checking the console, we see the following:

Google sign-in failure due to origin mismatch
Google sign-in failure due to origin mismatch From the original on saligrama.io

Google sign-in failure due to origin mismatch

Clearly, the issue was with the domain we were loading: http://localhost:8080 is not a registered origin for the demo app. We have run up against the origin restriction described earlier. The page was served from http, on localhost, on port 8080, and none of that matches what Google has on file for the demo project. So Google refused to hand over the token. Let's try using the Firebase project's domain itself.

Attempt 2: domain-jacking

We now want to use saligrama-oauth-demo.firebaseapp.com as the domain. That is the address Google has registered. While this is a host with its own public IP address ([redacted] at the time of writing), we can tell our local machine to point the hostname to any IP address of our choosing, including the local host, [redacted]. An IP address is the numeric address of a machine on the network; a hostname is the friendly name that gets translated into one. The translation is done by a lookup table on your own computer, checked before the wider internet is consulted.

This is done by editing the hosts file, adding a line containing the following:

Text
[redacted] saligrama-oauth-demo.firebaseapp.com

This line says: whenever this computer is asked for saligrama-oauth-demo.firebaseapp.com, answer with [redacted], which is the computer itself. The hosts file lives in different places depending on the system:

  • On Linux and macOS: /etc/hosts
  • On Windows: C:\Windows\system32\drivers\etc\hosts

Recalling that an origin is comprised of a scheme, a host, and a port, we should probably also run the web server on port 80, which requires administrator permissions on Linux. Ports below 1024 are reserved for privileged programs, so the system asks for proof you are allowed to use them.

Text
❯ sudo python3 -m http.server -d http-root -b [redacted] 80
Serving HTTP on [redacted] port 80 (http://[redacted]:80/) ...

sudo runs the command with administrator rights. The rest is the same as before, except the port is now 80, the default for plain http. Now we load this in our web browser, conduct the sign-in flow, and check the console:

Google sign-in basic page
Google sign-in basic page From the original on saligrama.io

Google sign-in basic page

Google sign-in failure due to origin mismatch
Google sign-in failure due to origin mismatch From the original on saligrama.io

Another failure. The page now has the right hostname, but the scheme is still http and the port is 80. Maybe changing the scheme and port, using HTTPS over port 443, will help. HTTPS is the secure version of HTTP: the traffic is encrypted, and the server proves its identity with a certificate.

Attempt 3: HTTPS, where the S stands for Success

Running an HTTPS server requires a little more legwork. First, we need to generate a self-signed SSL certificate. A certificate is a digital document that says "this server is who it claims to be". Normally a trusted authority signs it. A self-signed certificate is signed by the server itself, so browsers warn about it, but it still lets the encrypted connection work.

Text
❯ openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes \
  -keyout server.pem -out server.pem \
  -subj "/CN=saligrama-oauth-demo.firebaseapp.com" \
  -addext "subjectAltName=DNS:saligrama-oauth-demo.firebaseapp.com"

openssl is a tool for working with certificates and encryption. req -x509 asks it to create a self-signed certificate. -newkey rsa:4096 makes a new 4096-bit RSA key, the secret half of the pair. -sha256 picks the hashing method used in the signature. -days 3650 makes it valid for ten years. -nodes means the key file is not encrypted. -keyout server.pem -out server.pem writes both the key and the certificate into one file called server.pem. -subj "/CN=..." sets the name on the certificate to the Firebase project's hostname. -addext "subjectAltName=DNS:..." adds the modern field browsers actually check, listing the same hostname. The backslashes at the end of lines just mean the command continues on the next line.

We then need to actually allow our Python HTTP server to serve over HTTPS; a light modification to this GitHub Gist suffices:

Python
import http.server
import ssl

server_address = ("[redacted]", 443)

class CORSHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    extensions_map = {
        "": "application/octet-stream",
        ".manifest": "text/cache-manifest",
        ".html": "text/html",
        ".png": "image/png",
        ".jpg": "image/jpg",
        ".svg": "image/svg+xml",
        ".css": "text/css",
        ".js": "application/x-javascript",
        ".wasm": "application/wasm",
        ".json": "application/json",
        ".xml": "application/xml",
    }

    def end_headers(self):
        # Include additional response headers here. CORS for example:
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Cross-Origin-Opener-Policy", "same-origin-allow-popups")
        self.send_header("Cross-Origin-Embedder-Policy", "require-corp")
        http.server.SimpleHTTPRequestHandler.end_headers(self)

httpd = http.server.HTTPServer(server_address, CORSHTTPRequestHandler)
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.check_hostname = False
ctx.load_cert_chain(certfile="../server.pem")  # with key inside
httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)
httpd.serve_forever()

Line by line:

  • import http.server and import ssl load two of Python's built-in toolkits: one for serving web pages, one for encryption.
  • server_address = ("[redacted]", 443) says to listen on every network interface of this machine, on port 443, the default for HTTPS.
  • class CORSHTTPRequestHandler(...) defines a custom page handler, building on Python's standard one. A class is a reusable blueprint for behaviour.
  • The extensions_map dictionary tells the server what kind of file each extension is, so the browser knows how to treat it. For example, .html is text/html and .js is application/x-javascript.
  • def end_headers(self): is a hook that runs just before the server finishes sending its response headers. Headers are the small pieces of information sent alongside a page.
  • httpd = http.server.HTTPServer(...) creates the server object using our handler.
  • ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) creates the encryption settings for a server.
  • ctx.load_cert_chain(certfile="../server.pem") loads the certificate and key from the file we generated.
  • httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True) wraps the server's connection in encryption, so it speaks HTTPS.
  • httpd.serve_forever() starts the server and keeps it running.

Run the server:

Text
❯ sudo python3 simple-https-server.py

Again sudo is needed because port 443 is privileged. Naturally, as the certificate is self-signed, Firefox throws a warning that can be bypassed. In some cases, if you have already navigated to https://PROJECT_ID.firebaseapp.com, your browser will actually refuse to let you see the self-hosted page due to HSTS settings. HSTS is a policy that stores HTTPS certificates associated with websites and prevents users from accessing those websites again if the certificate does not match the stored one. In this case, you'll need to clear HSTS settings by clearing all data associated with the site from your browser.

Self-signed cert warning
Self-signed cert warning From the original on saligrama.io

Self-signed cert warning

We again go through the Google sign-in flow and check the console, which yields the token!

Auth success
Auth success From the original on saligrama.io

Auth success

I should note that I've seen some projects follow Firebase default settings to allow http://localhost (port 80) as an origin, which would shortcut the hostname and certificate process. However, I've also seen projects remove localhost as an acceptable origin once in production, so it's more reliable to use the actual Firebase project's domain over HTTPS as above.

Querying for data

Now that we have the token, we can query the Firebase database for data using a Node.js script, similar to the example from my last post.

JavaScript
// oauth-demo.mjs
import { initializeApp } from 'firebase/app';
import { getFirestore, doc, getDoc } from 'firebase/firestore/lite';
import { getAuth, signInWithCredential, GoogleAuthProvider } from "firebase/auth";

const firebaseConfig = {
    apiKey: "[redacted]",
    authDomain: "saligrama-oauth-demo.firebaseapp.com",
    projectId: "saligrama-oauth-demo",
    storageBucket: "saligrama-oauth-demo.appspot.com",
    messagingSenderId: "915380107062",
    appId: "1:915380107062:web:39f937f22655442c46a597"
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const auth = getAuth();

const id_token = "PASTE_OAUTH_TOKEN_HERE";

const credential = GoogleAuthProvider.credential(id_token);

signInWithCredential(auth, credential)
    .then((_) => {
        let docRef = doc(db, "test", "EsjmpXTOSnAb9o6JZufF");
        getDoc(docRef).then(x => {
                console.log(x.data());
            }
        );
    })
    .catch((error) => {
        console.error(error);
    });

Line by line:

  • The import lines pull in pieces of Firebase's JavaScript library: the app starter, the database functions, and the authentication functions.
  • firebaseConfig is the same set of public values we saw in the app's source code, copied here so the script talks to the same project.
  • initializeApp(firebaseConfig) starts the Firebase app in this script.
  • getFirestore(app) and getAuth() get handles to the database and the authentication system.
  • const id_token = "PASTE_OAUTH_TOKEN_HERE"; is where the token captured from the browser goes. It is a placeholder; you replace it with the real string.
  • GoogleAuthProvider.credential(id_token) wraps the token in the form Firebase expects for a Google sign-in.
  • signInWithCredential(auth, credential) signs in to Firebase using that credential. .then(...) runs the next part if it succeeds; .catch(...) runs if it fails and prints the error.
  • Inside the success branch, doc(db, "test", "EsjmpXTOSnAb9o6JZufF") points at one specific document in the test collection.
  • getDoc(docRef) fetches it, and console.log(x.data()) prints its contents.

Running the script, we get the desired data.

Text
❯ node oauth-demo.mjs
{ message: 'Spooky scary user data, send shivers down your spine' }

node runs the script. The output is the document's contents.

Why the origin check was the barrier

The barrier is the origin check that the identity provider performs on the sign-in request. A Firebase SPA has no application server that can hold a client secret, so the two-legged flow relies on the registered origin to authenticate the application. A page served from http://localhost:8080, or from the Firebase hostname over plain HTTP on port 80, was rejected with an origin mismatch. The check is working as designed; the bypass comes from making the browser believe it is on the registered origin, by pointing the hostname at the local machine and serving the page over HTTPS on port 443 with a certificate for that hostname. The self-signed certificate warning can be bypassed in the browser, and HSTS can get in the way if the real site was visited before.

What this means in practice

For an attacker, the technique makes it possible to sign into a Google OAuth-only Firebase database for exploratory purposes outside the official app context, and then query it with the resulting authorization header. What that yields depends entirely on the database's security rules: in the engagement described, minor Firebase security rule misconfigurations led to some unauthorized data accesses, which were disclosed and fixed. The token obtained is scoped to the app and, for SPAs, typically expires after one hour. The report does not describe any wider impact.

Contributing to Baserunner

Coincidentally, the lack of Google sign-in support was an open issue in Baserunner for nearly 18 months. With what I had learned from this engagement, I was able to add this support to Baserunner. This required adding a way to set the Google client ID on the frontend and dynamically generating a Google sign-in button based on that input client ID, then plumbing the resulting credential through to the saved Firebase state for login.

My pull request was merged in August 2022. We can now use Baserunner to query for the data!

Succesful query using Baserunner
Succesful query using Baserunner From the original on saligrama.io

Successful query using Baserunner

Things worth trying on a similar app

  • Check whether the project still allows http://localhost (port 80) as an origin. A positive result is a completed Google sign-in from a local server without any hostname or certificate work.
  • If localhost has been removed, point the Firebase project hostname at [redacted] in the hosts file and serve over HTTPS on port 443 with a certificate for that hostname. A positive result is the sign-in callback printing the token instead of an origin mismatch.
  • If the browser refuses the self-hosted page because of HSTS, clear all data for the site and retry. A positive result is the self-signed certificate warning appearing and being bypassable.
  • Once a token is captured, feed it to a Node.js script as a GoogleAuthProvider credential and read a known document. A positive result is the document's data being returned, which indicates the security rules permit the access.

Conclusion

While Google sign-in can make it more difficult to sign into Firebase databases for exploratory purposes outside the official app context, it's not impossible, as this work shows. Bypassing the origin restriction enforced by the Firebase authentication requires some finagling, but I hope this post serves as a guide on how to do so. With mainline Baserunner support for Google sign-in added by my pull request, exploring Firebase databases has never been easier.

Glossary

  • API: a way for one piece of software to ask another to do something over the network.
  • API token: a public identifying value an app ships to the browser so it can talk to a service; not a password.
  • Authorization header: the part of a web request that carries proof of who is asking.
  • Baserunner: a tool for querying Firebase databases once you have signed in.
  • Certificate: a digital document proving a server's identity; self-signed means the server signed it itself.
  • Client application / relying party: the app that relies on another server for sign-in.
  • Client ID: the public name an app uses when talking to Google's sign-in service.
  • Client secret: a private value a server can hold to prove it is the real app; SPAs cannot hold one.
  • Cloud Firestore: Google's database service used by Firebase apps.
  • Collection / document: a drawer and a folder inside it; the way Firestore organises data.
  • Console: the browser panel where a page can print messages.
  • CORS: the browser rule deciding whether a page from one origin may read a response from another.
  • Domain / hostname: the friendly name of a site, translated into an IP address.
  • Firebase: Google's set of services for building apps without your own servers.
  • Header: a small piece of information sent alongside a web request or response.
  • Hosts file: a local lookup table that maps hostnames to IP addresses before the internet is consulted.
  • HSTS: a browser policy that remembers a site's HTTPS certificate and refuses mismatches.
  • HTML: the language web pages are written in.
  • HTTPS: the encrypted version of HTTP, using certificates.
  • Identity provider (IdP) / authorization server: the server that runs the sign-in flow, such as Google.
  • IP address: the numeric address of a machine on a network.
  • JavaScript: the language that makes web pages interactive.
  • JSON: a way of writing labelled values.
  • Minified: code squashed and shortened to make the file smaller.
  • MFA: multi-factor authentication, more than one proof of identity.
  • Node.js: a program that runs JavaScript outside a browser.
  • OAuth: a protocol for delegating access between applications.
  • OIDC (OpenID Connect): an authentication standard built on OAuth 2, used by Sign In With Google.
  • Origin: a unique scheme://domain:port combination.
  • OTP: a one-time password, a short code sent to a phone.
  • Phishing: tricking someone into using a fake site that looks real.
  • Port: a numbered door on a server; 80 for HTTP, 443 for HTTPS.
  • Pull request: a proposed change to a shared code project.
  • Scheme: the http or https part of a web address.
  • Scope: the limit on what a token is allowed to access.
  • Single-page application (SPA): a website that loads once and updates itself in the browser.
  • Token: a string that proves identity or grants access, often with an expiry.
  • Web server: a program that hands out web pages when a browser asks.

Similar reports

View all

Same bug class and techniques, clearest first.

Security misconfiguration

The lesson behind this report.

Settings left unsafe: exposed panels, open storage buckets, debug modes, default credentials.