#!/usr/bin/env python3
"""
Bootkit and System Integrity Diagnostic Tool
For Kali Linux KDE - Comprehensive System Analysis
"""
import os
import sys
import subprocess
import hashlib
import re
import json
import logging
import platform
import tempfile
import shutil
import time
import traceback
import threading
import queue
import signal
from datetime import datetime
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
# Configure logging with rotation
LOG_DIR = "/var/log/bootkit_scanner"
os.makedirs(LOG_DIR, exist_ok=True)
log_file = f"{LOG_DIR}/bootkit_scan_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - [%(funcName)s:%(lineno)d] - %(message)s',
handlers=[
logging.FileHandler(log_file),
logging.StreamHandler(sys.stdout)
]
)
logger = logging.getLogger("bootkit_scanner")
# Global variables
TEMP_DIR = tempfile.mkdtemp(prefix="bootkit_scan_")
RESULTS = {
"scan_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"system_info": {},
"boot_integrity": {},
"kernel_modules": {},
"firmware_analysis": {},
"memory_analysis": {},
"network_analysis": {},
"file_integrity": {},
"rootkit_detection": {},
"vulnerabilities": [],
"recommendations": []
}
SCAN_QUEUE = queue.Queue()
SCAN_RESULTS = queue.Queue()
STOP_EVENT = threading.Event()
class CommandExecutionError(Exception):
"""Exception raised when a command fails to execute properly."""
pass
class ScannerError(Exception):
"""Base exception for scanner errors."""
pass
class AtomicFileWriter:
"""Ensures atomic file writes to prevent corruption during writing."""
def __init__(self, filepath):
self.filepath = filepath
self.temp_filepath = f"{filepath}.tmp"
def __enter__(self):
return self
def write(self, data):
try:
with open(self.temp_filepath, 'w') as f:
f.write(data)
os.fsync(f.fileno())
except Exception as e:
logger.error(f"Failed to write to temporary file: {e}")
raise
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
try:
# Atomic rename
os.rename(self.temp_filepath, self.filepath)
except Exception as e:
logger.error(f"Failed to rename temporary file: {e}")
try:
os.unlink(self.temp_filepath)
except:
pass
raise
else:
try:
os.unlink(self.temp_filepath)
except:
pass
def run_command(command, timeout=60, shell=False):
"""
Execute a command safely with proper error handling and timeout.
Args:
command: Command to execute (list or string)
timeout: Maximum execution time in seconds
shell: Whether to use shell execution
Returns:
Tuple of (stdout, stderr, return_code)
"""
try:
if isinstance(command, str) and not shell:
command = command.split()
logger.debug(f"Executing command: {command}")
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=shell,
universal_newlines=True
)
stdout, stderr = process.communicate(timeout=timeout)
return_code = process.returncode
if return_code != 0:
logger.warning(f"Command returned non-zero exit code {return_code}: {command}")
logger.debug(f"stderr: {stderr}")
return stdout, stderr, return_code
except subprocess.TimeoutExpired:
logger.error(f"Command timed out after {timeout} seconds: {command}")
try:
process.kill()
except:
pass
return "", f"Command timed out after {timeout} seconds", -1
except Exception as e:
logger.error(f"Failed to execute command: {command}")
logger.error(f"Error: {str(e)}")
return "", str(e), -1
def is_root():
"""Check if the script is running with root privileges."""
return os.geteuid() == 0
def cleanup():
"""Clean up temporary files and resources."""
try:
logger.info("Cleaning up temporary files...")
shutil.rmtree(TEMP_DIR, ignore_errors=True)
except Exception as e:
logger.error(f"Error during cleanup: {e}")
def signal_handler(sig, frame):
"""Handle interrupt signals gracefully."""
logger.info("Received interrupt signal. Cleaning up and exiting...")
STOP_EVENT.set()
cleanup()
sys.exit(1)
def get_system_info():
"""Collect detailed system information."""
logger.info("Collecting system information...")
try:
system_info = {
"hostname": platform.node(),
"os": " ".join(platform.linux_distribution()),
"kernel": platform.release(),
"architecture": platform.machine(),
"processor": platform.processor(),
}
# Get CPU info
cpu_info, _, _ = run_command("lscpu")
system_info["cpu_details"] = cpu_info
# Get memory info
mem_info, _, _ = run_command("free -h")
system_info["memory_details"] = mem_info
# Get disk info
disk_info, _, _ = run_command("df -h")
system_info["disk_details"] = disk_info
# Get hardware info
hw_info, _, _ = run_command("lshw -short")
system_info["hardware_details"] = hw_info
# Get UEFI/BIOS info
if os.path.exists("/sys/firmware/efi"):
system_info["boot_type"] = "UEFI"
efi_vars, _, _ = run_command("ls -la /sys/firmware/efi/efivars")
system_info["efi_variables"] = efi_vars
else:
system_info["boot_type"] = "BIOS/Legacy"
# Get secure boot status
sb_status, _, _ = run_command("mokutil --sb-state")
system_info["secure_boot"] = sb_status
RESULTS["system_info"] = system_info
logger.info("System information collected successfully")
except Exception as e:
logger.error(f"Error collecting system information: {e}")
logger.error(traceback.format_exc())
RESULTS["system_info"] = {"error": str(e)}
def check_boot_integrity():
"""Check boot sector and bootloader integrity."""
logger.info("Checking boot integrity...")
boot_integrity = {
"boot_partition": {},
"bootloader": {},
"boot_configuration": {},
"suspicious_indicators": []
}
try:
# Identify boot partition
boot_part, _, _ = run_command("findmnt -n -o SOURCE /boot")
boot_integrity["boot_partition"]["device"] = boot_part.strip()
# Check if system is using UEFI
is_uefi = os.path.exists("/sys/firmware/efi")
boot_integrity["boot_type"] = "UEFI" if is_uefi else "BIOS/Legacy"
# Check GRUB configuration
if os.path.exists("/boot/grub/grub.cfg"):
grub_cfg_hash = hashlib.sha256()
with open("/boot/grub/grub.cfg", "rb") as f:
grub_cfg_hash.update(f.read())
boot_integrity["bootloader"]["grub_cfg_hash"] = grub_cfg_hash.hexdigest()
# Check for suspicious entries in GRUB config
with open("/boot/grub/grub.cfg", "r") as f:
grub_content = f.read()
suspicious_patterns = [
"insmod evil", "insmod rootkit", "chainloader",
"kernel /dev/", "kernel http", "kernel ftp"
]
for pattern in suspicious_patterns:
if pattern in grub_content:
boot_integrity["suspicious_indicators"].append(
f"Suspicious pattern '{pattern}' found in GRUB configuration"
)
# Check boot sector (MBR) for non-UEFI systems
if not is_uefi:
# Get the disk containing boot partition
disk_dev = boot_integrity["boot_partition"]["device"].rstrip("0123456789")
mbr_file = f"{TEMP_DIR}/mbr_dump"
# Dump MBR
run_command(f"dd if={disk_dev} of={mbr_file} bs=512 count=1")
# Calculate MBR hash
mbr_hash = hashlib.sha256()
with open(mbr_file, "rb") as f:
mbr_hash.update(f.read())
boot_integrity["boot_partition"]["mbr_hash"] = mbr_hash.hexdigest()
# Check for known malicious MBR signatures
with open(mbr_file, "rb") as f:
mbr_data = f.read()
# Example signatures (simplified)
malicious_sigs = [
b"\xEB\x58\x90\x4D\x53\x44\x4F\x53\x35\x2E", # Example bootkit signature
b"\x33\xC0\x8E\xD0\xBC\x00\x7C\x8E\xC0\x8E\xD8" # Another example
]
for sig in malicious_sigs:
if sig in mbr_data:
boot_integrity["suspicious_indicators"].append(
f"Potential bootkit signature found in MBR"
)
# For UEFI systems, check EFI System Partition
else:
efi_part, _, _ = run_command("findmnt -n -o SOURCE /boot/efi")
boot_integrity["boot_partition"]["efi_partition"] = efi_part.strip()
# List EFI binaries
efi_binaries, _, _ = run_command("find /boot/efi -name '*.efi'")
boot_integrity["bootloader"]["efi_binaries"] = efi_binaries.strip().split("\n")
# Check for suspicious EFI binaries
for binary in boot_integrity["bootloader"]["efi_binaries"]:
if os.path.exists(binary):
# Calculate hash
bin_hash = hashlib.sha256()
with open(binary, "rb") as f:
bin_hash.update(f.read())
# Check file size (unusually small or large EFI binaries can be suspicious)
file_size = os.path.getsize(binary)
if file_size < 10000 or file_size > 10000000: # Arbitrary thresholds
boot_integrity["suspicious_indicators"].append(
f"Unusual file size for EFI binary: {binary} ({file_size} bytes)"
)
# Check kernel images
kernel_images, _, _ = run_command("find /boot -name 'vmlinuz-*'")
boot_integrity["boot_configuration"]["kernel_images"] = kernel_images.strip().split("\n")
# Check initrd images
initrd_images, _, _ = run_command("find /boot -name 'initrd*' -o -name 'initramfs*'")
boot_integrity["boot_configuration"]["initrd_images"] = initrd_images.strip().split("\n")
# Check for signs of tampering in boot configuration
if os.path.exists("/etc/default/grub"):
with open("/etc/default/grub", "r") as f:
grub_default = f.read()
suspicious_grub_options = [
"init=/bin/sh", "init=/bin/bash", "init=/sbin/sh",
"single", "1", "s", "debug", "break"
]
for option in suspicious_grub_options:
if f"GRUB_CMDLINE_LINUX=\".*{option}.*\"" in grub_default:
boot_integrity["suspicious_indicators"].append(
f"Suspicious kernel parameter '{option}' in GRUB configuration"
)
RESULTS["boot_integrity"] = boot_integrity
logger.info("Boot integrity check completed")
except Exception as e:
logger.error(f"Error checking boot integrity: {e}")
logger.error(traceback.format_exc())
RESULTS["boot_integrity"] = {"error": str(e)}
def analyze_kernel_modules():
"""Analyze loaded kernel modules for suspicious indicators."""
logger.info("Analyzing kernel modules...")
kernel_modules = {
"loaded_modules": [],
"suspicious_modules": [],
"hidden_modules": []
}
try:
# Get list of loaded modules from lsmod
lsmod_output, _, _ = run_command("lsmod")
loaded_modules = []
for line in lsmod_output.strip().split("\n")[1:]: # Skip header
parts = line.split()
if len(parts) >= 1:
loaded_modules.append(parts[0])
kernel_modules["loaded_modules"] = loaded_modules
# Check each module
for module in loaded_modules:
module_info = {}
# Get module info
modinfo_output, _, _ = run_command(f"modinfo {module}")
module_info["info"] = modinfo_output
# Check if module is signed
if "signature:" in modinfo_output:
module_info["signed"] = True
else:
module_info["signed"] = False
kernel_modules["suspicious_modules"].append({
"module": module,
"reason": "Unsigned kernel module"
})
# Check module location
for line in modinfo_output.split("\n"):
if line.startswith("filename:"):
module_path = line.split("filename:")[1].strip()
module_info["path"] = module_path
# Check if module is in an unusual location
if not module_path.startswith(("/lib/modules/", "/usr/lib/modules/")):
kernel_modules["suspicious_modules"].append({
"module": module,
"reason": f"Module located in unusual path: {module_path}"
})
kernel_modules["loaded_modules_details"] = module_info
# Check for hidden modules by comparing /proc/modules with lsmod
proc_modules_output, _, _ = run_command("cat /proc/modules")
proc_modules = []
for line in proc_modules_output.strip().split("\n"):
parts = line.split()
if len(parts) >= 1:
proc_modules.append(parts[0])
# Find modules in /proc/modules but not in l