|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""File Integrity Monitor (FIM). |
| 3 | +
|
| 4 | +Two modes: |
| 5 | + - init: hash files and create baseline JSON |
| 6 | + - verify: re-hash and report modifications/additions/deletions |
| 7 | +
|
| 8 | +Usage: |
| 9 | + python -m cyber_security.file_integrity_monitor init --root /path --output baseline.json --glob "**/*.py" |
| 10 | + python -m cyber_security.file_integrity_monitor verify --root /path --baseline baseline.json |
| 11 | +""" |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +import argparse |
| 15 | +import fnmatch |
| 16 | +import hashlib |
| 17 | +import json |
| 18 | +import os |
| 19 | +import sys |
| 20 | +from dataclasses import dataclass |
| 21 | +from typing import Dict, Iterable |
| 22 | + |
| 23 | + |
| 24 | +@dataclass |
| 25 | +class FileHash: |
| 26 | + path: str |
| 27 | + sha256: str |
| 28 | + |
| 29 | + |
| 30 | +def iter_files(root: str, pattern: str | None) -> Iterable[str]: |
| 31 | + for base, _dirs, files in os.walk(root): |
| 32 | + for name in files: |
| 33 | + rel = os.path.relpath(os.path.join(base, name), root) |
| 34 | + if pattern is None or fnmatch.fnmatch(rel, pattern): |
| 35 | + yield rel |
| 36 | + |
| 37 | + |
| 38 | +def hash_file(root: str, rel_path: str) -> str: |
| 39 | + h = hashlib.sha256() |
| 40 | + abs_path = os.path.join(root, rel_path) |
| 41 | + with open(abs_path, "rb") as f: |
| 42 | + for chunk in iter(lambda: f.read(8192), b""): |
| 43 | + h.update(chunk) |
| 44 | + return h.hexdigest() |
| 45 | + |
| 46 | + |
| 47 | +def build_baseline(root: str, pattern: str | None) -> Dict[str, str]: |
| 48 | + result: Dict[str, str] = {} |
| 49 | + for rel in iter_files(root, pattern): |
| 50 | + try: |
| 51 | + result[rel] = hash_file(root, rel) |
| 52 | + except (PermissionError, FileNotFoundError): |
| 53 | + continue |
| 54 | + return result |
| 55 | + |
| 56 | + |
| 57 | +def write_json(path: str, data: Dict[str, str]) -> None: |
| 58 | + with open(path, "w", encoding="utf-8") as f: |
| 59 | + json.dump(data, f, indent=2, sort_keys=True) |
| 60 | + |
| 61 | + |
| 62 | +def read_json(path: str) -> Dict[str, str]: |
| 63 | + with open(path, "r", encoding="utf-8") as f: |
| 64 | + return json.load(f) |
| 65 | + |
| 66 | + |
| 67 | +def cmd_init(args: argparse.Namespace) -> int: |
| 68 | + baseline = build_baseline(args.root, args.glob) |
| 69 | + write_json(args.output, baseline) |
| 70 | + print(f"Baseline written: {args.output} ({len(baseline)} files)") |
| 71 | + return 0 |
| 72 | + |
| 73 | + |
| 74 | +def cmd_verify(args: argparse.Namespace) -> int: |
| 75 | + prior = read_json(args.baseline) |
| 76 | + current = build_baseline(args.root, None) |
| 77 | + |
| 78 | + added = sorted(set(current) - set(prior)) |
| 79 | + removed = sorted(set(prior) - set(current)) |
| 80 | + modified = sorted([p for p in set(current) & set(prior) if current[p] != prior[p]]) |
| 81 | + |
| 82 | + if added: |
| 83 | + print("Added:") |
| 84 | + for p in added: |
| 85 | + print(f" + {p}") |
| 86 | + if removed: |
| 87 | + print("Removed:") |
| 88 | + for p in removed: |
| 89 | + print(f" - {p}") |
| 90 | + if modified: |
| 91 | + print("Modified:") |
| 92 | + for p in modified: |
| 93 | + print(f" * {p}") |
| 94 | + |
| 95 | + if not (added or removed or modified): |
| 96 | + print("No changes detected.") |
| 97 | + return 0 |
| 98 | + |
| 99 | + return 1 |
| 100 | + |
| 101 | + |
| 102 | +def parse_args(argv: list[str]) -> argparse.Namespace: |
| 103 | + parser = argparse.ArgumentParser(description="File Integrity Monitor (FIM)") |
| 104 | + sub = parser.add_subparsers(dest="command", required=True) |
| 105 | + |
| 106 | + p_init = sub.add_parser("init", help="Create baseline JSON of file hashes") |
| 107 | + p_init.add_argument("--root", required=True, help="Root directory to scan") |
| 108 | + p_init.add_argument("--output", required=True, help="Path to baseline JSON output") |
| 109 | + p_init.add_argument("--glob", help="Glob-like pattern relative to root (e.g., **/*.py)") |
| 110 | + p_init.set_defaults(func=cmd_init) |
| 111 | + |
| 112 | + p_ver = sub.add_parser("verify", help="Verify current state against baseline JSON") |
| 113 | + p_ver.add_argument("--root", required=True, help="Root directory to scan") |
| 114 | + p_ver.add_argument("--baseline", required=True, help="Path to baseline JSON") |
| 115 | + p_ver.set_defaults(func=cmd_verify) |
| 116 | + |
| 117 | + return parser.parse_args(argv) |
| 118 | + |
| 119 | + |
| 120 | +def main(argv: list[str] | None = None) -> int: |
| 121 | + args = parse_args(sys.argv[1:] if argv is None else argv) |
| 122 | + return int(args.func(args)) |
| 123 | + |
| 124 | + |
| 125 | +if __name__ == "__main__": # pragma: no cover |
| 126 | + raise SystemExit(main()) |
0 commit comments