// Looks for secrets where a server must not have them: in every file under // some directories, and in the memory of running server processes. Used by the // tests that show a server only ever holds ciphertext. // // A needle is searched for as UTF-8, UTF-16, and in standard and URL-safe // base64 at all three byte alignments, since a server might store a secret // re-encoded. import { readdirSync, readFileSync, readSync, openSync, closeSync, statSync } from 'node:fs'; import { join } from 'node:path'; export function variants(needle) { const bytes = Buffer.from(needle, 'utf8'); if (bytes.length < 12) throw new Error(`needle too short to search for reliably: ${needle}`); const out = [bytes, Buffer.from(needle, 'utf16le')]; for (let offset = 0; offset < 3; offset++) { const enc = Buffer.concat([Buffer.alloc(offset), bytes]); // Drop the edge characters that depend on neighbouring bytes. for (const kind of ['base64', 'base64url']) { const text = enc.toString(kind).replace(/=+$/, ''); out.push(Buffer.from(text.slice(offset ? 4 : 0, -4))); } } return out; } function walk(dir, out = []) { for (const name of readdirSync(dir)) { const p = join(dir, name); if (statSync(p).isDirectory()) walk(p, out); else out.push(p); } return out; } /** Needles found in any file under `dirs`: [{needle, file}]. */ export function scanFiles(dirs, needles) { const hits = []; const searches = needles.map((n) => [n, variants(n)]); for (const file of dirs.flatMap((d) => walk(d))) { const data = readFileSync(file); for (const [needle, vs] of searches) if (vs.some((v) => data.includes(v))) hits.push({ needle, file }); } return hits; } /** * Needles found in the readable memory of a process we started (Linux: reads * /proc/PID/mem, which the kernel allows for a parent). Returns * {hits: [{needle}], bytes} so the caller can check it really read something. */ export function scanMemory(pid, needles) { const searches = needles.map((n) => [n, variants(n)]); const maxLen = Math.max(...searches.flatMap(([, vs]) => vs.map((v) => v.length))); const found = new Set(); let bytes = 0; const fd = openSync(`/proc/${pid}/mem`, 'r'); try { for (const line of readFileSync(`/proc/${pid}/maps`, 'utf8').split('\n')) { const m = /^([0-9a-f]+)-([0-9a-f]+) (\S{4}) /.exec(line); if (!m || !m[3].startsWith('r') || /\[(vvar|vsyscall|vdso)\]/.test(line)) continue; const [start, end] = [Number.parseInt(m[1], 16), Number.parseInt(m[2], 16)]; const CHUNK = 4 << 20; for (let at = start; at < end; at += CHUNK - maxLen) { const len = Math.min(CHUNK, end - at); const buf = Buffer.alloc(len); let n; try { n = readSync(fd, buf, 0, len, at); } catch { break; } if (n <= 0) break; bytes += n; const view = buf.subarray(0, n); for (const [needle, vs] of searches) if (vs.some((v) => view.includes(v))) found.add(needle); } } } finally { closeSync(fd); } return { hits: [...found].map((needle) => ({ needle })), bytes }; }