Project: File-Integrity Monitor
Attackers who get onto a server change files: a web shell dropped into the document root, a modified sshd_config that allows root logins, a new key in authorized_keys, a replaced binary, a new SUID file. A file-integrity monitor (FIM) notices: it records a baseline of every watched file (content hash, size, permissions, owner) and later reports what was added, removed or changed. Tools such as AIDE, Tripwire, OSSEC/Wazuh syscheck and osquery do this in production; PCI DSS requires it for payment systems. This project builds a small one and, more importantly, protects its baseline, because a FIM whose baseline the attacker can rewrite reports "no changes" forever.
Why a hash
A cryptographic hash changes completely when one bit of the file changes, and nobody can craft a different file with the same SHA-256. Flip single bits in the lab and watch about half of the 256 output bits change each time, while a simple checksum barely moves:
Size and modification time are cheaper to check but easy to fake: the pipelines lesson showed an intruder restoring a timestamp with touch. The content hash is the evidence; metadata is a fast pre-filter and extra detail.
The monitor, with a signed baseline
The core works on a dictionary path → (content, mode) so it can run here in the browser on a simulated file tree; the session after it runs the same logic on real files. The baseline is signed with HMAC-SHA256 (hashlib, hmac and secrets) using a key that, in a real deployment, lives off the monitored host. The key below is fixed so the output is stable; a real one comes from secrets.token_bytes(32).
import hashlib, hmac, json
KEY = b"lab-only-fim-key-0001" # real deployments: 32 bytes from secrets, stored off-host
def snapshot(files):
return {p: {"sha256": hashlib.sha256(c).hexdigest(), "size": len(c), "mode": oct(m)}
for p, (c, m) in sorted(files.items())}
def sign(baseline):
blob = json.dumps(baseline, sort_keys=True).encode()
return {"files": baseline, "hmac": hmac.new(KEY, blob, hashlib.sha256).hexdigest()}
def verify(signed):
blob = json.dumps(signed["files"], sort_keys=True).encode()
return hmac.compare_digest(signed["hmac"], hmac.new(KEY, blob, hashlib.sha256).hexdigest())
def diff(old, new):
out = []
for p in sorted(old.keys() | new.keys()):
if p not in new:
out.append(("REMOVED", p, ""))
elif p not in old:
out.append(("ADDED", p, f"mode {new[p]['mode']}"))
else:
changes = [k for k in ("sha256", "size", "mode") if old[p][k] != new[p][k]]
if changes:
detail = ", ".join(f"{k} {old[p][k][:12] if k == 'sha256' else old[p][k]} -> "
f"{new[p][k][:12] if k == 'sha256' else new[p][k]}" for k in changes)
out.append(("CHANGED", p, detail))
return out
files = {
"/etc/ssh/sshd_config": (b"PermitRootLogin no\nPasswordAuthentication no\n", 0o644),
"/home/alice/.ssh/authorized_keys": (b"ssh-ed25519 AAAAC3Nza...lab alice@ws1\n", 0o600),
"/usr/local/bin/backup": (b"#!/bin/sh\ntar czf /backup/site.tgz /var/www\n", 0o755),
"/var/www/html/index.html": (b"<h1>lab</h1>\n", 0o644),
}
stored = sign(snapshot(files))
print("baseline signed, files:", len(stored["files"]), "signature ok:", verify(stored))
# --- simulated intrusion on the lab host ---
files["/etc/ssh/sshd_config"] = (b"PermitRootLogin yes\nPasswordAuthentication no\n", 0o644)
files["/home/alice/.ssh/authorized_keys"] = (files["/home/alice/.ssh/authorized_keys"][0] +
b"ssh-ed25519 AAAAC3Nza...lab intruder@lab\n", 0o600)
files["/usr/local/bin/backup"] = (files["/usr/local/bin/backup"][0], 0o4755) # SUID added
files["/var/www/html/.cache.php"] = (b"<?php /* lab marker */ ?>\n", 0o644)
del files["/var/www/html/index.html"]
for kind, path, detail in diff(stored["files"], snapshot(files)):
print(f"{kind:<8} {path:<34} {detail}")
# The intruder rewrites the baseline to hide the changes, but has no key:
forged = {"files": snapshot(files), "hmac": stored["hmac"]}
print("forged baseline signature ok:", verify(forged))baseline signed, files: 4 signature ok: True
CHANGED /etc/ssh/sshd_config sha256 d65ec1c8aa7f -> 84265ee08586, size 45 -> 46
CHANGED /home/alice/.ssh/authorized_keys sha256 1965944b517d -> 9497ef16775c, size 38 -> 79
CHANGED /usr/local/bin/backup mode 0o755 -> 0o4755
ADDED /var/www/html/.cache.php mode 0o644
REMOVED /var/www/html/index.html
forged baseline signature ok: False
Every change of the intrusion shows up with the attribute that changed: the hash and size of sshd_config and authorized_keys (an extra key: persistence), only the mode of backup (the SUID bit 0o4755, a privilege-escalation backdoor that a content-only check would miss), an added hidden PHP file, and a removed page. When the intruder replaces the stored baseline with a fresh snapshot, the HMAC no longer matches, so the monitor reports tampering instead of "no changes".
On real files
The same idea in your sandbox, on a small tree with a symbolic link. A FIM must use lstat and record the link target rather than following it, or an attacker can point a watched path at a different file.
mkdir -p app/conf && cd app
printf 'debug=false\n' > conf/app.ini
printf '#!/bin/sh\necho run\n' > run.sh && chmod 755 run.sh
ln -s conf/app.ini current.ini
cat > ../fim.py <<'PY'
import hashlib, json, os, stat, sys
def entry(path):
st = os.lstat(path)
e = {"mode": oct(stat.S_IMODE(st.st_mode)), "type": "file"}
if stat.S_ISLNK(st.st_mode):
e.update(type="symlink", target=os.readlink(path))
elif stat.S_ISREG(st.st_mode):
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
h.update(chunk)
e.update(sha256=h.hexdigest()[:16], size=st.st_size)
return e
def snapshot(root):
out = {}
for d, dirs, names in os.walk(root, followlinks=False):
dirs.sort()
for n in sorted(names):
p = os.path.join(d, n)
out[os.path.relpath(p, root)] = entry(p)
return out
if sys.argv[1] == "init":
json.dump(snapshot("."), open(sys.argv[2], "w"), sort_keys=True, indent=1)
else:
old, new = json.load(open(sys.argv[2])), snapshot(".")
for p in sorted(old.keys() | new.keys()):
if old.get(p) != new.get(p):
print(p, old.get(p), "->", new.get(p))
PY
python3 ../fim.py init ../baseline.json
echo "== baseline"; cat ../baseline.json; echo
printf 'debug=true\n' > conf/evil.ini
ln -sf conf/evil.ini current.ini
chmod u+s run.sh
echo "== check"; python3 ../fim.py check ../baseline.json== baseline
{
"conf/app.ini": {
"mode": "0o644",
"sha256": "9844f3630c1726c7",
"size": 12,
"type": "file"
},
"current.ini": {
"mode": "0o777",
"target": "conf/app.ini",
"type": "symlink"
},
"run.sh": {
"mode": "0o755",
"sha256": "a4e0317eafab5cf1",
"size": 19,
"type": "file"
}
}
== check
conf/evil.ini None -> {'mode': '0o644', 'type': 'file', 'sha256': '6be7613f826ad354', 'size': 11}
current.ini {'mode': '0o777', 'target': 'conf/app.ini', 'type': 'symlink'} -> {'mode': '0o777', 'type': 'symlink', 'target': 'conf/evil.ini'}
run.sh {'mode': '0o755', 'sha256': 'a4e0317eafab5cf1', 'size': 19, 'type': 'file'} -> {'mode': '0o4755', 'type': 'file', 'sha256': 'a4e0317eafab5cf1', 'size': 19}
The content of conf/app.ini did not change, so a monitor that followed the link would see current.ini "change" only through its target. Recording the link itself shows exactly what happened: a new file conf/evil.ini appeared, current.ini now points at it, and run.sh gained the SUID bit (0o4755) with its content unchanged.
How file tampering is detected
- Scheduled FIM runs (AIDE, Wazuh syscheck, osquery
file_events) on configuration, binaries, web roots,authorized_keys, cron and systemd directories. - Real-time watches: Linux
inotify/fanotifyor audit rules (auditctl -w /etc/ssh/sshd_config -p wa -k sshd) record who changed a file and when, which a periodic hash diff can't. - Package verification:
dpkg --verifyorrpm -Vacompare installed files with the package database's hashes, catching replaced system binaries without a custom baseline.
How to make the monitor trustworthy (prevention)
- Protect the baseline: sign it (HMAC or a signature) with a key kept off the host, or store it on another system or read-only media. Same for the tool itself.
- Record metadata as well as content: mode (SUID/SGID, world-writable), owner, symlink targets, file type.
- Exclude what changes legitimately (logs, caches) explicitly and narrowly, and review the exclusion list: attackers love excluded directories.
- Update the baseline only through change management: after a deployment, re-baseline from a known-good state, never automatically.
- Send results off the host as they are produced, so an intruder who disables the monitor leaves a gap that is itself an alert.
Pitfalls
- Following symlinks or hashing device files and FIFOs (which can block forever). Use
lstatand skip non-regular files. - Race conditions: a file can change between
statandopen; compare the size after reading. - Truncated hashes in reports (16 hex characters here, for readability) are fine for display, not for the stored baseline.
- A FIM is not prevention: it tells you after the fact. Pair it with least privilege and immutable deployments.
Practice
1. Add owner and group to snapshot in the browser version. Which intrusion step would that catch that the current version misses?
Add "uid": st.st_uid, "gid": st.st_gid in the real tool (and simulated values in the browser one). A chown root:root on an attacker-controlled script, combined with SUID, would otherwise only show the mode change.
2. The intruder knows the HMAC key is on the same server. What does the signature still give you?
Nothing against that intruder: with the key, they can re-sign a forged baseline. The key must live where the monitored host can't read it (the central server verifies, or the baseline is signed with a private key whose public half is the only thing on the host).
3. Why does the browser version compare mode as a separate field instead of including it in the hash?
So the report says what changed. A single hash over content and metadata would show "changed" for the SUID file without telling the analyst it was a permission change, which is the most important detail for that finding.
Practice problem in 21 languages: Adler-32 Checksum.
Test yourself
Which change would a content-hash-only monitor miss in the example?
- The extra SSH key
- The SUID bit added to /usr/local/bin/backup
- The new PHP file
- The removed index.html
The intruder replaced the stored baseline with a fresh snapshot. Why did verification fail?
- The snapshot was empty
- The HMAC over the forged baseline doesn't match without the key
- JSON can't be changed
- SHA-256 is slow
Why does the real-file monitor use os.lstat and os.readlink?
- They are faster
- To record a symbolic link itself and its target instead of following it
- To read hidden files
- To change permissions
Which tool records who changed /etc/ssh/sshd_config, not only that it changed?
- sha256sum
- An audit watch rule (auditctl -w ... -p wa)
- find -newer
- A nightly hash diff