taper / server /store.js
abr00kx's picture
Round 2 security fixes (part 4)
cce9364 verified
Raw History Blame Contribute Delete
8.62 kB
// Persistent storage with crypto-shredding (Cryptography and Transport,
// "Encryption at rest").
//
// - Plain records (accounts, hashed tokens, public keys) go in `records`.
// - Message data (events, queued to-device messages) goes in `sealed`,
// encrypted with AES-256-GCM under a key for the period it belongs to.
// - Period keys live in a separate directory, never inside the data
// directory, so a copy of the database alone is unreadable.
// - When everything a key protects has expired, the key is overwritten and
// deleted. Every copy of that data, including old backups and SQLite free
// pages, becomes unreadable at the same moment.
//
// Without a data directory the store is disabled and the server is
// memory-only.
import { DatabaseSync } from 'node:sqlite';
import { randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';
import { mkdirSync, readFileSync, writeFileSync, renameSync, readdirSync, unlinkSync, openSync, writeSync, fsyncSync, closeSync, existsSync } from 'node:fs';
import { join, resolve, relative, isAbsolute } from 'node:path';
export class Store {
static SCHEMA_VERSION = 1;
/**
* @param dataDir directory for the SQLite database (falsy: disabled)
* @param keyDir directory for period keys; must not be inside dataDir
* @param retentionMs how long message data may live
* @param periodMs key rotation period (default one day)
*/
constructor({ dataDir, keyDir, retentionMs, periodMs = 86_400_000 }) {
this.enabled = Boolean(dataDir);
this.retentionMs = retentionMs;
this.periodMs = periodMs;
this.keys = new Map(); // period -> Buffer
if (!this.enabled) return;
if (!keyDir) throw new Error('TAPER_KEY_DIR is required when TAPER_DATA_DIR is set');
const data = resolve(dataDir);
const keys = resolve(keyDir);
const rel = relative(data, keys);
if (rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))) {
throw new Error('TAPER_KEY_DIR must not be the data directory or inside it: keys must not be stored with the data they protect');
}
mkdirSync(data, { recursive: true, mode: 0o700 });
mkdirSync(keys, { recursive: true, mode: 0o700 });
this.keyDir = keys;
this.db = new DatabaseSync(join(data, 'taper.db'));
// The database's format. A server that finds a newer one refuses to start
// rather than guess: change this number with every change to the tables.
const version = this.db.prepare('PRAGMA user_version').get().user_version;
if (version > Store.SCHEMA_VERSION) throw new Error(`${join(data, 'taper.db')} was written by a newer Taper (format ${version}); this one understands up to ${Store.SCHEMA_VERSION}`);
this.db.exec(`
PRAGMA journal_mode = WAL;
PRAGMA secure_delete = ON;
CREATE TABLE IF NOT EXISTS records (ns TEXT NOT NULL, k TEXT NOT NULL, v TEXT NOT NULL, PRIMARY KEY (ns, k));
CREATE TABLE IF NOT EXISTS sealed (
ns TEXT NOT NULL, k TEXT NOT NULL, period INTEGER NOT NULL,
iv BLOB NOT NULL, ct BLOB NOT NULL, tag BLOB NOT NULL,
grp TEXT, ord INTEGER, PRIMARY KEY (ns, k));
CREATE INDEX IF NOT EXISTS sealed_period ON sealed (period);
CREATE INDEX IF NOT EXISTS sealed_grp ON sealed (ns, grp, ord);
`);
this.db.exec(`PRAGMA user_version = ${Store.SCHEMA_VERSION}`);
this.q = {
putRecord: this.db.prepare('INSERT OR REPLACE INTO records (ns, k, v) VALUES (?, ?, ?)'),
delRecord: this.db.prepare('DELETE FROM records WHERE ns = ? AND k = ?'),
allRecords: this.db.prepare('SELECT k, v FROM records WHERE ns = ?'),
putSealed: this.db.prepare('INSERT OR REPLACE INTO sealed (ns, k, period, iv, ct, tag, grp, ord) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'),
delSealed: this.db.prepare('DELETE FROM sealed WHERE ns = ? AND k = ?'),
allSealed: this.db.prepare('SELECT k, period, iv, ct, tag, grp, ord FROM sealed WHERE ns = ? ORDER BY grp, ord'),
delPeriodsBefore: this.db.prepare('DELETE FROM sealed WHERE period < ?'),
};
}
period(ts = Date.now()) { return Math.floor(ts / this.periodMs); }
/** Periods before this one are shredded: their data has all expired. Keep one extra period of margin. */
cutoff() { return this.period(Date.now() - this.retentionMs) - 1; }
keyPath(period) { return join(this.keyDir, `${period}.key`); }
/**
* A long-lived secret kept in the key directory (never in the data
* directory), created on first use. Shredding only touches period keys.
* In memory-only mode, a fresh secret per run.
*/
secret(name, create) {
if (!this.enabled) return create();
const path = join(this.keyDir, `${name}.secret`);
if (existsSync(path)) return readFileSync(path, 'utf8');
const value = create();
writeFileSync(path, value, { mode: 0o600, flag: 'wx' });
return value;
}
/** Atomically replace a long-lived secret in the key directory (mode 0600). */
setSecret(name, value) {
if (!this.enabled) return;
const path = join(this.keyDir, `${name}.secret`);
const tmp = join(this.keyDir, `.${name}.${randomBytes(6).toString('hex')}.tmp`);
const fd = openSync(tmp, 'wx', 0o600);
try { writeSync(fd, value); fsyncSync(fd); } finally { closeSync(fd); }
renameSync(tmp, path);
}
/** Flush and truncate the SQLite WAL so deleted plain rows do not linger in it. */
checkpoint() {
if (!this.enabled) return;
try { this.db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch { /* ignore if busy */ }
}
key(period) {
let k = this.keys.get(period);
if (k) return k;
const path = this.keyPath(period);
if (existsSync(path)) {
k = readFileSync(path);
} else {
if (period < this.cutoff()) return null; // a key that was, or is due to be, destroyed
k = randomBytes(32);
writeFileSync(path, k, { mode: 0o600, flag: 'wx' });
}
this.keys.set(period, k);
return k;
}
// --- plain records ---------------------------------------------------------
put(ns, k, value) { if (this.enabled) this.q.putRecord.run(ns, k, JSON.stringify(value)); }
del(ns, k) { if (this.enabled) this.q.delRecord.run(ns, k); }
all(ns) { return this.enabled ? this.q.allRecords.all(ns).map((r) => [r.k, JSON.parse(r.v)]) : []; }
// --- sealed (encrypted) records -------------------------------------------
seal(ns, k, value, { period = this.period(), grp = null, ord = null } = {}) {
if (!this.enabled) return;
const key = this.key(period);
if (!key) return; // the period has already been shredded: nothing may be stored under it
const iv = randomBytes(12);
const cipher = createCipheriv('aes-256-gcm', key, iv);
cipher.setAAD(Buffer.from(`${ns}|${k}`));
const ct = Buffer.concat([cipher.update(JSON.stringify(value)), cipher.final()]);
this.q.putSealed.run(ns, k, period, iv, ct, cipher.getAuthTag(), grp, ord);
}
unseal(ns, row) {
const key = this.key(row.period);
if (!key) return null;
try {
const d = createDecipheriv('aes-256-gcm', key, row.iv);
d.setAAD(Buffer.from(`${ns}|${row.k}`));
d.setAuthTag(row.tag);
return JSON.parse(Buffer.concat([d.update(row.ct), d.final()]).toString());
} catch {
return null;
}
}
unsealAll(ns) {
if (!this.enabled) return [];
return this.q.allSealed.all(ns).map((row) => [row.k, this.unseal(ns, row), row]).filter(([, v]) => v !== null);
}
delSealed(ns, k) { if (this.enabled) this.q.delSealed.run(ns, k); }
/**
* Destroy every period key whose data has all expired: overwrite the key
* file with random bytes, flush it, delete it, and drop its rows. Returns
* the destroyed periods.
*/
shred() {
if (!this.enabled) return [];
// A key for period p protects data created up to the end of p, which expires by end(p) + retention.
const cutoff = this.cutoff();
const destroyed = [];
for (const name of readdirSync(this.keyDir)) {
const m = /^(-?\d+)\.key$/.exec(name);
if (!m) continue;
const period = Number(m[1]);
if (period >= cutoff) continue;
const path = this.keyPath(period);
const fd = openSync(path, 'r+');
try { writeSync(fd, randomBytes(32), 0, 32, 0); fsyncSync(fd); } finally { closeSync(fd); }
unlinkSync(path);
this.keys.delete(period);
destroyed.push(period);
}
// Unconditionally: rows may outlive a key that was removed some other way.
if (this.q.delPeriodsBefore.run(cutoff).changes || destroyed.length) this.checkpoint();
return destroyed;
}
close() { if (this.enabled) this.db.close(); }
}