Audit logging
Who did what and when, the event lost after commit, append-only, and a hash chain shown catching an edit — and missing a full rewrite without an anchor.
An application log answers what went wrong. An audit log answers who did what, and when — and it is read by a different person, for a different reason, often years later: a security investigation, a customer dispute, an auditor, a court.
That difference in reader changes almost every design decision. An application log can be sampled, rotated after a week, and lose a line under load. An audit log that can lose a line is not an audit log.
What an audit event records
For any action that changes something that matters — money, permissions, personal data, configuration — an event carries:
| Field | Example | Why |
|---|---|---|
| Who | admin:ana, plus the real person behind a service account | "the system did it" answers nothing |
| What | ROLE_GRANT | a fixed vocabulary, not free text, so it can be searched |
| On what | user:77 | the target, by stable ID |
| Before and after | role: VIEWER → ADMIN | what changed, not only that something did |
| When | UTC timestamp from the server | never the client's clock |
| From where | source IP, session or request ID | links to the application logs |
| Outcome | SUCCESS / DENIED | failed attempts matter as much as successful ones |
That last row is the one most often left out. An audit log of only successful actions cannot show an attack, because an attacker's first twenty attempts are the ones that fail. The OWASP Logging Cheat Sheet lists authentication and authorization failures among the events that should always be recorded.
What an audit event must never record
The same care in the other direction. An audit log is kept for a long time, read by many people, and copied into other systems — so it is a terrible place for a secret.
- No passwords, including wrong ones — a mistyped password is usually one character off the real one.
- No tokens, session IDs in full, or API keys.
- No full card numbers — PCI DSS requires them to be unreadable wherever they are stored, and an audit table is storage.
- Personal data only as much as the purpose needs. Record that a customer's address changed and who changed it; think hard before recording the address.
The write that must not be lost
The subtle failure is not in what you record but when. Consider the obvious code:
@Transactional
public void grantRole(long userId, Role role, Admin by) {
users.grantRole(userId, role);
}
// ...and the caller, afterwards:
roleService.grantRole(77, Role.ADMIN, admin);
auditClient.send(new AuditEvent(admin, "ROLE_GRANT", 77)); // a separate stepThe role change commits. Then the process crashes, or the audit service times out, and the event is never sent. The permission exists and no record says who granted it — exactly the gap an attacker, or an insider, would want.
The fix is to make the audit record part of the same transaction as the change it describes:
@Transactional
public void grantRole(long userId, Role role, Admin by) {
Role before = users.grantRole(userId, role);
auditEvents.save(AuditEvent.of(by, "ROLE_GRANT", "user:" + userId, before, role));
}Now both commit or neither does. If the audit trail must end up in a separate system, write it to a table in the same transaction and ship it from there afterwards — the transactional outbox from the distributed data course, applied to audit.
Append-only, and why that is not enough
An audit log is append-only: rows are inserted and never updated or deleted. Enforce it where the application cannot argue: the database user that writes audit rows gets INSERT and SELECT on that table, and no UPDATE or DELETE.
That stops the application from rewriting history. It does not stop a database administrator, or an attacker who has become one. For that, you need the log to be tamper-evident: an edit is still possible, but it can be detected.
The standard technique is a hash chain. Each entry stores the hash of the previous entry, and its own hash covers both:
static void append(List<Entry> log, String event) throws Exception {
String prev = log.isEmpty() ? "0" : log.get(log.size() - 1).hash;
log.add(new Entry(event, prev, sha256(prev + "|" + event)));
}
static int firstBroken(List<Entry> log) throws Exception {
String prev = "0";
for (int i = 0; i < log.size(); i++) {
Entry e = log.get(i);
if (!e.prevHash.equals(prev) || !e.hash.equals(sha256(prev + "|" + e.event))) return i;
prev = e.hash;
}
return -1;
}Three events are appended — a refund, a role grant to ADMIN, an export. Then someone edits the second entry in place, to say the role granted was VIEWER:
intact, first broken: -1
edited, first broken: 1Verification finds it and names the entry. That is the chain doing its job.
Now the attacker is more careful. They do not edit one row; they rebuild the whole chain from the point they changed, recomputing every hash after it:
rewritten, first broken: -1
head matches anchor: falseThe rewritten chain verifies perfectly. Every link is consistent, because the attacker computed them all. A hash chain on its own proves only that the log is internally consistent — and anyone who can write the whole table can make it consistent.
What caught the rewrite is the second line. Before the tampering, the hash of the latest entry was copied somewhere the attacker cannot reach, and the rebuilt chain ends in a different hash. That copy is the anchor, and without one the chain is decoration:
- Publish the head hash periodically to a separate system with separate credentials.
- Ship audit events to write-once storage — object storage with a retention lock, for example, which refuses deletes until the retention period ends.
- Or hand the log to a separate team or service entirely, so no single set of credentials can rewrite both the log and its evidence.
Retention, and reading it
Keep audit logs as long as the obligations that apply to you require — financial and payment regulations commonly specify a year or more — and plan the storage for that. A year of audit events is rarely large; a year of application logs is.
And test that it can be read. The question an audit log exists to answer is something like "everything admin raj did between the 3rd and the 10th", asked under pressure. If that query needs a script someone has to write first, it will not be answered well on the day.
Under the hood: from a hash chain to a Merkle tree, and why real systems use the tree
The hash chain above proves something specific and something limited: it proves the log is internally self-consistent, and — once anchored — that it has not been rewritten since the anchor was taken. Two real problems remain even with a good anchor. First, verifying the chain up to entry N requires re-hashing all N entries in order, which is O(n) and gets expensive as the log grows into millions of rows. Second, proving that one specific entry is part of the log — the question an auditor actually asks, "was this refund really recorded, unaltered, on the 4th?" — still means walking the whole chain from that entry to the head.
A Merkle tree (the structure behind Certificate Transparency logs, and the same idea Git uses for commit history) restructures the same hash-chaining idea into a binary tree: each leaf is the hash of one audit entry, and each internal node is the hash of its two children's hashes, all the way up to a single root hash that commits to every leaf beneath it. The payoff is that proving one entry belongs to the tree — an inclusion proof — needs only the O(log n) sibling hashes on the path from that leaf to the root, not the whole log. For a million-entry log, that is about 20 hashes instead of a million. The root hash plays exactly the role the anchored head hash plays in a simple chain: publish it somewhere the writer cannot reach, and anyone holding an old root can verify a new tree is a strict, honest extension of it (a consistency proof) — which is precisely how Certificate Transparency lets browsers detect a certificate authority that tries to quietly issue a fraudulent certificate and hide it from some observers but not others.
The chain in this lesson's code is the right size for the concept and for a service whose audit rate is modest; the tree is what production-scale tamper-evident logging actually uses, because the guarantee — "this specific record was in the log, and the log has not been secretly rewritten" — is the same guarantee, verifiable in logarithmic instead of linear time, and checkable per-record instead of only end-to-end.
Try it yourself
Work out what a Merkle inclusion proof actually needs
An audit log has grown to 1,000,000 entries, organised as a Merkle tree (so roughly 20 levels deep, since 2^20 is about a million). An auditor asks you to prove that entry #417,203 — a specific role grant — is genuinely part of the log, without asking you to re-hash all million entries in front of them.
What is the minimum information you need to hand them, and why does its size not depend on how large the log has grown to?
Why the proof stays small as the log grows
You need the leaf hash for entry #417,203, plus the sibling hash at each level on the path from that leaf up to the root — one sibling per level, about 20 of them for a million-entry tree — plus the published root hash (the anchor) to compare against. The auditor recomputes the path themselves: hash the leaf with its sibling to get the parent, hash that with the next sibling, and so on up to the root; if the recomputed root matches the anchored one, the entry is proven to be part of that exact tree. The proof's size is proportional to the tree's depth (log₂ of the entry count), not its size — doubling the log to two million entries adds only one more level, one more sibling hash, to every proof. That logarithmic growth is the entire reason Merkle trees replace linear hash chains once a log gets large: the chain's proof cost grows with every new entry, the tree's does not.
Misconceptions
- "A hash chain alone makes a log tamper-proof." It makes tampering detectable, and only once the head hash has been anchored somewhere the person who could rewrite the log cannot also rewrite. Without an anchor, a full rewrite (recomputing every hash consistently) passes verification perfectly, as the worked example shows.
- "Encrypting the audit log protects its integrity." Encryption protects confidentiality — who can read it. It says nothing about whether the ciphertext was altered, unless it is combined with an integrity mechanism (a MAC, a signature, or the hash-chain/Merkle approach above). A database administrator with write access to an encrypted audit table can still overwrite a row; they just cannot read what they are overwriting without the key.
Sources
- OWASP Logging Cheat Sheet.
- Certificate Transparency, RFC 6962 — Merkle tree inclusion and consistency proofs, in production use.
- NIST SP 800-92, "Guide to Computer Security Log Management".