File size: 14,058 Bytes
b855ced
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cce9364
 
 
 
 
 
 
 
 
 
b855ced
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cce9364
b855ced
 
cce9364
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
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
// Dead man's switch: destroy everything this server holds and take it out of
// service. Documented for operators in docs/dead-mans-switch.md.
//
// Four ways to set it off, one way to carry it out:
//
//   command    an operator on the machine runs `admin.js decommission <server name>`
//   quorum     M of N operators each send a signed `decommission` order
//   dead hand  no operator has checked in for TAPER_DMS_DEADHAND_MS, and nobody
//              did during the grace period that followed
//   duress     an operator checks in with their duress key: the check-in looks
//              accepted, and the wipe follows after TAPER_DMS_DURESS_DELAY_MS
//
// The wipe is crypto-shredding first (every key overwritten and deleted, so
// any copy of the data, backups included, is unreadable), then the data files
// themselves, then any extra paths the operator listed (TLS key, onion
// service keys). It leaves a DECOMMISSIONED marker so the server won't start
// again on an empty database as if nothing happened.
//
// Signed orders use Ed25519 from node:crypto. An order is:
//   taper-dms-v1 \n <server name> \n <action> \n <time, ms> \n <random nonce>
// and is accepted only within ORDER_MAX_AGE_MS of its time, once.

import { generateKeyPairSync, createPrivateKey, createPublicKey, sign, verify, randomBytes } from 'node:crypto';
import {
  existsSync, lstatSync, openSync, writeSync, fsyncSync, closeSync, unlinkSync, readdirSync, rmdirSync,
  readFileSync, writeFileSync, renameSync, accessSync, constants as fsc,
} from 'node:fs';
import { join, dirname } from 'node:path';

export const MARKER = 'DECOMMISSIONED';
export const ORDER_MAX_AGE_MS = 10 * 60_000;
const ACTIONS = new Set(['checkin', 'decommission']);
const b64u = (buf) => Buffer.from(buf).toString('base64url');

// --- keys and orders ---------------------------------------------------------

/** A new operator key pair: the private key as PEM, the public key as base64url (raw 32 bytes). */
export function generateOperatorKey() {
  const { privateKey, publicKey } = generateKeyPairSync('ed25519');
  const raw = publicKey.export({ format: 'jwk' }).x;
  return { privatePem: privateKey.export({ format: 'pem', type: 'pkcs8' }), publicKey: raw };
}

const publicFromRaw = (x) => createPublicKey({ key: { kty: 'OKP', crv: 'Ed25519', x }, format: 'jwk' });

/**
 * The operators file: one operator per line,
 *   <name> <public key> [<duress public key>]
 * Blank lines and lines starting with # are ignored.
 */
export function parseOperators(text) {
  const ops = new Map(); // public key -> { name, duress }
  const names = new Set();
  for (const [i, line] of text.split('\n').entries()) {
    const t = line.trim();
    if (!t || t.startsWith('#')) continue;
    const [name, key, duressKey, extra] = t.split(/\s+/);
    if (!key || extra) throw new Error(`operators file, line ${i + 1}: expected "<name> <public key> [<duress public key>]"`);
    if (names.has(name)) throw new Error(`operators file, line ${i + 1}: ${name} is listed twice`);
    names.add(name);
    for (const [k, duress] of [[key, false], [duressKey, true]]) {
      if (!k) continue;
      if (!/^[A-Za-z0-9_-]{43}$/.test(k)) throw new Error(`operators file, line ${i + 1}: not an Ed25519 public key`);
      if (ops.has(k)) throw new Error(`operators file, line ${i + 1}: a key is listed twice`);
      publicFromRaw(k); // throws if it isn't a valid point
      ops.set(k, { name, duress });
    }
  }
  return ops;
}

/** Sign an order. The result is one opaque string to hand to the server. */
export function signOrder({ privatePem, server, action, ts = Date.now(), nonce = b64u(randomBytes(16)) }) {
  if (!ACTIONS.has(action)) throw new Error(`action is one of: ${[...ACTIONS].join(', ')}`);
  const key = createPrivateKey(privatePem);
  const publicKey = createPublicKey(key).export({ format: 'jwk' }).x;
  const message = `taper-dms-v1\n${server}\n${action}\n${ts}\n${nonce}`;
  return b64u(JSON.stringify({ k: publicKey, a: action, t: ts, n: nonce, s: b64u(sign(null, Buffer.from(message), key)) }));
}

/**
 * Check an order. Returns { name, duress, action, nonce } or throws.
 * Does not remember nonces: the switch does that.
 */
export function verifyOrder(token, { operators, server, now = Date.now() }) {
  let o;
  try { o = JSON.parse(Buffer.from(String(token), 'base64url').toString('utf8')); } catch { throw new Error('Not an order'); }
  if (!o || typeof o !== 'object' || typeof o.k !== 'string' || typeof o.a !== 'string' || !Number.isSafeInteger(o.t)
      || typeof o.n !== 'string' || !/^[A-Za-z0-9_-]{16,64}$/.test(o.n) || typeof o.s !== 'string') throw new Error('Not an order');
  if (!ACTIONS.has(o.a)) throw new Error('Unknown action');
  const op = operators.get(o.k);
  if (!op) throw new Error('Unknown key');
  if (Math.abs(now - o.t) > ORDER_MAX_AGE_MS) throw new Error('Order too old or from the future');
  const message = `taper-dms-v1\n${server}\n${o.a}\n${o.t}\n${o.n}`;
  if (!verify(null, Buffer.from(message), publicFromRaw(o.k), Buffer.from(o.s, 'base64url'))) throw new Error('Bad signature');
  return { name: op.name, duress: op.duress, action: o.a, nonce: o.n };
}

// --- the wipe ----------------------------------------------------------------

/** Overwrite a file with random bytes, flush it to disk and delete it. */
function shredFile(path) {
  const size = lstatSync(path).size;
  const fd = openSync(path, 'r+');
  try {
    const chunk = randomBytes(Math.min(size, 1 << 20) || 1);
    for (let off = 0; off < size; off += chunk.length) writeSync(fd, chunk, 0, Math.min(chunk.length, size - off), off);
    fsyncSync(fd);
  } finally { closeSync(fd); }
  unlinkSync(path);
}

/** Shred a file, or everything in a directory and then the directory. Symbolic links are removed, never followed. */
function shredPath(path, destroyed, keepDir = false) {
  let st;
  try { st = lstatSync(path); } catch { return; }
  try {
    if (st.isDirectory()) {
      for (const name of readdirSync(path)) shredPath(join(path, name), destroyed); // each entry fails alone
      if (!keepDir) rmdirSync(path);
      destroyed.push(`${path}/`);
      return;
    }
    if (st.isFile()) { try { shredFile(path); } catch { unlinkSync(path); } } else unlinkSync(path);
    destroyed.push(path);
  } catch { /* one failure must not stop the rest of the wipe */ }
}

/**
 * What a wipe would destroy, without touching it, and what it couldn't
 * (deleting needs write access to the containing directory).
 */
export function plan({ dataDir, keyDir, extraPaths = [] }) {
  const list = [];
  const blocked = [];
  const writable = (p) => { try { accessSync(p, fsc.W_OK); return true; } catch { return false; } };
  const walk = (p) => {
    let st;
    try { st = lstatSync(p); } catch { return; }
    if (!writable(dirname(p)) || (st.isFile() && !writable(p))) blocked.push(p);
    if (st.isDirectory() && !st.isSymbolicLink()) {
      try { for (const n of readdirSync(p)) walk(join(p, n)); } catch { blocked.push(p); }
    } else list.push(p);
  };
  // Keys first: once they are gone the data is unreadable, even if the rest is interrupted.
  for (const p of [keyDir, dataDir]) if (p) walk(p);
  for (const p of extraPaths) { if (existsSync(p)) walk(p); else blocked.push(`${p} (does not exist)`); }
  return { list, blocked };
}

/**
 * Destroy everything. Order matters: keys, then data, then extra paths. Each
 * step goes on if an earlier one failed, and the errors are returned.
 */
export function wipe({ dataDir, keyDir, extraPaths = [], before = () => {} }) {
  const destroyed = [];
  const errors = [];
  const attempt = (fn) => { try { fn(); } catch (e) { errors.push(e.message); } };
  attempt(before); // close the database, drop connections
  if (keyDir) attempt(() => shredPath(keyDir, destroyed, true));
  if (dataDir) attempt(() => shredPath(dataDir, destroyed, true));
  for (const p of extraPaths) attempt(() => shredPath(p, destroyed));
  if (dataDir) {
    attempt(() => writeFileSync(join(dataDir, MARKER), `This Taper server was decommissioned at ${new Date().toISOString()}.\n`, { mode: 0o600 }));
  }
  return { destroyed, errors };
}

export const isDecommissioned = (dataDir) => Boolean(dataDir) && existsSync(join(dataDir, MARKER));

// --- the switch --------------------------------------------------------------

export class DeadMansSwitch {
  /**
   * @param server        server name (part of every signed order)
   * @param operators     Map from parseOperators (may be empty: command mode only)
   * @param quorum        signed decommission orders needed (M of N)
   * @param windowMs      how long collected orders count towards the quorum
   * @param deadhandMs    no check-in for this long starts the grace period (0: off)
   * @param graceMs       grace period after a missed deadline, before the wipe
   * @param duressDelayMs time between a duress check-in and the wipe
   * @param statePath     where the last check-in is kept (in the key directory)
   * @param onWipe        (reason) => void: carries out the wipe
   */
  constructor({ server, operators = new Map(), quorum = 1, windowMs = 3_600_000, deadhandMs = 0, graceMs = 86_400_000,
    duressDelayMs = 15 * 60_000, statePath = null, onWipe, log = console.log, now = Date.now }) {
    const names = new Set([...operators.values()].map((o) => o.name));
    if (names.size && (quorum < 1 || quorum > names.size)) throw new Error(`TAPER_DMS_QUORUM must be from 1 to ${names.size} (the number of operators)`);
    if (deadhandMs && !names.size) throw new Error('The dead hand needs operators who can check in (TAPER_DMS_OPERATORS)');
    Object.assign(this, { server, operators, quorum, windowMs, deadhandMs, graceMs, duressDelayMs, statePath, onWipe, log, now });
    this.votes = new Map(); // operator name -> time of their decommission order
    this.seen = new Map(); // nonce -> time, to refuse replays
    this.fired = false;
    this.duressTimer = null;
    this.lastCheckin = this.loadState() ?? now();
    this.saveState();
  }

  loadState() {
    if (!this.statePath || !existsSync(this.statePath)) return null;
    try { const ts = JSON.parse(readFileSync(this.statePath, 'utf8')).last_checkin_ts; return Number.isSafeInteger(ts) ? ts : null; } catch { return null; }
  }

  saveState() {
    if (!this.statePath) return;
    const tmp = `${this.statePath}.tmp`;
    writeFileSync(tmp, JSON.stringify({ last_checkin_ts: this.lastCheckin }), { mode: 0o600 });
    renameSync(tmp, this.statePath);
  }

  fire(reason) {
    if (this.fired) return;
    this.fired = true;
    this.stop();
    this.log(`dead man's switch: ${reason}; wiping`);
    this.onWipe(reason);
  }

  checkin() {
    this.lastCheckin = this.now();
    this.saveState();
  }

  /** The command mode: an operator on the machine, who must type the server name. */
  command(confirm) {
    if (confirm !== this.server) throw new Error(`To decommission, confirm with the server name: decommission ${this.server}`);
    setImmediate(() => this.fire('decommissioned by command'));
    return { decommissioning: true };
  }

  /**
   * A signed order, from the admin socket or the network. The answer to a
   * duress check-in is the same as to a real one.
   */
  submit(token) {
    const t = this.now();
    const order = verifyOrder(token, { operators: this.operators, server: this.server, now: t });
    for (const [n, ts] of this.seen) if (t - ts > 2 * ORDER_MAX_AGE_MS) this.seen.delete(n);
    if (this.seen.has(order.nonce)) throw new Error('Order already used');
    this.seen.set(order.nonce, t);

    if (order.duress) {
      // Looks like the action was accepted; the wipe follows, and no check-in can stop it.
      if (!this.duressTimer && !this.fired) {
        this.duressTimer = setTimeout(() => this.fire('duress'), this.duressDelayMs);
        this.duressTimer.unref?.();
      }
      if (order.action !== 'checkin') return { votes: this.voteCount(t), quorum: this.quorum };
    }
    if (order.action === 'checkin') {
      this.checkin(); // a duress check-in records one too, so the state file can't tell them apart
      return { checked_in: true };
    }
    this.votes.set(order.name, t);
    const votes = this.voteCount(t);
    this.log(`dead man's switch: decommission order ${votes} of ${this.quorum}`);
    if (votes >= this.quorum) setImmediate(() => this.fire(`decommissioned by ${votes} of ${this.operatorCount()} operators`));
    return { votes, quorum: this.quorum };
  }

  operatorCount() { return new Set([...this.operators.values()].map((o) => o.name)).size; }

  voteCount(t = this.now()) {
    for (const [name, ts] of this.votes) if (t - ts > this.windowMs) this.votes.delete(name);
    return this.votes.size;
  }

  /** The dead hand's clock. Call often (start() does, every checkMs). */
  tick() {
    if (this.fired || !this.deadhandMs) return;
    const late = this.now() - this.lastCheckin - this.deadhandMs;
    if (late >= this.graceMs) this.fire('no operator checked in');
    else if (late >= 0 && !this.warned) { this.warned = true; this.log(`dead man's switch: no check-in for ${Math.round((this.deadhandMs + late) / 3_600_000)} h; wiping in ${Math.round((this.graceMs - late) / 60_000)} min unless an operator checks in`); }
    else if (late < 0) this.warned = false;
  }

  status() {
    const t = this.now();
    return {
      operators: this.operatorCount(),
      quorum: this.quorum,
      decommission_votes: this.voteCount(t),
      dead_hand: this.deadhandMs
        ? { last_checkin: new Date(this.lastCheckin).toISOString(), deadline: new Date(this.lastCheckin + this.deadhandMs).toISOString(), wipe_at: new Date(this.lastCheckin + this.deadhandMs + this.graceMs).toISOString() }
        : 'off',
      // Deliberately absent: whether a duress wipe is pending. Whoever can run this command may be the one applying the pressure.
    };
  }

  start(checkMs = 60_000) {
    this.tick();
    this.timer = setInterval(() => this.tick(), checkMs);
    this.timer.unref?.();
  }

  stop() { clearInterval(this.timer); }
}