#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
bootkit_diagnostic.py ─ INITIAL FORENSIC SNAPSHOT COLLECTOR
─────────────────────────────────────────────────────────────
Kali 2025.2 (KDE) – Python 3.12+
Author : DFIR Ops – May 2025
Goal : Read-only, atomic, world-class error-handled collection of the main
boot-related attack surfaces (MBR, ESP, GRUB, kernel modules, TPM,
Tripwire, YARA hits, Secure-Boot, firmware versions …) to give you an
immediate high–confidence health report WITHOUT touching any state.
EXIT-CODES
0 Everything executed (warnings may still be present – check report)
1 One or more critical tasks failed
LOGGING
• Console (INFO/WARN/CRIT)
• JSON artefact saved to /forensics/diag_<DATE>_<HOST>.json
• Human log saved to /forensics/diag_<DATE>_<HOST>.log
DEPENDENCIES
python3-psutil , python-yaml , Yara (CLI) , Tripwire , fwupd , tpm2-tools
"""
##############################################################################
import atexit
import datetime
import json
import os
import platform
import shutil
import subprocess
import sys
import tempfile
import textwrap
import threading
from hashlib import sha256
from pathlib import Path
from typing import Dict, List, Tuple, Any, Optional
# ────────────────────────────── Globals ──────────────────────────────────── #
HOSTNAME = platform.node()
NOW = datetime.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ')
OUT_DIR = Path("/forensics") if Path("/forensics").is_dir() else Path.cwd()
LOG_FILE = OUT_DIR / f"diag_{NOW}_{HOSTNAME}.log"
JSON_FILE= OUT_DIR / f"diag_{NOW}_{HOSTNAME}.json"
LOCKFILE = OUT_DIR / f".bootkit_diag.lock"
TIMEOUT = 60 # seconds for external commands
REPORT: Dict[str, Any] = {"meta": {"host": HOSTNAME, "timestamp": NOW},
"warnings": [], "results": {}}
EXIT_STATUS = 0 # 0 = OK, 1 = CRITICAL
# ───────────────────────────── Utilities ─────────────────────────────────── #
def _log(level: str, msg: str) -> None:
"""Atomic console + file logger"""
stamp = datetime.datetime.utcnow().strftime('%H:%M:%S')
line = f"[{stamp}] {level:<5} {msg}"
print(line)
try:
with LOG_FILE.open('a', encoding='utf-8') as fh:
fh.write(line + "\n")
except Exception: # noqa: BLE001
pass # Never let logging break execution
def _warn(msg: str) -> None:
REPORT["warnings"].append(msg)
_log("WARN", msg)
def _crit(msg: str) -> None:
global EXIT_STATUS
EXIT_STATUS = 1
_log("CRIT", msg)
def run_cmd(cmd: List[str],
desc: str,
timeout: int = TIMEOUT,
ok_rc: Tuple[int, ...] = (0, ),
env: Optional[Dict[str, str]] = None) -> Tuple[int, str, str]:
"""
Robust wrapper around subprocess.run
Returns (returncode, stdout, stderr)
"""
if shutil.which(cmd[0]) is None:
_warn(f"{desc}: command not found: {cmd[0]}")
return (127, "", f"{cmd[0]} not found")
try:
proc = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=timeout,
env=env,
check=False,
)
if proc.returncode not in ok_rc:
_warn(f"{desc}: non-zero exit {proc.returncode}")
return (proc.returncode, proc.stdout.strip(), proc.stderr.strip())
except subprocess.TimeoutExpired:
_crit(f"{desc}: TIMEOUT after {timeout}s")
return (124, "", "TIMEOUT")
except Exception as exc: # noqa: BLE001
_crit(f"{desc}: {exc!r}")
return (1, "", f"EXCEPTION:{exc!r}")
def hash_file(path: Path, block_size: int = 1 << 20) -> str:
"""Streaming SHA-256 of a file (read-only)"""
h = sha256()
try:
with path.open('rb') as fh:
for chunk in iter(lambda: fh.read(block_size), b''):
h.update(chunk)
return h.hexdigest()
except Exception as exc: # noqa: BLE001
_warn(f"Hashing failed for {path}: {exc}")
return "ERROR"
def atomic_lock() -> None:
"""Prevent concurrent executions"""
try:
LOCKFILE.touch(exist_ok=False)
except FileExistsError:
_crit(f"Lockfile {LOCKFILE} exists – another instance running?")
sys.exit(1)
def unlock() -> None:
try:
LOCKFILE.unlink(missing_ok=True)
except Exception: # noqa: BLE001
pass
atexit.register(unlock)
atomic_lock()
# ─────────────────── Data-collection sub-routines ───────────────────────── #
def collect_system_info() -> None:
REPORT["results"]["system_info"] = {
"os": platform.platform(),
"kernel": platform.release(),
"architecture": platform.machine(),
"python": platform.python_version(),
}
def check_mbr() -> None:
out_path = Path(tempfile.gettempdir()) / f"mbr_{NOW}.bin"
cmd = ["dd", "if=/dev/sda", "bs=512", "count=1"]
rc, out, err = run_cmd(cmd, "Read MBR", ok_rc=(0,))
if rc == 0:
try:
with out_path.open('wb') as fh:
fh.write(out.encode() if isinstance(out, str) else out) # type: ignore[arg-type]
mbr_hash = hash_file(out_path)
REPORT["results"]["mbr_sha256"] = mbr_hash
finally:
out_path.unlink(missing_ok=True)
else:
REPORT["results"]["mbr_sha256"] = "ERROR"
_warn(f"Unable to read MBR: {err}")
def scan_efi_partition() -> None:
esp = Path("/efi")
hits: List[Dict[str, str]] = []
if not esp.is_dir():
_warn("EFI partition not mounted at /efi")
REPORT["results"]["efi_scan"] = hits
return
yara_bin = shutil.which("yara")
rules_dir = Path("/opt/yara_rules")
if yara_bin and rules_dir.is_dir():
cmd = [yara_bin, "-r", str(rules_dir), str(esp)]
rc, out, _ = run_cmd(cmd, "YARA EFI scan", timeout=120)
if rc == 0 and out:
for line in out.splitlines():
rule, file_path = line.split(maxsplit=1)
hits.append({"rule": rule, "file": file_path})
else:
_warn("YARA not available – skipping EFI scan")
REPORT["results"]["efi_scan"] = hits
def secure_boot_status() -> None:
sbverify = shutil.which("sbverify")
shim_var = Path("/sys/firmware/efi")
status = "UNKNOWN"
if sbverify and shim_var.exists():
# Quick check on default Shim binary if present
shim = Path("/efi/EFI/BOOT/BOOTX64.EFI")
if shim.exists():
rc, _, _ = run_cmd([sbverify, "--list", str(shim)],
"sbverify", ok_rc=(0, 1, 2))
status = "ENABLED" if rc == 0 else "DISABLED/INVALID"
REPORT["results"]["secure_boot"] = status
def tripwire_check() -> None:
rc, out, _ = run_cmd(["tripwire", "--check", "-q"],
"Tripwire Check", timeout=180, ok_rc=(0, 1, 2))
anomalies = []
for line in out.splitlines():
if line.startswith("Modified:"):
anomalies.append(line.strip())
REPORT["results"]["tripwire_anomalies"] = anomalies
def kernel_module_scan() -> None:
suspicious: List[str] = []
rc, out, _ = run_cmd(["lsmod"], "List Kernel Modules")
if rc == 0:
for line in out.splitlines()[1:]:
parts = line.split()
if len(parts) >= 1:
modname = parts[0]
# Very lightweight heuristic
if modname.startswith(("root", "rk_", "hide", "kit")):
suspicious.append(modname)
REPORT["results"]["kernel_modules_suspicious"] = suspicious
def tpm_pcr_dump() -> None:
pcr_txt = "NOT_AVAILABLE"
if shutil.which("tpm2_pcrread"):
rc, out, _ = run_cmd(
["tpm2_pcrread", "sha256:0,2,4,7"],
"TPM PCR read", timeout=30)
if rc == 0:
pcr_txt = out
else:
_warn("tpm2_pcrread not installed")
REPORT["results"]["tpm_sha256_pcrs"] = pcr_txt
# ──────────────────────────── MAIN LOGIC ────────────────────────────────── #
def main() -> None:
threads = []
def _run(target):
try:
target()
except Exception as exc: # noqa: BLE001
_crit(f"Unhandled error in {target.__name__}: {exc!r}")
# Parallelise independent collectors to speed up ↯
for func in (collect_system_info, check_mbr, scan_efi_partition,
secure_boot_status, tripwire_check,
kernel_module_scan, tpm_pcr_dump):
th = threading.Thread(target=_run, args=(func,), daemon=True)
th.start()
threads.append(th)
for th in threads:
th.join()
# Persist JSON report
try:
with JSON_FILE.open("w", encoding="utf-8") as fh:
json.dump(REPORT, fh, indent=2)
_log("INFO", f"JSON report → {JSON_FILE}")
except Exception as exc: # noqa: BLE001
_crit(f"Failed to write JSON report: {exc!r}")
# Human summary
_log("INFO", "==== SUMMARY ====")
for key, val in REPORT["results"].items():
_log("INFO", f"{key}: {val if val else 'OK'}")
if REPORT["warnings"]:
_log("WARN", f"Warnings: {len(REPORT['warnings'])}")
_log("INFO", f"Exit-Status: {EXIT_STATUS}")
sys.exit(EXIT_STATUS)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
_crit("Interrupted by user (Ctrl-C)")
sys.exit(1)