Let the code prove tracker connections instead of the user
Both sides derive an HMAC key from the code, next to the swarm ID, and sign their role and both DTLS fingerprints as they see them. An interposer or a peer that found the swarm without the code can't, so its connection ends and the next peer gets its turn, as does one that proves nothing within 10 s. Tracker transfers need no comparing and no clicks anymore, the manual exchange keeps its fingerprint check. The swarm ID changes once more, old and new clients don't find each other. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
707248f36b
commit
c6145b8919
4 files changed
+193
-89
No files matched your search
+88
-25
@@ -35,6 +35,9 @@ export const TRACKER_WAIT = 6 * 60_000;
|
||||
const MIN_INTERVAL = 30_000;
|
||||
// OWASP's recommendation for PBKDF2-SHA-256. Changing it splits old and new clients into separate swarms.
|
||||
const PBKDF2_ITERATIONS = 600_000;
|
||||
// A tracker peer that connects but proves no code gives up its turn after this. Signing takes
|
||||
// milliseconds, a peer that knows the code is never near it.
|
||||
const PROOF_TIMEOUT = 10_000;
|
||||
// Far beyond what a file system stores, but keeps an absurd name out of the page and the worker.
|
||||
const MAX_NAME = 1024;
|
||||
|
||||
@@ -50,7 +53,8 @@ export type Events = {
|
||||
log: (message: string) => void;
|
||||
// Something the user has to act on, the session can't go on by itself. Not logged separately.
|
||||
error: (message: string) => void;
|
||||
// Called on both sides once connected, and without a check when it ended undecided.
|
||||
// Called on both sides once connected by the manual exchange, and without a check when it ended
|
||||
// undecided. Tracker signaling has the code to prove the connection, nobody has to compare anything.
|
||||
check: (check?: Check) => void;
|
||||
// Bytes of the transferred file the receiver's download manager has read, on both sides. 0 when
|
||||
// the transfer starts.
|
||||
@@ -143,19 +147,28 @@ function randomCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
// The tracker swarm is identified by a 20 byte info_hash, derived from the shared code. Whoever sees
|
||||
// the swarms, a tracker or anyone scraping one, can test a guessed code against all of them at once.
|
||||
// PBKDF2 makes every guess cost what a share pays once (~50 ms), so a GPU gets through a vanishing
|
||||
// part of the 62⁸ codes within TRACKER_WAIT. The salt is fixed, both sides only know the code.
|
||||
async function infoHash(code: string) {
|
||||
// The code is all both sides share. It gives the tracker swarm, identified by a 20 byte info_hash,
|
||||
// and the key that proves the connection, see prove. Whoever sees the swarms, a tracker or anyone
|
||||
// scraping one, can test a guessed code against all of them at once. PBKDF2 makes every guess cost
|
||||
// what a share pays once (~50 ms), so a GPU gets through a vanishing part of the 62⁸ codes within
|
||||
// TRACKER_WAIT. The salt is fixed, both sides only know the code. HKDF splits the result, the public
|
||||
// info_hash tells nothing about the key.
|
||||
async function secrets(code: string) {
|
||||
const text = new TextEncoder();
|
||||
const key = await crypto.subtle.importKey('raw', text.encode(code), 'PBKDF2', false, ['deriveBits']);
|
||||
const password = await crypto.subtle.importKey('raw', text.encode(code), 'PBKDF2', false, ['deriveBits']);
|
||||
const bits = await crypto.subtle.deriveBits(
|
||||
{ name: 'PBKDF2', hash: 'SHA-256', salt: text.encode('hellcon'), iterations: PBKDF2_ITERATIONS },
|
||||
key,
|
||||
160,
|
||||
password,
|
||||
256,
|
||||
);
|
||||
return String.fromCharCode(...new Uint8Array(bits));
|
||||
const master = await crypto.subtle.importKey('raw', bits, 'HKDF', false, ['deriveBits', 'deriveKey']);
|
||||
const expand = (info: string) => ({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(), info: text.encode(info) });
|
||||
const hash = await crypto.subtle.deriveBits(expand('swarm'), master, 160);
|
||||
const key = await crypto.subtle.deriveKey(expand('proof'), master, { name: 'HMAC', hash: 'SHA-256' }, false, [
|
||||
'sign',
|
||||
'verify',
|
||||
]);
|
||||
return { hash: String.fromCharCode(...new Uint8Array(hash)), key };
|
||||
}
|
||||
|
||||
function announce(ws: WebSocket, hash: string, peerId: string, params: object) {
|
||||
@@ -206,11 +219,58 @@ function securityCheck(pc: RTCPeerConnection) {
|
||||
return { local: short(pc.localDescription?.sdp), remote: short(pc.remoteDescription?.sdp) };
|
||||
}
|
||||
|
||||
// checked resolves once the user confirmed the codes. Both sides wait for it: the sender sends nothing
|
||||
// to a man in the middle, the receiver accepts no file from one. Until the transfer starts, which
|
||||
// needs both confirmations, a rejected check, a peer that left or end closes the connection and calls
|
||||
// next: tracker signaling goes on with another peer. Without next, as in the manual exchange, the
|
||||
// session is over and the reason is an error. From start on, sendFile and receiveFile handle a loss.
|
||||
// Every fingerprint the SDP names, in full: one added beside the real one changes the result too.
|
||||
// Browsers may move them between session and media level, so each counts once.
|
||||
const fingerprints = (sdp: string) =>
|
||||
[...new Set([...sdp.matchAll(/^a=fingerprint:(.+)$/gim)].map(([, line]) => line!.trim().toLowerCase()))].sort();
|
||||
|
||||
// The security check of tracker signaling, resolves once the peer proved the code. Each side signs its
|
||||
// role, its SDP type, and the fingerprints of both certificates as it sees them. The peer checks that
|
||||
// against its own view. An interposer has its own certificate towards each side and can't sign for it
|
||||
// without the code, neither can a peer that found the swarm some other way. One that sends no proof
|
||||
// within PROOF_TIMEOUT or a wrong one ends the connection.
|
||||
function prove(pc: RTCPeerConnection, channel: RTCDataChannel, key: CryptoKey, end: (reason: string) => void) {
|
||||
const local = pc.localDescription!;
|
||||
const remote = pc.remoteDescription!;
|
||||
const statement = (type: string, own: string, peer: string) =>
|
||||
new TextEncoder().encode(JSON.stringify([type, fingerprints(own), fingerprints(peer)]));
|
||||
const send = async () => {
|
||||
const proof = await crypto.subtle.sign('HMAC', key, statement(local.type, local.sdp, remote.sdp));
|
||||
if (channel.readyState !== 'open') return;
|
||||
channel.send(JSON.stringify({ proof: btoa(String.fromCharCode(...new Uint8Array(proof))) }));
|
||||
};
|
||||
if (channel.readyState === 'open') void send();
|
||||
else channel.addEventListener('open', () => void send(), { once: true });
|
||||
|
||||
return new Promise<void>((resolve) => {
|
||||
const timeout = setTimeout(() => end('the peer proved no code'), PROOF_TIMEOUT);
|
||||
const check = async (event: MessageEvent) => {
|
||||
const proof = parse(event.data)?.proof;
|
||||
if (typeof proof !== 'string') return;
|
||||
// Registered before sendFile and receiveFile, which must not see it: Chromium can verify before
|
||||
// the next listener runs, the receiver would take the proof for the sender's offer then.
|
||||
event.stopImmediatePropagation();
|
||||
channel.removeEventListener('message', check);
|
||||
clearTimeout(timeout);
|
||||
// atob throws on what isn't base64.
|
||||
let valid = false;
|
||||
try {
|
||||
const signature = Uint8Array.from(atob(proof), (char) => char.charCodeAt(0));
|
||||
valid = await crypto.subtle.verify('HMAC', key, signature, statement(remote.type, remote.sdp, local.sdp));
|
||||
} catch {}
|
||||
if (valid) resolve();
|
||||
else end('security check failed, the peer does not know the code');
|
||||
};
|
||||
channel.addEventListener('message', check);
|
||||
});
|
||||
}
|
||||
|
||||
// checked resolves once the security check passed: by the user confirming the codes, or with a key
|
||||
// once the peer proved the code. Both sides wait for it: the sender sends nothing to a man in the
|
||||
// middle, the receiver accepts no file from one. Until the transfer starts, which needs both sides to
|
||||
// pass, a failed check, a peer that left or end closes the connection and calls next: tracker
|
||||
// signaling goes on with another peer. Without next, as in the manual exchange, the session is over
|
||||
// and the reason is an error. From start on, sendFile and receiveFile handle a loss.
|
||||
type Handshake = { checked: Promise<void>; start: () => void; end: (reason: string) => void };
|
||||
|
||||
function connected(
|
||||
@@ -219,6 +279,7 @@ function connected(
|
||||
via: string,
|
||||
events: Events,
|
||||
next?: () => void,
|
||||
key?: CryptoKey,
|
||||
): Handshake {
|
||||
events.log(`connected via ${via}`);
|
||||
events.log('waiting for the security check');
|
||||
@@ -238,9 +299,11 @@ function connected(
|
||||
if (pc.connectionState === 'failed') end('peer left before the transfer');
|
||||
});
|
||||
return {
|
||||
checked: new Promise((resolve) =>
|
||||
events.check({ ...securityCheck(pc), confirm: resolve, reject: () => end('security check failed') }),
|
||||
),
|
||||
checked: key
|
||||
? prove(pc, channel, key, end).then(() => events.log('security check passed'))
|
||||
: new Promise((resolve) =>
|
||||
events.check({ ...securityCheck(pc), confirm: resolve, reject: () => end('security check failed') }),
|
||||
),
|
||||
start: () => (done = true),
|
||||
end,
|
||||
};
|
||||
@@ -663,14 +726,14 @@ function noTracker(trackers: (Tracker | undefined)[]) {
|
||||
}
|
||||
|
||||
// Tracker signaling (optional): sender joins the swarm on every tracker and answers one offer at a
|
||||
// time. Until a receiver passed the security check, the next one gets its turn: a peer that guessed
|
||||
// the code, or got the same one by chance, doesn't end the share. Neither does an offer that can't be
|
||||
// answered or never connects. Once the download started the share is used up, the trackers go. After
|
||||
// time. Until a receiver proved the code, the next one gets its turn: a peer that found the swarm
|
||||
// without it doesn't end the share. Neither does an offer that can't be answered, never connects or
|
||||
// proves nothing. Once the download started the share is used up, the trackers go. After
|
||||
// TRACKER_WAIT they go as well, a receiver connected by then still gets its turn.
|
||||
export async function sendViaTracker(file: File, events: Events, signal: AbortSignal) {
|
||||
events = live(events, signal);
|
||||
const code = randomCode();
|
||||
const hash = await infoHash(code);
|
||||
const { hash, key } = await secrets(code);
|
||||
const peerId = randomBinary(20);
|
||||
const trackers: Tracker[] = [];
|
||||
let busy = false;
|
||||
@@ -726,7 +789,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
const handshake = connected(pc, channel, url, events, next);
|
||||
const handshake = connected(pc, channel, url, events, next, key);
|
||||
const start = () => {
|
||||
handshake.start();
|
||||
shared = true;
|
||||
@@ -789,7 +852,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
||||
export async function receiveViaTracker(code: string, events: ReceiveEvents, signal: AbortSignal) {
|
||||
events = live(events, signal);
|
||||
await downloadsReady();
|
||||
const hash = await infoHash(code.trim());
|
||||
const { hash, key } = await secrets(code.trim());
|
||||
if (signal.aborted) return;
|
||||
const peerId = randomBinary(20);
|
||||
// The current offer per tracker, its socket only until the answer came. lost: the socket closed
|
||||
@@ -843,7 +906,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
clearTimeout(timeout);
|
||||
if (isConnected || started) return pc.close();
|
||||
isConnected = true;
|
||||
const handshake = connected(pc, channel, url, events, next);
|
||||
const handshake = connected(pc, channel, url, events, next, key);
|
||||
const start = () => {
|
||||
handshake.start();
|
||||
started = true;
|
||||
|
||||
Reference in new issue
Block a user