Back
+30 XP
Concept

Append-Only Audit Trail with Tamper Seals

Compliance regulations mandate audit logs that cannot be altered retroactively without detection. A cryptographic hash chain seals each record with the SHA-256 hash of its payload and the preceding entry's seal. Altering or deleting any historical record breaks the seal chain.

python
import hashlib

# Hash chain linking:
seal = hashlib.sha256(f"{index}:{payload}:{prev_seal}".encode()).hexdigest()

# Append-Only Audit Trail with Tamper Seals If an attacker gains unauthorized access to your database or an insider manipulates balance records, their next move is always to modify the audit logs to erase their tracks. If your log is a plain text file, they simply `sed` or delete lines. 🛑📜 A **Cryptographic Hash Chain (Tamper Seal)** turns log entries into an immutable ledger: - Record $0$ has $\text{prev\_seal} = \text{0000...0000}$. - Record $N$ seal is computed as: $$\text{seal}_N = \text{SHA-256}(N \parallel \text{event\_json} \parallel \text{seal}_{N-1})$$ - If an attacker tampers with Record $2$, the recomputed seal for Record $2$ will not match its stored seal, and Record $3$’s reference to $\text{seal}_2$ will immediately break. One single altered byte collapses the entire downstream chain. ```python import hashlib def generate_seal(index: int, payload: str, prev_seal: str) -> str: raw = f"{index}:{payload}:{prev_seal}".encode("utf-8") return hashlib.sha256(raw).hexdigest() ``` ## Pop Quiz Why does embedding the previous entry's cryptographic hash into each new record prevent retroactive tampering? - [ ] Mutating any historical record alters its hash, invalidating the seals of every subsequent record down the chain. - [ ] The operating system automatically encrypts the file system inode using hardware TPM chips. - [ ] Previous hashes prevent multi-threaded race conditions in the Python logging module. - [ ] Because SHA-256 digests cannot be decoded without secret government keys. ## Real-World Challenge Implement `TamperEvidentLog`: - `append(event: dict) -> str`: Serializes event with deterministic key sorting, links to the previous entry's seal (or 64 zeros for the first entry), computes SHA-256 seal, and appends to the log. Returns the seal hash. - `verify_integrity() -> tuple[bool, int]`: Audits all records sequentially. Returns `(True, -1)` if completely valid, or `(False, corrupted_index)` at the first point of tampering. <details> <summary>Solution</summary> ```python import hashlib import json class TamperEvidentLog: def __init__(self): self.entries = [] def append(self, event_data: dict) -> str: index = len(self.entries) prev_seal = self.entries[-1]["seal"] if self.entries else "0" * 64 serialized = json.dumps(event_data, sort_keys=True) raw_seal_input = f"{index}:{serialized}:{prev_seal}".encode("utf-8") seal_hash = hashlib.sha256(raw_seal_input).hexdigest() entry = { "index": index, "data": event_data, "prev_seal": prev_seal, "seal": seal_hash } self.entries.append(entry) return seal_hash def verify_integrity(self) -> tuple[bool, int]: for idx, entry in enumerate(self.entries): # 1. Verify link to previous seal expected_prev = self.entries[idx - 1]["seal"] if idx > 0 else "0" * 64 if entry["prev_seal"] != expected_prev: return False, idx # 2. Recompute current seal serialized = json.dumps(entry["data"], sort_keys=True) raw_input = f"{entry['index']}:{serialized}:{entry['prev_seal']}".encode("utf-8") recalculated_seal = hashlib.sha256(raw_input).hexdigest() if entry["seal"] != recalculated_seal: return False, idx return True, -1 # Verification audit = TamperEvidentLog() s1 = audit.append({"event": "USER_CREATED", "uid": 1001}) s2 = audit.append({"event": "PRIVILEGE_ELEVATED", "uid": 1001, "role": "admin"}) is_valid, err_idx = audit.verify_integrity() assert is_valid is True assert err_idx == -1 # Tamper with first record: modify event payload audit.entries[0]["data"]["uid"] = 9999 is_valid, err_idx = audit.verify_integrity() assert is_valid is False assert err_idx == 0, f"Expected breach at index 0, got {err_idx}" ``` </details>