When attackers compromise a system, they often modify files: a backdoored binary, a changed configuration, a new script in a startup folder. File integrity monitoring (FIM) catches these changes by comparing files against a known good state. In this post you will build a simple FIM tool with Python's built-in hashlib module.
What is a hash?
A cryptographic hash function turns any file into a short, fixed-length fingerprint. With SHA-256:
- The same file always produces the same hash.
- Changing even one byte produces a completely different hash.
- It is practically impossible to create a different file with the same hash.
So if a file's hash changes, the file has changed.
Step 1: Hash a file safely
Large files should be read in chunks so they do not fill your memory:
import hashlib
from pathlib import Path
def sha256_of(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
digest.update(chunk)
return digest.hexdigest()
Step 2: Create a baseline
A baseline records the hash of every file in a folder while you know the system is clean:
import json
def build_baseline(folder: str) -> dict[str, str]:
root = Path(folder)
return {str(p): sha256_of(p) for p in root.rglob("*") if p.is_file()}
baseline = build_baseline("/etc/nginx")
Path("baseline.json").write_text(json.dumps(baseline, indent=2))
Store the baseline somewhere an attacker cannot easily modify it, ideally on a different machine.
Step 3: Compare and report changes
Later, build a fresh snapshot and compare it with the baseline:
def compare(old: dict[str, str], new: dict[str, str]) -> None:
added = new.keys() - old.keys()
deleted = old.keys() - new.keys()
changed = {p for p in old.keys() & new.keys() if old[p] != new[p]}
for label, files in (("ADDED", added), ("DELETED", deleted), ("CHANGED", changed)):
for path in sorted(files):
print(f"[{label}] {path}")
old = json.loads(Path("baseline.json").read_text())
compare(old, build_baseline("/etc/nginx"))
Set operations make the comparison short and fast, even with thousands of files.
Limits of a simple checker
Our script is a great learning tool, but production FIM needs more:
- Real-time detection instead of periodic scans.
- Who made the change and which process was involved.
- Central storage and alerting across many machines.
- Protection of the baseline itself.
These are exactly the features a platform like Wazuh provides out of the box, which we cover in our post on file integrity monitoring with Wazuh.
Practice ideas
- Run the checker on a schedule with
cronand email yourself the report. - Ignore files that are expected to change, such as logs.
- Record file permissions and owners as well as hashes.
Building tools like this is the heart of our Applied Python Programming course: small, practical scripts that teach both Python and real security concepts.
Learn this hands-on
Applied Python Programming
Write real security scripts with a guided lab for every concept.
View course