Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
13 changes: 13 additions & 0 deletions docs/AUDIT_ATTESTATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
74 changes: 72 additions & 2 deletions src/audit-anchor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { appendAuditEventDirect } from "./audit.js";
import { randomBytes, createHash } from "node:crypto";
import {
computeAnchorTip,
computeAnchorTipV3,
lineSeals,
anchorKeyFingerprint,
lineHashes,
anchorAuditLog,
Expand All @@ -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
Expand Down Expand Up @@ -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(() => {
Expand Down Expand Up @@ -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 () => {
Expand Down
95 changes: 82 additions & 13 deletions src/audit-anchor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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");
Expand All @@ -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.
Expand All @@ -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. */
Expand Down Expand Up @@ -247,14 +313,14 @@ export async function anchorAuditLog(
content: string,
dir?: string,
): Promise<AnchorRecord> {
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),
Expand Down Expand Up @@ -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
Expand All @@ -320,23 +386,26 @@ 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,
expected: anchor.count,
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);
Expand Down
Loading