How-To Guide

How to Design Tamper-Evident Audit Logs

Chain records with per-entry hashes, anchor chain heads externally, redact secrets at write time, and verify the chain continuously.

On this page

  1. Introduction
  2. Define events before infrastructure
  3. Chain the records
  4. Anchor outside the log
  5. Redact at write time
  6. Verify continuously
  7. Common pitfalls
  8. Conclusion

Introduction

An audit log answers questions after the fact, who changed this record, when was this permission granted, what did this administrator see, and its value collapses the moment the log itself is editable. The attacker model is internal: a compromised admin account, a malicious insider, or malware running with database privileges, because those are the actors who can reach the audit table and have the motivation to revise history. Ordinary logging practice offers them no resistance: application logs rotate away in days, database rows are mutable with a single UPDATE, and a DELETE followed by a plausible re-entry leaves no trace. Tamper-evidence is the realistic goal, tamper-proofing is not, you cannot stop a privileged actor from writing, but you can make any revision detectable. The design is a hash chain over append-only records, external anchoring so even a full-chain rewrite is caught, redaction at write time so the log is safe to keep, and a verifier that runs continuously. This tutorial builds all four pieces and is explicit about what each does and does not defend.

Define events before infrastructure

The log’s usefulness is decided by the event schema, not the cryptography. Each auditable action records: actor, the authenticated identity, not the IP alone; action, from a closed vocabulary, grant, revoke, read, update, delete, export; target, the resource with stable identifiers; before and after states for mutations, the diff or the full prior value where feasible; timestamp, in UTC as an instant; and request context, the request id and trace id that link the event to operational logs. Two disciplines make the schema hold up under scrutiny. Closed vocabulary: free-text actions cannot be queried or reasoned about in an investigation, so the action list is an enum reviewed like code. Before and after: an update event that records only the fact of change, not the content, answers who and when but never what, which is the question investigations actually ask. Write the event catalog first, security-relevant actions, authentication events, permission changes, data export and read access, and let it drive retention and access decisions downstream.

Chain the records

The chain is one field: each record includes the hash of the previous record, computed over the canonical serialization of that previous record, so the chain links records into a sequence where altering any byte of any record changes its hash, which breaks the next record’s stored previous-hash, which cascades visibly to the head.

import { createHash } from 'node:crypto';

export function appendAuditEvent(store: AuditStore, event: AuditEvent) {
 const prev = store.latest();
 const record = {
  ...event,
  seq: prev ? prev.seq + 1 : 1,
  prevHash: prev ? prev.hash : null,
  recordedAt: new Date().toISOString(),
 };
 const hash = createHash('sha256')
  .update(canonicalJson(record))
  .digest('hex');
 return store.insert({ ...record, hash });
}

function canonicalJson(value: unknown): string {
 return JSON.stringify(value, (_k, v) =>
  v !== null && typeof v === 'object' && !Array.isArray(v)
   ? Object.keys(v).sort().reduce((acc: Record<string, unknown>, key) => {
     acc[key] = (v as Record<string, unknown>)[key];
     return acc;
    }, {})
   : v);
}

Canonical serialization is load-bearing: key order must be deterministic, or verification produces false breaks. Append-only is the storage discipline, INSERT only, no UPDATE, no DELETE, enforced by table privileges, a revoke of UPDATE and DELETE on the audit table from the application role, with rotation handled by new segments rather than row deletion. The hash column itself is included in the next record’s input, so forging requires rewriting everything after the target, which is where external anchoring finishes the job.

Anchor outside the log

The honest threat model concedes that an attacker with database privileges can rebuild the entire chain consistently, every record re-hashed, every prevHash updated. Detection of that scenario requires an anchor the attacker cannot reach: something published or signed outside the compromised zone. Three shapes, in increasing strength. Signature anchors: an external signing service, or HashiCorp Vault’s audit-device model where Vault signs entries, produces a signature of each record or of the chain head at intervals, and the verifier holds the public key. Publication anchors: the chain head, its sequence number and hash, is written to WORM storage, an append-only object bucket, or another system with different credentials and blast radius. Third-party anchors: the head hash is submitted to an external timestamping service or a transparency-log style append-only structure, making history revision publicly provable.

// every 5 minutes: persist the head where the app cannot rewrite it
setInterval(() => {
 const head = store.latest();
 worm.append(JSON.stringify({
  seq: head.seq, headHash: head.hash, at: new Date().toISOString(),
 }));
}, 5 * 60 * 1000);

The anchor interval bounds the attack window: history can be revised without detection only for events after the last anchor, five minutes of exposure in this example, which is a defensible trade against the cost and latency of per-event anchoring.

Redact at write time

Audit logs live long, travel far into investigations and compliance reviews, and are read more widely than application logs, so secrets must never enter them. Redaction at write time, not at read time, because read-time filtering depends on every future reader running the filter, a leak waiting for one forgotten dashboard. The write path runs every event through a scrubber: passwords and tokens are excluded by schema design, the event builder never accepts them; free-text fields, reasons, comments, error messages, pass through pattern-based redaction for known shapes, bearer tokens, long hex and base64 runs, email addresses where policy requires; and structured fields that must retain shape are hashed rather than dropped, a token’s hash stays useful for correlation while the value stays secret. The complementary rule is completeness of what is kept: redaction must not become censorship, an actor editing the event before append to remove their own actions is tampering by another door, which is why the event is built from server-side state and the actor comes from the authenticated session, never from client-supplied fields.

Verify continuously

A chain nobody checks is decoration. The verifier walks the log on a schedule: recompute each record’s hash from its canonical form, confirm each prevHash matches the previous record’s hash, confirm sequence numbers are contiguous, and compare the current head against the anchors recorded in WORM storage or the signature service. Any break, a recomputed hash mismatch, a gap in sequence, an anchor disagreement, raises an alert with the specific location, the first divergent record, because the response procedure needs to know where history stops being trustworthy.

export function verifyChain(records: AuditRecord[]): VerificationResult {
 let prev: AuditRecord | null = null;
 for (const r of records) {
  const { hash, ...rest } = r;
  if (createHash('sha256').update(canonicalJson(rest)).digest('hex') !== hash) {
   return { ok: false, brokenAt: r.seq, reason: 'hash mismatch' };
  }
  if (prev && r.prevHash !== prev.hash) {
   return { ok: false, brokenAt: r.seq, reason: 'chain break' };
  }
  if (prev && r.seq !== prev.seq + 1) {
   return { ok: false, brokenAt: r.seq, reason: 'sequence gap' };
  }
  prev = r;
 }
 return { ok: true, head: prev };
}

Verification also runs on-demand during investigations, and its output, chain intact through sequence N, break detected at N+1 with anchor corroboration, is exactly the artifact an incident report needs. Rotation and sharding add one level: segments verify internally, and a manifest chains the segment heads, so the verifier checks both tiers.

Common pitfalls

  • **Claiming tamper-proof. ** Chains detect, they do not prevent; without external anchoring, a privileged attacker rewrites everything consistently.
  • **Mutable audit tables. ** UPDATE privileges on the log make the chain theater; append-only by grant, not by convention.
  • **Non-canonical serialization. ** Key-order-dependent hashing yields false breaks and trains operators to ignore verifier alarms.
  • **Read-time redaction. ** One forgotten dashboard leaks every secret the filter was supposed to catch.
  • **Free-text actions. ** Investigations query vocabulary, not prose; the action list is an enum.
  • **Never-run verification. ** An unchecked chain is decoration; the verifier’s alert is the feature.

Conclusion

Tamper-evidence is the honest goal for audit logs, and it is achieved in layers, each addressing an attacker the previous layer cannot. Define the event schema first, closed action vocabulary, actor from the authenticated session, before and after for mutations, because the schema determines investigative value. Chain records with canonical-serialization hashes under append-only storage privileges, so local edits and deletions break visibly. Anchor the chain head externally, signatures, WORM copies, or third-party timestamps, so even a consistent full rewrite is caught, with the anchor interval defining the exposure window. Redact at write time so long-lived, widely-read logs never carry secrets, and run the verifier continuously with specific break locations. The result is an audit log that answers the post-incident questions, including the one about the log itself.

Sources: OWASP: logging cheat sheet, NIST FIPS 180-4: SHA-2, HashiCorp Vault: audit devices.

FAQ

Does a hash chain prevent tampering?
No, it detects tampering. An attacker with full write access can rebuild the whole chain consistently. Detection that survives log access requires external anchoring: signatures, a WORM copy, or a third-party timestamp of the chain head.
Should audit logs go through the application logger?
No. Application logs are for debugging, with retention measured in days and no integrity guarantees. Audit events are compliance artifacts with long retention and integrity requirements; they need their own store and pipeline.
How do hash chains handle log rotation and sharding?
Each shard or rotated segment carries its own chain, and a manifest chains the segment heads together. The verifier then checks both levels: records within segments and the manifest across them.

Related Examples