taper / server /test-tor.js
abr00kx's picture
Upload Taper: hardened ephemeral E2EE messaging protocol (Matrix hard fork) (part 4)
b855ced verified
Raw History Blame Contribute Delete
7.92 kB
// Tor transport test: two servers federate through a SOCKS5 proxy that
// stands in for Tor, using made-up onion addresses that only the proxy can
// "resolve". Checks stream isolation, that nothing bypasses the proxy, and
// the startup rules. `npm test` runs it; test-tor-live.js uses real Tor.
import net from 'node:net';
import { spawn, spawnSync } from 'node:child_process';
import { randomBytes } from 'node:crypto';
import assert from 'node:assert/strict';
import { socksConnect } from './socks.js';
import { Client } from './test-client.js';
const BASE = 24000 + Math.floor(Math.random() * 1000);
const onion = (c) => `${c.repeat(56)}.onion`;
const A = { name: 'a.test', port: BASE, onion: onion('a') };
const B = { name: 'b.test', port: BASE + 1, onion: onion('b') };
const FED = '/_taper/federation/v1';
// A SOCKS5 server (RFC 1928/1929) that requires username/password, records
// each CONNECT, and maps onion names to local ports. Anything else fails
// the way Tor fails for an unknown onion service (0xF0).
function fakeTor(routes) {
const log = [];
const server = net.createServer((sock) => {
let buf = Buffer.alloc(0);
let step = 'greeting';
let username = null;
sock.on('error', () => {});
sock.on('data', function onData(chunk) {
buf = Buffer.concat([buf, chunk]);
if (step === 'greeting' && buf.length >= 2 && buf.length >= 2 + buf[1]) {
const methods = [...buf.subarray(2, 2 + buf[1])];
buf = buf.subarray(2 + buf[1]);
if (!methods.includes(0x02)) { sock.end(Buffer.from([0x05, 0xff])); return; }
sock.write(Buffer.from([0x05, 0x02]));
step = 'auth';
}
if (step === 'auth' && buf.length >= 2 && buf.length >= 3 + buf[1] && buf.length >= 3 + buf[1] + buf[2 + buf[1]]) {
const ulen = buf[1];
username = buf.subarray(2, 2 + ulen).toString();
const plen = buf[2 + ulen];
buf = buf.subarray(3 + ulen + plen);
sock.write(Buffer.from([0x01, 0x00]));
step = 'connect';
}
if (step === 'connect' && buf.length >= 5 && buf.length >= 7 + buf[4]) {
const atyp = buf[3];
const host = atyp === 0x03 ? buf.subarray(5, 5 + buf[4]).toString() : `(address type ${atyp})`;
const port = buf.readUInt16BE(5 + buf[4]);
log.push({ atyp, host, port, username });
const rest = buf.subarray(7 + buf[4]);
step = 'done';
sock.removeListener('data', onData);
const target = routes[host];
if (atyp !== 0x03 || !target) { sock.end(Buffer.from([0x05, 0xf0, 0x00, 0x01, 0, 0, 0, 0, 0, 0])); return; }
const up = net.connect(target, '127.0.0.1', () => {
sock.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0]));
if (rest.length) up.write(rest);
sock.pipe(up).pipe(sock);
});
up.on('error', () => sock.destroy());
}
});
});
return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve({ server, log, port: server.address().port })));
}
function startServer(self, peer, socksPort) {
const proc = spawn(process.execPath, ['index.js'], {
env: {
...process.env, PORT: String(self.port), TAPER_SERVER_NAME: self.name, TAPER_REGISTER_POW_BITS: '8',
TAPER_FEDERATION_PEERS: `${peer.name}=ws://${peer.onion}${FED}`, TAPER_TOR_SOCKS: `127.0.0.1:${socksPort}`,
},
stdio: ['ignore', 'pipe', 'inherit'],
});
return new Promise((resolve, reject) => {
proc.stdout.on('data', (d) => { if (String(d).includes('Taper gateway on')) resolve(proc); });
proc.once('exit', (code) => reject(new Error(`${self.name} exited with ${code}`)));
});
}
const refusal = (env) => spawnSync(process.execPath, ['index.js'], { env: { ...process.env, PORT: String(BASE + 5), ...env }, encoding: 'utf8', timeout: 10_000 });
async function main() {
const results = [];
const test = async (name, fn) => {
try { await fn(); results.push(['PASS', name]); } catch (e) { results.push(['FAIL', name, e.stack ?? String(e)]); }
};
await test('an onion peer without a Tor SOCKS port is refused at startup', async () => {
const r = refusal({ TAPER_FEDERATION_PEERS: `b.test=ws://${B.onion}${FED}` });
assert.equal(r.status, 1);
assert.match(r.stderr, /TAPER_TOR_SOCKS/);
});
await test('plain ws:// to a clearnet peer is refused at startup (Tor exits could read it)', async () => {
const r = refusal({ TAPER_FEDERATION_PEERS: `b.test=ws://b.example.org${FED}`, TAPER_TOR_SOCKS: '127.0.0.1:9' });
assert.equal(r.status, 1);
assert.match(r.stderr, /only allowed for \.onion and loopback/);
});
await test('socksConnect reports Tor onion errors and never resolves names itself', async () => {
const tor = await fakeTor({});
try {
await assert.rejects(socksConnect({ proxy: { host: '127.0.0.1', port: tor.port }, host: onion('c'), port: 80, username: 'u', password: 'p' }),
/onion service descriptor not found/);
assert.deepEqual(tor.log.map((e) => [e.atyp, e.host]), [[0x03, onion('c')]]);
} finally {
tor.server.close();
}
});
const tor = await fakeTor({ [A.onion]: A.port, [B.onion]: B.port });
const servers = [await startServer(A, B, tor.port), await startServer(B, A, tor.port)];
try {
await test('two servers federate through the proxy using onion addresses', async () => {
const alice = await Client.connectTo(`ws://127.0.0.1:${A.port}/_taper/gateway/v1`);
const bob = await Client.connectTo(`ws://127.0.0.1:${B.port}/_taper/gateway/v1`);
const aAuth = await alice.register('alice', 'alice-password-1');
const bAuth = await bob.register('bob', 'bob-password-1');
await alice.identify(aAuth.access_token);
await bob.identify(bAuth.access_token);
const { room_id } = await alice.call('t.room.create', {});
await alice.call('t.room.invite', { room_id, user_id: bAuth.user_id });
await bob.next((f) => f.type === 't.room.invite', 15_000);
await bob.call('t.room.join', { room_id });
await bob.next((f) => f.type === 't.room.joined', 15_000);
const content = { algorithm: 't.megolm.v1.aes-sha2', ciphertext: 'b25pb24', session_id: 's', binding: randomBytes(16).toString('base64url') };
const { event_id } = await bob.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: 't1', content });
await alice.next((f) => f.type === 't.room.event' && f.body.event.event_id === event_id, 15_000);
alice.close();
bob.close();
});
await test('every federation connection went through the proxy, by name, isolated per peer', async () => {
assert.ok(tor.log.length >= 2, `only ${tor.log.length} proxied connections`);
for (const e of tor.log) {
assert.equal(e.atyp, 0x03, 'a server sent an IP address instead of a name');
assert.ok([A.onion, B.onion].includes(e.host), `unexpected destination ${e.host}`);
}
// a.test's connections to b.test, and b.test's to a.test, use their own isolation keys.
assert.ok(tor.log.filter((e) => e.host === B.onion).every((e) => e.username === 'taper:b.test'));
assert.ok(tor.log.filter((e) => e.host === A.onion).every((e) => e.username === 'taper:a.test'));
// Both the key document fetch and the socket went through it.
assert.ok(tor.log.filter((e) => e.host === B.onion).length >= 2, 'expected key fetch and federation socket via Tor');
});
} finally {
for (const s of servers) s.kill('SIGTERM');
tor.server.close();
}
for (const [status, name, msg] of results) console.log(`${status} ${name}${msg ? `\n ${msg.split('\n').slice(0, 5).join('\n ')}` : ''}`);
const failed = results.filter((r) => r[0] === 'FAIL').length;
console.log(`\n${results.length - failed}/${results.length} passed`);
process.exit(failed ? 1 : 0);
}
main().catch((e) => { console.error(e); process.exit(1); });