secure_boot.py
Secure Boot Configuration This script configures and manages Secure Boot to prevent bootkits and low-level rootkits from infecting the system.
- prevention
- python
- 435 lines
Run security tools only on systems you own or have written permission to test.
Run it
From the repository root, after
pip install -r tools/requirements.txtcd 03-malware-analysis/rootkits/prevention python3 secure_boot.py --help
Source
#!/usr/bin/env python3"""Secure Boot ConfigurationThis script configures and manages Secure Boot to prevent bootkitsand low-level rootkits from infecting the system.""" import osimport sysimport subprocessimport argparseimport platformimport shutilfrom datetime import datetimefrom colorama import init, Fore, Style init(autoreset=True) class SecureBootManager: """ Secure Boot Configuration and Management """ def __init__(self): self.system = platform.system() self.secure_boot_status = self.check_secure_boot_status() def check_secure_boot_status(self): """Check if Secure Boot is enabled""" if self.system == 'Windows': return self.check_secure_boot_windows() elif self.system == 'Linux': return self.check_secure_boot_linux() elif self.system == 'Darwin': return self.check_secure_boot_macos() else: return {'enabled': False, 'reason': 'Unsupported OS'} def check_secure_boot_windows(self): """Check Secure Boot status on Windows""" status = {'enabled': False, 'details': {}} try: # Method 1: Check using Confirm-SecureBootUEFI result = subprocess.run( ['powershell', '-Command', 'Confirm-SecureBootUEFI'], capture_output=True, text=True ) if 'True' in result.stdout: status['enabled'] = True status['details']['method'] = 'Confirm-SecureBootUEFI' # Method 2: Check using bcdedit result = subprocess.run( ['bcdedit', '/enum', '{current}'], capture_output=True, text=True ) if 'secureboot' in result.stdout.lower(): status['details']['bcdedit'] = 'SecureBoot flag present' # Method 3: Check using msinfo32 result = subprocess.run( ['powershell', '-Command', 'Get-WmiObject -Class Win32_ComputerSystem | Select-Object -ExpandProperty SecureBootState'], capture_output=True, text=True ) if '1' in result.stdout or 'True' in result.stdout: status['enabled'] = True status['details']['wmi'] = 'SecureBootState = 1' except Exception as e: status['error'] = str(e) return status def check_secure_boot_linux(self): """Check Secure Boot status on Linux""" status = {'enabled': False, 'details': {}} try: # Check /sys/firmware/efi/efivars if os.path.exists('/sys/firmware/efi'): status['details']['efi'] = 'UEFI detected' # Check SecureBoot variable secureboot_path = '/sys/firmware/efi/efivars/SecureBoot-*' import glob files = glob.glob(secureboot_path) for file in files: try: with open(file, 'rb') as f: data = f.read() if len(data) > 0 and data[-1] == 1: status['enabled'] = True status['details']['secureboot_var'] = 'SecureBoot enabled' except: pass # Check using mokutil if shutil.which('mokutil'): result = subprocess.run( ['mokutil', '--sb-state'], capture_output=True, text=True ) if 'enabled' in result.stdout.lower(): status['enabled'] = True status['details']['mokutil'] = result.stdout.strip() except Exception as e: status['error'] = str(e) return status def check_secure_boot_macos(self): """Check Secure Boot status on macOS""" status = {'enabled': False, 'details': {}} try: # Check using csrutil result = subprocess.run( ['csrutil', 'status'], capture_output=True, text=True ) if 'enabled' in result.stdout.lower(): status['enabled'] = True status['details']['csrutil'] = result.stdout.strip() # Check boot security result = subprocess.run( ['nvram', '-p'], capture_output=True, text=True ) if 'security-mode' in result.stdout: status['details']['nvram'] = 'Security mode configured' except Exception as e: status['error'] = str(e) return status def enable_secure_boot_windows(self): """Guide user to enable Secure Boot on Windows""" print(f"\n{Fore.CYAN}[*] Instructions to enable Secure Boot on Windows:{Style.RESET_ALL}") print(f"""{Fore.YELLOW}1. Restart your computer2. Enter UEFI/BIOS setup (usually F2, F10, Del during boot)3. Navigate to Boot or Security settings4. Find Secure Boot option5. Set Secure Boot to Enabled6. Save changes and exit{Fore.CYAN}Alternative: Use Windows PowerShell as Administrator:{Style.RESET_ALL} # Check if Secure Boot is supported Get-WmiObject -Class Win32_ComputerSystem | Select-Object -ExpandProperty SecureBootState # Convert to UEFI (if not already) mbr2gpt /convert /allowFullOS # Enable Secure Boot via UEFI firmware settings shutdown /r /fw /t 0 """) def enable_secure_boot_linux(self): """Guide user to enable Secure Boot on Linux""" print(f"\n{Fore.CYAN}[*] Instructions to enable Secure Boot on Linux:{Style.RESET_ALL}") print(f"""{Fore.YELLOW}1. Restart your computer2. Enter UEFI/BIOS setup (usually F2, F10, Del during boot)3. Navigate to Boot or Security settings4. Find Secure Boot option5. Set Secure Boot to Enabled6. Save changes and exit{Fore.CYAN}Using mokutil (if available):{Style.RESET_ALL} # Check current status sudo mokutil --sb-state # Enable Secure Boot (requires reboot) sudo mokutil --enable-validation{Fore.CYAN}Signing kernels for Secure Boot:{Style.RESET_ALL} # Install signing tools sudo apt-get install shim-signed mokutil # Sign a kernel module sudo kmodsign sha512 /var/lib/shim-signed/mok/MOK.priv /var/lib/shim-signed/mok/MOK.der module.ko """) def enable_secure_boot_macos(self): """Guide user to enable Secure Boot on macOS""" print(f"\n{Fore.CYAN}[*] Instructions to enable Secure Boot on macOS:{Style.RESET_ALL}") print(f"""{Fore.YELLOW}1. Restart your Mac and hold Command+R for Recovery Mode2. Open Terminal from Utilities menu3. Check current status: csrutil status4. Enable System Integrity Protection: csrutil enable5. Restart your Mac6. Go to System Settings → Privacy & Security7. Under Security, select "Full Security"{Fore.CYAN}For Apple Silicon Macs:{Style.RESET_ALL} Secure Boot is automatically enabled and managed by: - Hardware root of trust - Signed operating system - Verified boot chain """) def verify_boot_integrity(self): """Verify boot process integrity""" print(f"\n{Fore.CYAN}[*] Verifying boot integrity...{Style.RESET_ALL}") findings = [] if self.system == 'Windows': # Check BCD configuration result = subprocess.run(['bcdedit', '/enum'], capture_output=True, text=True) bcd_output = result.stdout # Check for boot configuration issues if 'bootstatuspolicy' in bcd_output: findings.append(('bootstatuspolicy', bcd_output)) # Check for Windows Boot Manager integrity if os.path.exists('C:\\Windows\\Boot\\EFI\\bootmgfw.efi'): findings.append(('bootmgfw_exists', 'Windows Boot Manager found')) elif self.system == 'Linux': # Check GRUB configuration if os.path.exists('/boot/grub/grub.cfg'): with open('/boot/grub/grub.cfg', 'r') as f: grub_cfg = f.read() if 'check_signatures' in grub_cfg: findings.append(('grub_signatures', 'GRUB signature checking enabled')) # Check for UEFI boot entries if os.path.exists('/sys/firmware/efi/efivars'): findings.append(('uefi_mode', 'System booting in UEFI mode')) for finding in findings: print(f"{Fore.GREEN} [✓] {finding[1]}{Style.RESET_ALL}") return findings def configure_boot_security(self): """Configure additional boot security measures""" print(f"\n{Fore.CYAN}[*] Configuring boot security...{Style.RESET_ALL}") if self.system == 'Windows': # Set boot configuration commands = [ # Enable early launch anti-malware ['bcdedit', '/set', '{current}', 'bootstatuspolicy', 'IgnoreAllFailures'], ['bcdedit', '/set', '{current}', 'recoveryenabled', 'No'], # Configure boot logging ['bcdedit', '/set', '{current}', 'bootlog', 'Yes'], # Set boot options ['bcdedit', '/set', '{current}', 'sos', 'Yes'], ] for cmd in commands: try: subprocess.run(cmd, check=True, capture_output=True) print(f"{Fore.GREEN} [✓] {' '.join(cmd)}{Style.RESET_ALL}") except Exception as e: print(f"{Fore.RED} [✗] {' '.join(cmd)}: {e}{Style.RESET_ALL}") elif self.system == 'Linux': # Configure GRUB security grub_configs = [ 'GRUB_ENABLE_BLSCFG=true', 'GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"', 'GRUB_DISABLE_OS_PROBER=false', 'GRUB_TIMEOUT=5', 'GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`', 'GRUB_GFXMODE=auto' ] grub_file = '/etc/default/grub' if os.path.exists(grub_file): with open(grub_file, 'r') as f: current_config = f.read() # Add missing security options security_options = [ 'GRUB_VERIFY_SIGNATURES=enabled', 'GRUB_ENABLE_CRYPTODISK=y' ] for opt in security_options: if opt not in current_config: with open(grub_file, 'a') as f: f.write(f'\n{opt}\n') print(f"{Fore.GREEN} [✓] Added {opt}{Style.RESET_ALL}") # Update GRUB subprocess.run(['update-grub'], check=True) print(f"{Fore.GREEN} [✓] GRUB configuration updated{Style.RESET_ALL}") def generate_security_report(self): """Generate boot security report""" report = { 'timestamp': datetime.now().isoformat(), 'system': platform.platform(), 'secure_boot': self.secure_boot_status, 'recommendations': self.get_recommendations() } report_file = f"secure_boot_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json" with open(report_file, 'w') as f: import json json.dump(report, f, indent=2) print(f"\n{Fore.GREEN}[✓] Report saved to {report_file}{Style.RESET_ALL}") return report_file def get_recommendations(self): """Get security recommendations""" recommendations = [] if not self.secure_boot_status.get('enabled', False): recommendations.append({ 'priority': 'HIGH', 'action': 'Enable Secure Boot', 'reason': 'Prevents bootkits and rootkits from loading before OS' }) if self.system == 'Windows': recommendations.extend([ { 'priority': 'MEDIUM', 'action': 'Enable BitLocker', 'reason': 'Protects against offline attacks' }, { 'priority': 'MEDIUM', 'action': 'Configure Windows Defender', 'reason': 'Early launch anti-malware protection' } ]) elif self.system == 'Linux': recommendations.extend([ { 'priority': 'MEDIUM', 'action': 'Enable LUKS disk encryption', 'reason': 'Protects against boot tampering' }, { 'priority': 'HIGH', 'action': 'Sign kernel modules', 'reason': 'Prevents unauthorized kernel modules' } ]) return recommendations def show_status(self): """Show Secure Boot status""" print(f"\n{Fore.CYAN}{'='*60}{Style.RESET_ALL}") print(f"{Fore.CYAN}🔒 SECURE BOOT STATUS{Style.RESET_ALL}") print(f"{Fore.CYAN}{'='*60}{Style.RESET_ALL}") if self.secure_boot_status.get('enabled', False): print(f"{Fore.GREEN} [✓] Secure Boot is ENABLED{Style.RESET_ALL}") else: print(f"{Fore.RED} [✗] Secure Boot is DISABLED{Style.RESET_ALL}") print(f"\n{Fore.CYAN}Details:{Style.RESET_ALL}") for key, value in self.secure_boot_status.get('details', {}).items(): print(f" {key}: {value}") if 'error' in self.secure_boot_status: print(f"{Fore.RED} Error: {self.secure_boot_status['error']}{Style.RESET_ALL}") # Show recommendations recommendations = self.get_recommendations() if recommendations: print(f"\n{Fore.YELLOW}Recommendations:{Style.RESET_ALL}") for rec in recommendations: priority_color = Fore.RED if rec['priority'] == 'HIGH' else Fore.YELLOW print(f" {priority_color}[{rec['priority']}]{Style.RESET_ALL} {rec['action']}") print(f" {rec['reason']}") print(f"\n{Fore.CYAN}{'='*60}{Style.RESET_ALL}") def main(): parser = argparse.ArgumentParser(description='Secure Boot Manager') parser.add_argument('--status', action='store_true', help='Show Secure Boot status') parser.add_argument('--enable', action='store_true', help='Show instructions to enable Secure Boot') parser.add_argument('--verify', action='store_true', help='Verify boot integrity') parser.add_argument('--configure', action='store_true', help='Configure boot security') parser.add_argument('--report', action='store_true', help='Generate security report') args = parser.parse_args() manager = SecureBootManager() if args.status: manager.show_status() if args.enable: if manager.system == 'Windows': manager.enable_secure_boot_windows() elif manager.system == 'Linux': manager.enable_secure_boot_linux() elif manager.system == 'Darwin': manager.enable_secure_boot_macos() if args.verify: manager.verify_boot_integrity() if args.configure: manager.configure_boot_security() if args.report: manager.generate_security_report() if not any([args.status, args.enable, args.verify, args.configure, args.report]): manager.show_status() if __name__ == "__main__": main()