File size: 9,188 Bytes
b855ced
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Does the backend ever hold plaintext? Two users chat with unique marker
// strings (message text, a room name, a file, their passwords, the Megolm
// session keys they back up). Then the server's data directory, its key
// directory, its logs and its live process memory are searched for every
// marker. The server must hold none of them, while the same search must find
// a value it does hold (a control, so an empty search can't pass).

import { spawn } from 'node:child_process';
import { mkdtempSync, rmSync, readdirSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import assert from 'node:assert/strict';
import { randomBytes } from 'node:crypto';
import * as sdk from '../client/node_modules/@matrix-org/matrix-sdk-crypto-wasm/node.mjs';
import { TaperCrypto, deriveBackupKey, sealBackup } from '../client/crypto.js';
import { encryptFile, upload } from '../client/media.js';
import { Client } from './test-client.js';
import { scanFiles, scanMemory } from './plaintext-scan.js';

const PORT = 25000 + Math.floor(Math.random() * 900);
const URL_ = `ws://127.0.0.1:${PORT}/_taper/gateway/v1`;
const mark = (what) => `TAPER-${what}-${randomBytes(9).toString('hex')}`;
const M = {
  aliceMsg: mark('ALICE-MESSAGE'), bobMsg: mark('BOB-MESSAGE'), roomName: mark('ROOM-NAME'),
  file: mark('FILE-CONTENT'), alicePw: mark('ALICE-PASSWORD'), bobPw: mark('BOB-PASSWORD'),
};
const txn = () => randomBytes(8).toString('hex');

const dir = mkdtempSync(join(tmpdir(), 'taper-backend-'));
const dataDir = join(dir, 'data');
const keyDir = join(dir, 'keys');
let log = '';
const server = spawn(process.execPath, ['index.js'], {
  env: { ...process.env, PORT: String(PORT), TAPER_REGISTER_POW_BITS: '8', TAPER_DATA_DIR: dataDir, TAPER_KEY_DIR: keyDir },
  stdio: ['ignore', 'pipe', 'pipe'],
});
server.stdout.on('data', (d) => { log += d; });
server.stderr.on('data', (d) => { log += d; });
await new Promise((resolve) => { const t = setInterval(() => { if (log.includes('Taper gateway')) { clearInterval(t); resolve(); } }, 50); });
await sdk.initAsync();

async function user(name, password) {
  const c = await Client.connectTo(URL_);
  const auth = await c.register(name, password);
  await c.identify(auth.access_token);
  const lc = await TaperCrypto.create(sdk, { userId: auth.user_id, deviceId: auth.device_id, request: (m, b) => c.call(m, b) });
  assert.equal(await lc.ensureCrossSigning({ exportKey: auth.exportKey }), 'created');
  const pending = [];
  c.handlers.push((f) => {
    if (f.op !== 'dispatch') return false;
    if (f.type === 't.to_device') pending.push(lc.receive({ toDevice: f.body.events }));
    else if (f.type === 't.device_lists') pending.push(lc.receive({ changed: f.body.changed }));
    else if (f.type === 't.keys.counts') pending.push(lc.receive({ oneTimeKeyCounts: f.body.one_time_key_counts }));
    else return false;
    return true;
  });
  return { c, lc, id: auth.user_id, exportKey: auth.exportKey, settle: () => Promise.all(pending.splice(0)) };
}

const results = [];
const test = async (name, fn) => {
  try { await fn(); results.push(['PASS', name]); } catch (e) { results.push(['FAIL', name, e.message || String(e.stack ?? e)]); }
};
const evidence = {};

try {
  const alice = await user('alice', M.alicePw);
  const bob = await user('bob', M.bobPw);
  const members = [alice.id, bob.id];
  const nextEvent = (u, pred) => u.c.next((f) => f.type === 't.room.event' && pred(f.body.event), 8000).then((f) => f.body.event);
  const { room_id } = await alice.c.call('t.room.create', {});
  await alice.c.call('t.room.invite', { room_id, user_id: bob.id });
  await bob.c.call('t.room.join', { room_id });

  await test('messages, a room name and a file are sent and read by the other side', async () => {
    const name = await alice.lc.encryptState(room_id, members, 't.room.name', '', { name: M.roomName });
    await alice.c.call('t.room.state.set', { room_id, ...name });
    const a = await alice.lc.encrypt(room_id, members, 't.room.message', { msgtype: 't.text', body: M.aliceMsg });
    const sent = await alice.c.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: txn(), content: a });
    const ev = await nextEvent(bob, (e) => e.event_id === sent.event_id);
    await bob.settle();
    assert.equal((await bob.lc.decrypt(ev)).content.body, M.aliceMsg);
    evidence.wireEvent = ev;
    const b = await bob.lc.encrypt(room_id, members, 't.room.message', { msgtype: 't.text', body: M.bobMsg });
    const reply = await bob.c.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: txn(), content: b });
    await alice.settle();
    assert.equal((await alice.lc.decrypt(await nextEvent(alice, (e) => e.event_id === reply.event_id))).content.body, M.bobMsg);
    // A file with the marker inside.
    const plain = new Uint8Array(70_000);
    plain.set(new TextEncoder().encode(M.file), 5000);
    const enc = await encryptFile(plain);
    const io = { request: (m, x) => alice.c.call(m, x), sendBinary: (x) => alice.c.sendBinary(x), downloads: alice.c.downloads };
    const uri = await upload(enc.ciphertext, io);
    const fc = await alice.lc.encrypt(room_id, members, 't.room.message', { msgtype: 't.file', body: 'f.bin', file: { ...enc.file, url: uri }, info: { size: plain.length } }, { attachments: [uri] });
    await alice.c.call('t.room.send', { room_id, type: 't.room.encrypted', txn_id: txn(), content: fc });
  });

  let sessionKeys = [];
  await test('the room keys are backed up sealed, so the server holds them only as ciphertext', async () => {
    const { json, ids } = await alice.lc.exportNewRoomKeys(new Set());
    assert.ok(ids.length > 0);
    sessionKeys = JSON.parse(json).map((k) => k.session_key);
    assert.ok(sessionKeys.every((k) => typeof k === 'string' && k.length > 40));
    const key = await deriveBackupKey(alice.exportKey, alice.id);
    const part = `${new Date().toISOString().slice(0, 10)}.0`;
    await alice.c.call('t.backup.put', { part, blob: await sealBackup(key, alice.id, part, { keys: json }) });
  });

  await test('what the server relays and returns is ciphertext', async () => {
    const stored = await bob.c.call('t.room.messages', { room_id, limit: 50 });
    const text = JSON.stringify(stored) + JSON.stringify(evidence.wireEvent);
    for (const [what, m] of Object.entries(M)) assert.ok(!text.includes(m), `${what} is readable in what the server returns`);
    const enc = stored.chunk.filter((e) => e.type === 't.room.encrypted');
    assert.ok(enc.length >= 4, 'expected the messages, the file message and the room name');
    assert.ok(enc.every((e) => e.content.algorithm === 't.megolm.v1.aes-sha2' && typeof e.content.ciphertext === 'string'));
  });

  // Let the server finish writing before looking.
  await new Promise((r) => setTimeout(r, 500));
  const secrets = [...Object.values(M), ...sessionKeys];

  await test('the data directory, key directory and logs hold none of it', () => {
    const files = readdirSync(dataDir);
    assert.ok(files.includes('taper.db'), `no database was written: ${files}`);
    const hits = scanFiles([dataDir, keyDir], secrets);
    assert.deepEqual(hits, [], `found in files: ${JSON.stringify(hits)}`);
    for (const s of secrets) assert.ok(!log.includes(s), 'a secret reached the server log');
  });

  await test('neither does the running server process (its memory was searched)', () => {
    // The control: a value the server certainly holds in memory is found by the same search.
    const control = scanMemory(server.pid, ['@alice:localhost', 't.megolm.v1.aes-sha2'].map((s) => s.padEnd(12, ' ').trimEnd()));
    assert.ok(control.bytes > 20_000_000, `only read ${control.bytes} bytes of memory`);
    assert.ok(control.hits.length >= 1, 'the control search found nothing, so the memory search proves nothing');
    const { hits } = scanMemory(server.pid, secrets);
    assert.deepEqual(hits, [], `found in server memory: ${JSON.stringify(hits)}`);
  });

  await test('the search itself works: a marker in a file is found, in any encoding', async () => {
    const { writeFileSync } = await import('node:fs');
    const probe = mark('PROBE');
    const d = join(dir, 'probe');
    const { mkdirSync } = await import('node:fs');
    mkdirSync(d);
    writeFileSync(join(d, 'raw'), `xx${probe}yy`);
    writeFileSync(join(d, 'b64'), Buffer.from(`q${probe}`).toString('base64'));
    writeFileSync(join(d, 'b64url'), Buffer.from(`zz${probe}`).toString('base64url'));
    writeFileSync(join(d, 'utf16'), Buffer.from(probe, 'utf16le'));
    const files = new Set(scanFiles([d], [probe]).map((h) => h.file.split('/').pop()));
    assert.deepEqual([...files].sort(), ['b64', 'b64url', 'raw', 'utf16']);
  });

  alice.c.close();
  bob.c.close();
} finally {
  server.kill('SIGTERM');
  await new Promise((r) => server.once('exit', r));
  rmSync(dir, { recursive: true, force: true });
}

let failed = 0;
for (const [status, name, detail] of results) {
  console.log(`${status}  ${name}${detail ? `\n      ${detail}` : ''}`);
  if (status === 'FAIL') failed++;
}
console.log(`\n${results.length - failed}/${results.length} passed`);
process.exit(failed ? 1 : 0);