How-To Guide

How to Build Tamper-Evident Audit Logs

Build hash-chained, append-only audit logs that detect edits and truncation, with signed checkpoints, redaction, verification, and tests.

On this page

  1. Introduction
  2. Threat Model: What Tamper-Evident Means
  3. Hash Chains and Merkle Roots
  4. Append-Only Storage and Access Control
  5. What to Record and What Never to Record
  6. Verification, Anchoring, and Retention
  7. Failure Modes and Testing
  8. Limitations and When Not to Build

Introduction

An audit log answers who did what, when, to which resource, and with what outcome. It is not an application log: debug logs help engineers diagnose behavior and are routinely sampled, rotated, and deleted; audit logs support accountability, incident investigation, and compliance, so their value depends on completeness and trust.

Tamper-evident means you can detect that an event was altered, removed, or reordered, not that tampering is impossible. Design decisions follow from the threat model: whom you defend against, what they can access, and where the trust anchor lives.

Threat Model: What Tamper-Evident Means

Consider an insider editing a row to hide an action, an application bug deleting events, an attacker with stolen credentials, and a storage administrator who can rewrite the table. Truncation is easy too: a plain hash chain cannot detect deleted tail events without an external record of the expected head.

Define the trust boundary explicitly. If the attacker controls the database and the signing key, no purely local scheme survives. The goal is to make undetected tampering require compromising independent systems, such as a signing service and a write-once bucket in another account. Tamper evidence without an independent anchor is only a checksum against accidental corruption.

Hash Chains and Merkle Roots

A hash chain links each event to its predecessor. The hash of an event covers its security-relevant fields plus the previous hash, so changing any field changes every later hash. Verifying the chain from a trusted starting point reveals the first modified or missing event.

import { createHash } from "node:crypto";

function canonical(value: unknown): string {
  if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
  if (value && typeof value === "object") {
    return `{${Object.entries(value as Record<string, unknown>)
      .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
      .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`)
      .join(",")}}`;
  }
  return JSON.stringify(value) ?? "null";
}

function eventHash(prevHash: string, event: Record<string, unknown>): string {
  return createHash("sha256")
    .update(canonical({ prevHash, ...event }))
    .digest("hex");
}

Canonicalization is not optional. If two processes serialize the same event differently, verification fails or two different events produce the same signed representation. Sort object keys, define number and timestamp formats, and include a schema version so a future field addition does not silently change the hash computation.

A Merkle tree allows inclusion and consistency proofs, the model used by Certificate Transparency. A signed checkpoint of the latest sequence and hash is simpler and detects tail truncation if stored independently.

Append-Only Storage and Access Control

Application permissions should allow inserts and reads, never updates, deletes, or truncation. Put the audit table in a separate schema with a dedicated role and revoke destructive privileges from the application role. A trigger can reject updates, but only a separate account is a real boundary.

CREATE TABLE audit_events (
  seq         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  occurred_at timestamptz NOT NULL,
  actor_id    text NOT NULL,
  action      text NOT NULL,
  resource    text NOT NULL,
  details     jsonb NOT NULL,
  prev_hash   text NOT NULL UNIQUE,
  hash        text NOT NULL UNIQUE
);
REVOKE UPDATE, DELETE, TRUNCATE ON audit_events FROM app_role;

Concurrent writers must not create forks. The unique constraint on prev_hash ensures only one event can follow a given head; a losing insert retries against the new head. Under high volume, a single writer avoids a retry storm at the cost of serializing audit writes.

Export events to object storage with Object Lock or a write-once bucket in another account. Let the application append but never delete, set policy-based retention, and restrict who can change it.

What to Record and What Never to Record

Record authentication successes and failures, authorization denials, privilege changes, administrative configuration changes, sensitive exports, key rotations, and destructive operations. Include a stable event identifier, UTC timestamp, actor identity, source address where relevant, action, target identifiers, outcome, reason, request identifier, and a redacted before/after diff.

Never record passwords, session tokens, API keys, full card numbers, or unnecessary personal data. Redaction must happen before hashing and storage, because a hash of a low-entropy secret can be brute-forced. If correlation is required, use a keyed hash with a secret managed outside the log. Treat free text as hostile: structured JSON, control-character encoding, and length limits prevent log injection from forging entries.

Client-supplied timestamps are untrusted. Record the server’s event time and, if useful, the client’s claimed time as a separate field. Time synchronization matters for investigation, but ordering should come from the sequence, not from wall-clock timestamps.

Verification, Anchoring, and Retention

A verifier should walk from a trusted checkpoint, recompute each hash, and report the first sequence where the chain breaks. Run it continuously, alert on failure, and never auto-repair a broken chain. Sequence gaps are not proof of tampering because identity columns skip values after rollbacks; missing events with intact hashes require correlation with application records.

Sign checkpoints periodically with a key held in a KMS or signing service. A checkpoint contains the latest sequence, hash, timestamp, and schema version. Publish it to write-once storage, a separate account, or a third-party timestamp authority. RFC 3161 timestamps or a transparency log prove the checkpoint existed at a point in time, which defeats a later full-chain rewrite.

Retention is tension: compliance may require years, while privacy rules may require deleting personal data. Deleting an event breaks the chain, so minimize and redact at ingestion, use per-tenant encryption keys and crypto-shredding where deletion is mandatory, and document the resulting verification semantics. Rotate signing keys with overlap and rehearse restoring the database and checkpoint.

Failure Modes and Testing

The most dangerous failure is a missing audit event after a successful action. If the action and audit write share a database, commit them in one transaction or use an outbox; if the action is external, write an intent record first and reconcile. For critical operations, fail closed when the audit sink is unavailable rather than buffering in memory and losing evidence on a crash.

Schema evolution is another quiet failure. Adding a field changes canonicalization; without a version in the payload and verifier, old events stop verifying. Test the verifier against every schema version still inside retention. Clock skew can make timestamps misleading even when the chain is intact, so monitor drift and keep event and ingest times.

Tests should mutate a payload and expect failure at that sequence, delete a middle event, reorder events, truncate the tail and expect checkpoint failure, and append concurrently to confirm one chain. Add tests for canonicalization stability, redaction, write-failure handling, and verification after a restore.

Limitations and When Not to Build

A hash chain adds serialization, verification work, and operational complexity. It prevents neither deletion nor access-control mistakes and is not a blockchain. For a small application, a managed audit service or a write-once export may provide stronger guarantees with less code. Build your own chain when you need control over retention, verification, and the threat model, and be honest: the log is tamper-evident relative to a named anchor, not tamper-proof.

Sources: NIST SP 800-92: Guide to Computer Security Log Management, RFC 6962: Certificate Transparency, OWASP Logging Cheat Sheet.

FAQ

Is a hash chain the same as a blockchain?
No. A hash chain provides ordering and tamper evidence with a fraction of the complexity. A blockchain adds distributed consensus, which is unnecessary when a single organization controls the log but still needs internal tamper evidence.
Can an administrator with database access defeat the chain?
Yes, if the administrator can rewrite every event and recompute every hash. Signed checkpoints published to independent storage raise the cost: the attacker must also forge the signature or alter the external anchor. Tamper-evident is not tamper-proof.
Should audit logs contain full request bodies?
Usually not. Store identifiers, outcomes, and redacted diffs, not passwords, tokens, or unnecessary personal data. If a sensitive value must be correlated, use a keyed hash rather than the raw value.

Related Examples