Tamper-evident audit logs: hash chaining and why it matters
The first thing a competent attacker does after gaining access is clean up. They delete the log line that shows the privilege escalation, edit the timestamp on the suspicious login, remove the row that records a new API key being minted. If your audit log is an ordinary database table, all of that is a single UPDATE or DELETE away—and when the incident responders arrive, the record they need to reconstruct what happened has already been rewritten by the person they're investigating. An audit log that the attacker can edit is not evidence. It's fiction with a timestamp.
Append-only is necessary but not sufficient
The usual first step is to make the log append-only: revoke UPDATE and DELETE at the database grant level, ship entries to a write-once store, stream to a separate account the app can't delete from. Good—but it only raises the bar. An attacker with enough access, or an insider with DBA rights, can still reach the underlying storage. More importantly, append-only gives you no way to prove to a third party that nothing was removed. Absence of evidence is not evidence of absence; you need the log to carry its own proof of integrity.
Hash chaining: each entry commits to the last
The technique is borrowed from the same cryptography that underpins Git and, yes, blockchains—but you need none of the distributed-consensus machinery. Each log entry includes the hash of the entry before it. That single field turns a pile of independent rows into a chain where any change ripples forward and becomes detectable.
import { createHash } from "crypto";
function chainHash(prevHash: string, entry: object): string {
return createHash("sha256")
.update(prevHash)
.update(JSON.stringify(entry)) // canonical serialization matters — see below
.digest("hex");
}
// genesis entry starts from a fixed, well-known seed
let prev = "0".repeat(64);
function append(entry: Record<string, unknown>) {
const body = { ...entry, ts: new Date().toISOString() };
const hash = chainHash(prev, body);
store.insert({ ...body, prevHash: prev, hash });
prev = hash;
return hash;
}Now suppose an attacker edits entry 400—changing a target user id, say. Entry 400's content no longer produces the hash stored in entry 401's prevHash field. To hide the edit, they must recompute 400's hash, then 401's, then 402's, all the way to the head of the log. The tampering isn't prevented, but it becomes detectable: a verifier walks the chain, recomputes each hash, and the first mismatch points straight at the altered record.
Canonicalization is the whole ballgame. If two systems serialize the same entry differently—key order, whitespace, how they encode a number—they compute different hashes and verification fails on honest data. Pin a canonical form (sorted keys, no insignificant whitespace, explicit encodings) and write it down as a spec. This is the single most common reason a hash-chained log "breaks" for no apparent reason.
The gap hash chaining leaves
Chaining proves no entry was modified. It does not, on its own, stop an attacker who controls the writer from rewriting the entire chain from some point forward—recomputing every hash after their edit so the chain is internally consistent again. Internal consistency is cheap to fake if you hold the whole log. You need an external witness that pins the chain to a point in time the attacker cannot reach back and change.
Periodic anchoring
At intervals—hourly, daily—take the current head hash and publish it somewhere outside the attacker's control. Options, in rough order of how much they cost you:
- Write it to a separate append-only store owned by a different team or account.
- Email or message the digest to an external address on a schedule.
- Have a third-party timestamping authority sign it (RFC 3161), producing a signed token that proves the digest existed at that time.
- For the highest bar, submit the digest to a public transparency log or ledger.
Once a head hash is anchored, every entry it commits to is frozen. An attacker who rewrites history after the anchor produces a chain whose head no longer matches the witnessed value, and the discrepancy is provable to anyone holding the anchor—auditor, regulator, court. The window of deniability shrinks to the time between anchors, which you control.
-- a verifier's smoke test: find the first break in the chain
SELECT id, ts
FROM audit_log a
WHERE a.prev_hash <> (
SELECT b.hash FROM audit_log b
WHERE b.id = a.id - 1
)
ORDER BY a.id
LIMIT 1;Why not just use a blockchain? You'd be adopting consensus, tokens, and a peer network to solve a problem that a SHA-256 chain plus one external anchor already solves—at a fraction of the operational cost and with none of the latency. Reach for a public ledger only when you specifically need a globally witnessed, censorship-resistant anchor. For almost everyone, a signed timestamp on an hourly digest is more than enough.
Operational realities
Verification must be routine, not something you first run during an incident—run the chain check on a schedule and alert on any break or any gap in the anchor cadence. Decide up front how you handle legitimate schema changes: entries you wrote last year must still verify under the serialization rules in force when they were written, so version your canonical form and keep old verifiers around. And separate the writer from the verifier: the service that appends should not be the only thing that can confirm the chain, or you're trusting the fox to audit the henhouse.
Compliance frameworks increasingly ask not just whether you keep audit logs but whether you can demonstrate they haven't been altered—and the answer "trust us" doesn't survive a breach. A hash-chained, periodically anchored log lets you prove integrity to someone who doesn't trust you at all. When you own your identity and audit infrastructure end to end, that proof is yours to produce on demand; Bastionary chains and anchors its audit trail by default, so tamper-evidence is a property of the log, not a feature you have to bolt on.
Run it yourself
Bastionary is free, open-source software. Follow the quick start to have it running on your own server, or browse the releases on Git.