From e39b4e9eabb4b88a5f4a6f7c249e9b7302c5ce5e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 30 Jun 2026 11:15:42 +0000 Subject: [PATCH] =?UTF-8?q?fix(audit):=20bind=20attribution=20into=20the?= =?UTF-8?q?=20HMAC=20anchor=20(v3)=20=E2=80=94=20catch=20sealed-entry=20de?= =?UTF-8?q?-attribution?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The deep adversarial pass found the audit attribution layer's one unguarded move: a writer-only attacker (no private key, no anchor key) could STRIP or rewrite kid/sig on an entry that was already signed AND anchored, and every layer stayed green — the keyless chain re-hashes without kid/sig, the signature tally re-counts the entry as `unsigned` (fail-open), and the hash-only anchor tip was byte-identical. Fix: the HMAC anchor now folds attribution into the seal. New `computeAnchorTipV3` chains over `hash | kid | sig` per line (unit-separated; own domain seed), and anchor records are written at `version: 3`. Altering or removing the signer of any ANCHORED entry now moves the tip → hard `tip-mismatch`; forging kid/sig onto a sealed keyless entry is caught the same way. `verifyAgainstAnchor` picks the fold algorithm from the record version, so legacy v≤2 anchors keep verifying hash-only until the next `kit audit anchor` re-seals them as v3 (backward-compatible, self-migrating). Not changed: signing over `hash` alone is kept — binding kid into the signature adds nothing here (a relabel to a known key already fails verification; strip / unknown-relabel fail-open regardless). The anchor is the authoritative seal, so that is where attribution is bound. Adds 3 regression tests (v3 tip moves on kid/sig change; v3 verify catches the strip; legacy v2 stays hash-only). Updates docs/AUDIT_ATTESTATION.md + CHANGELOG. 1945 tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) Claude-Session: https://claude.ai/code/session_015ERHw6bVUz39sAuoQZ1iyg --- CHANGELOG.md | 16 +++++++ docs/AUDIT_ATTESTATION.md | 13 ++++++ src/audit-anchor.test.ts | 74 +++++++++++++++++++++++++++++- src/audit-anchor.ts | 95 +++++++++++++++++++++++++++++++++------ 4 files changed, 183 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 36a1de4e..47d7d750 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,22 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +### Security + +- **Audit attribution is now bound into the HMAC anchor (de-attribution of a + sealed entry is caught).** The adversarial pass found that a writer-only + attacker — no private key, no anchor key — could **strip or rewrite the + `kid`/`sig` of an entry that was already signed AND anchored**, and every layer + stayed green: the keyless chain re-hashes without those fields, the signature + tally just re-counts the entry as `unsigned` (fail-open), and the hash-only + anchor tip was byte-identical. The anchor seal now folds attribution + (`computeAnchorTipV3` over `hash | kid | sig` per line; anchor record + `version: 3`), so altering or removing the signer of any **anchored** entry + changes the tip → hard `tip-mismatch`; forging a `kid`/`sig` onto a sealed + keyless entry is caught the same way. Backward-compatible: legacy `version ≤ 2` + records keep verifying hash-only until the next `kit audit anchor` re-seals them + as v3. (Surfaced by the deep adversarial security pass; complements #175.) + ### Added - **Private cross-device memory sync over your own git remote (`kit memory push` diff --git a/docs/AUDIT_ATTESTATION.md b/docs/AUDIT_ATTESTATION.md index a173c473..a1f89d0a 100644 --- a/docs/AUDIT_ATTESTATION.md +++ b/docs/AUDIT_ATTESTATION.md @@ -110,6 +110,19 @@ Verdict rules (`verifyAuditSignatures`): | `kid` not resolvable to a public key | `unverifiable` — fail-OPEN (absence of trust ≠ forgery) | | No `kid`/`sig` (legacy/keyless) | `unsigned` — fail-OPEN | +**Attribution of a SEALED entry is tamper-evident (anchor v3).** The fail-OPEN +rows above mean a fresh log's _missing_ attribution is treated as benign. On its +own that left a gap: a writer-only attacker could **strip or rewrite `kid`/`sig` +on an entry that was already signed AND anchored** — the keyless chain re-hashes +without those fields, the signature tally just re-counts it as `unsigned`, and +the old hash-only anchor tip was byte-identical. The HMAC anchor now folds +attribution into the seal (record `version: 3`, `computeAnchorTipV3` over +`hash | kid | sig` per line), so stripping or altering the signer of any +**anchored** entry changes the tip and is caught as a hard `tip-mismatch`. A +keyless entry seals with empty attribution, so forging a `kid`/`sig` ONTO a +sealed keyless entry is caught the same way. Legacy `version ≤ 2` records keep +verifying hash-only until the next `kit audit anchor` re-seals them as v3. + Asymmetric payoff: a remote / CI / teammate verifies WHO produced an entry with only the PUBLIC key — never a forge-capable secret, unlike the HMAC anchor. Same same-UID boundary applies for _production_: a same-UID principal can read the diff --git a/src/audit-anchor.test.ts b/src/audit-anchor.test.ts index 0351bf56..a4341962 100644 --- a/src/audit-anchor.test.ts +++ b/src/audit-anchor.test.ts @@ -7,6 +7,8 @@ import { appendAuditEventDirect } from "./audit.js"; import { randomBytes, createHash } from "node:crypto"; import { computeAnchorTip, + computeAnchorTipV3, + lineSeals, anchorKeyFingerprint, lineHashes, anchorAuditLog, @@ -19,6 +21,7 @@ import { tryAdvanceAnchorOnAppend, resolveExternalAnchor, type AnchorVerifyResult, + type AnchorRecord, } from "./audit-anchor.js"; // Build a real hash-chained log without auto-anchoring (KIT_AUDIT_ANCHOR=0 is @@ -55,6 +58,73 @@ describe("audit anchor - pure helpers", () => { }); }); +// The deep adversarial pass found that a writer-only attacker could STRIP or +// rewrite kid/sig on an already-sealed entry and every layer (chain, signatures, +// hash-only anchor) still reported green — de-attribution of a sealed record. The +// v3 seal folds attribution INTO the anchor tip so the rewrite is now caught. +describe("audit anchor - v3 binds attribution (sealed-entry de-attribution)", () => { + const key = Buffer.alloc(32, 9); + const line = (op: string, kid: string, sig: string) => + JSON.stringify({ + operation: op, + environment: "dev", + success: true, + prev: "0".repeat(64), + hash: createHash("sha256").update(op).digest("hex"), + kid, + sig, + }); + const signed = line("op-0", "kid-real", "SIG_REAL") + "\n"; + const stripped = line("op-0", "", "") + "\n"; // kid/sig erased, hash untouched + + it("computeAnchorTipV3 moves when kid/sig change; the legacy hash-only tip does NOT", () => { + const a = lineSeals(signed)!; + const b = lineSeals(stripped)!; + assert.notEqual(computeAnchorTipV3(key, a), computeAnchorTipV3(key, b)); + // hash-only fold is blind to attribution — exactly the gap v3 closes + assert.equal( + computeAnchorTip( + key, + a.map((s) => s.hash), + ), + computeAnchorTip( + key, + b.map((s) => s.hash), + ), + ); + }); + + it("a v3 anchor reports tip-mismatch after a sealed entry's kid is stripped", () => { + const rec: AnchorRecord = { + tip: computeAnchorTipV3(key, lineSeals(signed)!), + count: 1, + algo: "hmac-sha256", + updatedAt: "2026-01-01T00:00:00Z", + keyFingerprint: anchorKeyFingerprint(key), + version: 3, + }; + assert.equal(verifyAgainstAnchor(signed, rec, key).status, "anchored-ok"); + assert.equal(verifyAgainstAnchor(stripped, rec, key).status, "tip-mismatch"); + }); + + it("a legacy v2 anchor still verifies hash-only (back-compat) — and is blind to the strip", () => { + const rec: AnchorRecord = { + tip: computeAnchorTip( + key, + lineSeals(signed)!.map((s) => s.hash), + ), + count: 1, + algo: "hmac-sha256", + updatedAt: "2026-01-01T00:00:00Z", + keyFingerprint: anchorKeyFingerprint(key), + version: 2, + }; + assert.equal(verifyAgainstAnchor(signed, rec, key).status, "anchored-ok"); + // documents the pre-v3 behavior: a hash-only anchor accepts the de-attributed log + assert.equal(verifyAgainstAnchor(stripped, rec, key).status, "anchored-ok"); + }); +}); + describe("audit anchor - key file", () => { let dir: string; beforeEach(() => { @@ -264,13 +334,13 @@ describe("audit anchor - key rotation (FIX 4)", () => { rmSync(dir, { recursive: true, force: true }); }); - it("anchorAuditLog records the key fingerprint (v2)", async () => { + it("anchorAuditLog records the key fingerprint (v3, attribution-bound)", async () => { const content = await buildChain(cwd, 3); const logPath = join(cwd, ".kit-audit.jsonl"); const rec = await anchorAuditLog(logPath, content, dir); const key = await tryReadAuditAnchorKey(dir); assert.equal(rec.keyFingerprint, anchorKeyFingerprint(key!)); - assert.equal(rec.version, 2); + assert.equal(rec.version, 3); }); it("a rotated key reports 'anchor-key-changed', NOT content tip-mismatch", async () => { diff --git a/src/audit-anchor.ts b/src/audit-anchor.ts index 9b9fd7e9..e0c012e8 100644 --- a/src/audit-anchor.ts +++ b/src/audit-anchor.ts @@ -48,6 +48,13 @@ const ANCHOR_ALGO = "hmac-sha256"; // Domain-separation seed so the anchor HMAC chain can never collide with any // other HMAC use of the same key. const ANCHOR_SEED = "kit-audit-anchor/v1"; +// v3 seal folds ATTRIBUTION (kid/sig) into the tip alongside the hash, so +// stripping or rewriting the signer of a sealed entry changes the tip. Its own +// seed keeps a v3 tip from ever colliding with a v1/v2 (hash-only) tip. +const ANCHOR_SEED_V3 = "kit-audit-anchor/v3"; +// Unit separator — cannot appear in a hex hash, an identity id, or base64 — so +// the (hash, kid, sig) fields can't be ambiguously concatenated. +const FIELD_SEP = "\x1f"; /** Resolve the directory that holds the anchor key + record (default ~/.kit). */ export function anchorDir(override?: string): string { @@ -138,7 +145,7 @@ export function lineHashes(content: string): string[] | null { * Fold an HMAC chain over the supplied line hashes and return the final tip * (hex). Pure: same key + hashes always yield the same tip. Only a holder of * the key can reproduce this value, which is what makes a key-less rewrite - * detectable. + * detectable. (v1/v2 seal — hash only; kept for legacy anchor records.) */ export function computeAnchorTip(key: Buffer, hashes: string[]): string { let tip = createHmac("sha256", key).update(ANCHOR_SEED).digest("hex"); @@ -150,6 +157,65 @@ export function computeAnchorTip(key: Buffer, hashes: string[]): string { return tip; } +/** A line's integrity hash plus its attribution (empty strings when keyless). */ +export interface LineSeal { + hash: string; + kid: string; + sig: string; +} + +/** + * Extract per-line hash + attribution from raw `.kit-audit.jsonl`. Returns null + * if any non-empty line is unparseable or lacks a string hash. `kid`/`sig` are + * "" for keyless (legacy) entries — folding them as empty means a keyless entry + * has a stable seal, and ADDING a forged kid/sig to it later changes the tip. + */ +export function lineSeals(content: string): LineSeal[] | null { + const lines = content.split("\n").filter((l) => l.trim().length > 0); + const seals: LineSeal[] = []; + for (const line of lines) { + let obj: { hash?: unknown; kid?: unknown; sig?: unknown }; + try { + obj = JSON.parse(line) as typeof obj; + } catch { + return null; + } + if (typeof obj.hash !== "string") return null; + seals.push({ + hash: obj.hash, + kid: typeof obj.kid === "string" ? obj.kid : "", + sig: typeof obj.sig === "string" ? obj.sig : "", + }); + } + return seals; +} + +/** + * v3 seal: fold an HMAC chain over (hash, kid, sig) per line. This binds the + * ATTRIBUTION into the external anchor, so a writer-only attacker who strips or + * rewrites the signer of a SEALED entry — invisible to the keyless chain and to + * the old hash-only anchor — now changes the tip and is caught as a tip-mismatch. + * Pure. + */ +export function computeAnchorTipV3(key: Buffer, seals: LineSeal[]): string { + let tip = createHmac("sha256", key).update(ANCHOR_SEED_V3).digest("hex"); + for (const s of seals) { + tip = createHmac("sha256", key) + .update(tip + "\n" + s.hash + FIELD_SEP + s.kid + FIELD_SEP + s.sig) + .digest("hex"); + } + return tip; +} + +/** Recompute a record's tip with the algorithm matching its schema version. */ +function tipForRecordVersion(key: Buffer, seals: LineSeal[], version: number | undefined): string { + if ((version ?? 0) >= 3) return computeAnchorTipV3(key, seals); + return computeAnchorTip( + key, + seals.map((s) => s.hash), + ); +} + // Domain-separated key-id label. The fingerprint is an HMAC of a FIXED label // keyed by the anchor key, so it identifies the key (lets verify tell "the key // rotated" apart from "the content was tampered") WITHOUT revealing key bytes. @@ -159,8 +225,8 @@ export function anchorKeyFingerprint(key: Buffer): string { return createHmac("sha256", key).update(ANCHOR_KEY_FP_LABEL).digest("hex").slice(0, 32); } -/** Current schema version of the anchor record. */ -export const ANCHOR_RECORD_VERSION = 2; +/** Current schema version of the anchor record. v3 binds attribution (kid/sig). */ +export const ANCHOR_RECORD_VERSION = 3; export interface AnchorRecord { /** HMAC tip over the sealed prefix of `count` entries. */ @@ -247,14 +313,14 @@ export async function anchorAuditLog( content: string, dir?: string, ): Promise { - const hashes = lineHashes(content); - if (hashes === null) { + const seals = lineSeals(content); + if (seals === null) { throw new Error("audit log is unparseable or unchained - cannot anchor"); } const key = await getAuditAnchorKey(dir); const rec: AnchorRecord = { - tip: computeAnchorTip(key, hashes), - count: hashes.length, + tip: computeAnchorTipV3(key, seals), + count: seals.length, algo: ANCHOR_ALGO, updatedAt: new Date().toISOString(), keyFingerprint: anchorKeyFingerprint(key), @@ -304,8 +370,8 @@ export function verifyAgainstAnchor( anchor: AnchorRecord | null, key: Buffer | null, ): AnchorVerifyResult { - const hashes = lineHashes(content); - const entries = hashes?.length ?? 0; + const seals = lineSeals(content); + const entries = seals?.length ?? 0; if (!anchor) return { status: "no-anchor", entries }; if (!key) return { status: "key-unavailable", entries, expected: anchor.count }; // Key-rotation check FIRST so a changed key reports as a rotation, never as a @@ -320,7 +386,7 @@ export function verifyAgainstAnchor( "the current anchor key differs from the one that sealed this log (rotated/replaced key); old anchors are invalid by design - re-run 'kit audit anchor'", }; } - if (hashes === null) { + if (seals === null) { return { status: "unparseable", entries, @@ -328,15 +394,18 @@ export function verifyAgainstAnchor( reason: "log is unparseable - cannot reconcile with the anchor", }; } - if (hashes.length < anchor.count) { + if (seals.length < anchor.count) { return { status: "truncated", entries, expected: anchor.count, - reason: `log has ${hashes.length} entries but the anchor sealed ${anchor.count} (truncated/rolled back)`, + reason: `log has ${seals.length} entries but the anchor sealed ${anchor.count} (truncated/rolled back)`, }; } - const recomputed = computeAnchorTip(key, hashes.slice(0, anchor.count)); + // Recompute the sealed prefix with the algorithm that MATCHES the record's + // version: a legacy (v≤2) anchor folds hash-only; a v3 anchor folds attribution + // too, so a stripped/rewritten kid|sig on a sealed entry now fails to reproduce. + const recomputed = tipForRecordVersion(key, seals.slice(0, anchor.count), anchor.version); const a = Buffer.from(recomputed, "hex"); const b = Buffer.from(anchor.tip, "hex"); const matches = a.length === b.length && timingSafeEqual(a, b);