Published Agent Skill package. Follow the instructions in SKILL.md to complete the user's task.

analyzing-bootkit-and-rootkit-samples

'Analyzes bootkit and advanced rootkit malware infecting the Master

This page contains 4 files from the original skill zip. Supporting markdown and scripts are included below so you do not need extra downloads.

Files in this package

SKILL.md

Analyzing Bootkit and Rootkit Samples

When to Use

Do not use for standard user-mode malware; bootkits and rootkits operate at a fundamentally different level requiring specialized analysis techniques.

Prerequisites

Workflow

Step 1: Acquire Boot Sectors and Firmware

Extract MBR, VBR, and UEFI firmware for offline analysis:

# Acquire MBR (first 512 bytes of disk)
dd if=/dev/sda of=mbr.bin bs=512 count=1

# Acquire first track (usually contains bootkit code beyond MBR)
dd if=/dev/sda of=first_track.bin bs=512 count=63

# Acquire VBR (Volume Boot Record - first sector of partition)
dd if=/dev/sda1 of=vbr.bin bs=512 count=1

# Acquire UEFI System Partition
mkdir /mnt/efi
mount /dev/sda1 /mnt/efi
cp -r /mnt/efi/EFI /analysis/efi_backup/

# Dump UEFI firmware (requires chipsec or flashrom)
# Using chipsec:
python chipsec_util.py spi dump firmware.rom

# Using flashrom:
flashrom -p internal -r firmware.rom

# Verify firmware dump integrity
sha256sum firmware.rom

Step 2: Analyze MBR/VBR for Bootkit Code

Examine boot sector code for malicious modifications:

# Disassemble MBR code (16-bit real mode)
ndisasm -b16 mbr.bin > mbr_disasm.txt

# Compare MBR with known-good Windows MBR
# Standard Windows MBR begins with: EB 5A 90 (JMP 0x5C, NOP)
# Standard Windows 10 MBR: 33 C0 8E D0 BC 00 7C (XOR AX,AX; MOV SS,AX; MOV SP,7C00h)

python3 << 'PYEOF'
with open("mbr.bin", "rb") as f:
    mbr = f.read()

# Check MBR signature (bytes 510-511 should be 0x55AA)
if mbr[510:512] == b'\x55\xAA':
    print("[*] Valid MBR signature (0x55AA)")
else:
    print("[!] Invalid MBR signature")

# Check for known bootkit signatures
bootkit_sigs = {
    b'\xE8\x00\x00\x5E\x81\xEE': "TDL4/Alureon bootkit",
    b'\xFA\x33\xC0\x8E\xD0\xBC\x00\x7C\x8B\xF4\x50\x07': "Standard Windows MBR (clean)",
    b'\xEB\x5A\x90\x4E\x54\x46\x53': "Standard NTFS VBR (clean)",
}

for sig, name in bootkit_sigs.items():
    if sig in mbr:
        print(f"[{'!' if 'clean' not in name else '*'}] Signature match: {name}")

# Check partition table entries
print("\nPartition Table:")
for i in range(4):
    offset = 446 + (i * 16)
    entry = mbr[offset:offset+16]
    if entry != b'\x00' * 16:
        boot_flag = "Active" if entry[0] == 0x80 else "Inactive"
        part_type = entry[4]
        start_lba = int.from_bytes(entry[8:12], 'little')
        size_lba = int.from_bytes(entry[12:16], 'little')
        print(f"  Partition {i+1}: Type=0x{part_type:02X} {boot_flag} Start=LBA {start_lba} Size={size_lba} sectors")
PYEOF

Step 3: Analyze UEFI Firmware for Implants

Inspect UEFI firmware volumes for unauthorized modules:

# Extract UEFI firmware components with UEFITool
# GUI: Open firmware.rom -> Inspect firmware volumes
# CLI:
UEFIExtract firmware.rom all

# List all DXE drivers (most common target for UEFI implants)
find firmware.rom.dump -name "*.efi" -exec file {} \;

# Compare against known-good firmware module list
# Each UEFI module has a GUID - compare against vendor baseline

# Verify Secure Boot configuration
python chipsec_main.py -m common.secureboot.variables

# Check SPI flash write protection
python chipsec_main.py -m common.bios_wp

# Check for known UEFI malware patterns
yara -r uefi_malware.yar firmware.rom
Known UEFI Bootkit Detection Points:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
LoJax (APT28):
  - Modified SPI flash
  - Added DXE driver that drops agent to Windows
  - Persists through OS reinstall and disk replacement

BlackLotus:
  - Exploits CVE-2022-21894 to bypass Secure Boot
  - Modifies EFI System Partition bootloader
  - Installs kernel driver during boot

CosmicStrand:
  - Modifies CORE_DXE firmware module
  - Hooks kernel initialization during boot
  - Drops shellcode into Windows kernel memory

MoonBounce:
  - SPI flash implant in CORE_DXE module
  - Modified GetVariable() function
  - Deploys user-mode implant through boot chain

ESPecter:
  - Modifies Windows Boot Manager on ESP
  - Patches winload.efi to disable DSE
  - Loads unsigned kernel driver

Step 4: Detect Kernel-Level Rootkit Behavior

Analyze the running system for rootkit artifacts:

# Memory forensics for rootkit detection
# SSDT hook detection
vol3 -f memory.dmp windows.ssdt | grep -v "ntoskrnl\|win32k"

# Hidden processes (DKOM)
vol3 -f memory.dmp windows.psscan > psscan.txt
vol3 -f memory.dmp windows.pslist > pslist.txt
# Diff to find hidden processes

# Kernel callback registration (rootkits register callbacks for filtering)
vol3 -f memory.dmp windows.callbacks

# Driver analysis
vol3 -f memory.dmp windows.driverscan
vol3 -f memory.dmp windows.modules

# Check for unsigned drivers
vol3 -f memory.dmp windows.driverscan | while read line; do
    driver_path=$(echo "$line" | awk '{print $NF}')
    if [ -f "$driver_path" ]; then
        sigcheck -nobanner "$driver_path" 2>/dev/null | grep "Unsigned"
    fi
done

# IDT hook detection
vol3 -f memory.dmp windows.idt

Step 5: Boot Process Integrity Verification

Verify the integrity of the entire boot chain:

# Verify Windows Boot Manager signature
sigcheck -a C:\Windows\Boot\EFI\bootmgfw.efi

# Verify winload.efi
sigcheck -a C:\Windows\System32\winload.efi

# Verify ntoskrnl.exe
sigcheck -a C:\Windows\System32\ntoskrnl.exe

# Check Measured Boot logs (if TPM is available)
# Windows: BCDEdit /enum firmware
bcdedit /enum firmware

# Verify Secure Boot state
Confirm-SecureBootUEFI  # PowerShell cmdlet

# Check boot configuration for tampering
bcdedit /v

# Look for boot configuration changes
# testsigning: should be No
# nointegritychecks: should be No
# debug: should be No
bcdedit | findstr /i "testsigning nointegritychecks debug"

Step 6: Document Bootkit/Rootkit Analysis

Compile comprehensive analysis findings:

Analysis should document:
- Boot sector (MBR/VBR) integrity status with hex comparison
- UEFI firmware module inventory and integrity verification
- Secure Boot status and any bypass mechanisms detected
- Kernel-level hooks (SSDT, IDT, IRP, inline) identified
- Hidden processes, drivers, and files discovered
- Persistence mechanism (SPI flash, ESP, MBR, kernel driver)
- Boot chain integrity verification results
- Attribution to known bootkit families if possible
- Remediation steps (reflash firmware, rebuild MBR, replace hardware)

Key Concepts

Term Definition
Bootkit Malware that infects the boot process (MBR, VBR, UEFI) to execute before the operating system loads, gaining persistent low-level control
MBR (Master Boot Record) First 512 bytes of a disk containing bootstrap code and partition table; MBR bootkits replace this code with malicious loaders
UEFI (Unified Extensible Firmware Interface) Modern firmware interface replacing BIOS; UEFI bootkits implant malicious modules in firmware volumes or modify the ESP
Secure Boot UEFI security feature verifying digital signatures of boot components; bootkits like BlackLotus exploit vulnerabilities to bypass it
SPI Flash Flash memory chip storing UEFI firmware; advanced bootkits like LoJax and MoonBounce modify SPI flash for firmware-level persistence
DKOM (Direct Kernel Object Manipulation) Rootkit technique modifying kernel structures to hide processes, files, and network connections without hooking functions
Driver Signature Enforcement (DSE) Windows security feature requiring kernel drivers to be digitally signed; bootkits disable DSE during boot to load unsigned rootkit drivers

Tools & Systems

Common Scenarios

Scenario: Investigating Persistent Compromise Surviving OS Reinstallation

Context: An organization reimaged a compromised workstation, but the same C2 beaconing resumed within hours. Standard disk forensics finds no malware. UEFI bootkit is suspected.

Approach:

  1. Boot from a Linux live USB to avoid executing any compromised OS components
  2. Dump the SPI flash firmware using chipsec or flashrom for offline analysis
  3. Dump the MBR and VBR sectors with dd for boot sector analysis
  4. Copy the EFI System Partition for bootloader integrity verification
  5. Open the SPI dump in UEFITool and compare module GUIDs against vendor-provided firmware
  6. Look for additional or modified DXE drivers that should not be present
  7. Analyze any suspicious modules with Ghidra (x86_64 UEFI module format)
  8. Verify Secure Boot configuration and check for exploit-based bypasses

Pitfalls:

Output Format

BOOTKIT / ROOTKIT ANALYSIS REPORT
====================================
System:           Dell OptiPlex 7090 (UEFI, TPM 2.0)
Firmware Version: 1.15.0 (Dell)
Secure Boot:      ENABLED (but bypassed)
Capture Method:   Linux Live USB + chipsec SPI dump

MBR/VBR ANALYSIS
MBR Signature:    Valid (0x55AA)
MBR Code:         MATCHES standard Windows 10 MBR (clean)
VBR Code:         MATCHES standard NTFS VBR (clean)

UEFI FIRMWARE ANALYSIS
Total Modules:    287
Vendor Expected:  285
Extra Modules:    2 UNAUTHORIZED
  [!] DXE Driver GUID: {ABCD1234-...} "SmmAccessDxe_mod" (MODIFIED)
      Original Size: 12,288 bytes
      Current Size:  45,056 bytes (32KB ADDED)
      Entropy: 7.82 (HIGH - encrypted payload)

  [!] DXE Driver GUID: {EFGH5678-...} "UefiPayloadDxe" (NEW - not in vendor firmware)
      Size: 28,672 bytes
      Function: Drops persistence agent during boot

BOOT CHAIN INTEGRITY
bootmgfw.efi:     MODIFIED (hash mismatch, Secure Boot bypass via CVE-2022-21894)
winload.efi:      MODIFIED (DSE disabled at load time)
ntoskrnl.exe:     CLEAN (but unsigned driver loaded after boot)

KERNEL ROOTKIT COMPONENTS
Driver:           C:\Windows\System32\drivers\null_mod.sys (unsigned, hidden)
SSDT Hooks:       3 (NtQuerySystemInformation, NtQueryDirectoryFile, NtDeviceIoControlFile)
Hidden Processes: 2 (PID 6784: beacon.exe, PID 6812: keylog.exe)
Hidden Files:     C:\Windows\System32\drivers\null_mod.sys

ATTRIBUTION
Family:           BlackLotus variant
Confidence:       HIGH (CVE-2022-21894 exploit, ESP modification pattern matches)

REMEDIATION
1. Reflash SPI firmware with clean vendor image via hardware programmer
2. Rebuild EFI System Partition from clean Windows installation media
3. Reinstall OS from verified media
4. Enable all firmware write protections
5. Update firmware to latest version (patches CVE-2022-21894)

Supporting file: LICENSE

This file is part of the analyzing-bootkit-and-rootkit-samples skill package. Use it when SKILL.md references LICENSE.


                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to the Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by the Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding any notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. Please do not remove or change
      the license header comment from a contributed file except when
      necessary.

   Copyright 2026 mukul975

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

Supporting file: references/api-reference.md

This file is part of the analyzing-bootkit-and-rootkit-samples skill package. Use it when SKILL.md references references/api-reference.md.

API Reference: Bootkit and Rootkit Analysis Tools

dd - Boot Sector Extraction

Syntax

dd if=/dev/sda of=mbr.bin bs=512 count=1          # MBR
dd if=/dev/sda of=first_track.bin bs=512 count=63  # First track
dd if=/dev/sda1 of=vbr.bin bs=512 count=1          # VBR

ndisasm - 16-bit Disassembly

Syntax

ndisasm -b16 mbr.bin > mbr_disasm.txt
ndisasm -b16 -o 0x7C00 mbr.bin   # Set origin to MBR load address

Key Flags

Flag Description
-b16 16-bit real-mode disassembly
-b32 32-bit protected-mode
-o Origin address offset

UEFITool - Firmware Analysis

CLI Syntax

UEFIExtract firmware.rom all             # Extract all modules
UEFIExtract firmware.rom <GUID> body     # Extract specific module body

Output

Extracts firmware volumes into a directory tree with each DXE driver, PEI module, and option ROM as separate files identified by GUID.

chipsec - Hardware Security Assessment

Syntax

python chipsec_main.py -m common.secureboot.variables  # Check Secure Boot
python chipsec_main.py -m common.bios_wp               # SPI write protection
python chipsec_main.py -m common.spi_lock               # SPI lock status
python chipsec_util.py spi dump firmware.rom            # Dump SPI flash

Key Modules

Module Purpose
common.secureboot.variables Verify Secure Boot configuration
common.bios_wp Check BIOS write protection
common.spi_lock Verify SPI flash lock bits
common.smm SMM protection verification

Volatility 3 - Rootkit Detection Plugins

Syntax

vol3 -f memory.dmp <plugin>

Rootkit Detection Plugins

Plugin Purpose
windows.ssdt System Service Descriptor Table hooks
windows.callbacks Kernel callback registrations
windows.driverscan Scan for driver objects
windows.modules List loaded kernel modules
windows.psscan Pool-tag scan for processes (finds hidden)
windows.pslist Active process list (DKOM-affected)
windows.idt Interrupt Descriptor Table hooks

Output Format

Offset  Order  Module         Section  Owner
------- -----  ------         -------  -----
0x...   0      ntoskrnl.exe   .text    ntoskrnl.exe
0x...   73     UNKNOWN        -        rootkit.sys   ← suspicious

flashrom - SPI Flash Dumping

Syntax

flashrom -p internal -r firmware.rom     # Read/dump
flashrom -p internal -w clean.rom        # Write/reflash
flashrom -p internal --verify clean.rom  # Verify flash contents

YARA - Firmware Pattern Scanning

Syntax

yara -r uefi_malware.yar firmware.rom
yara -s -r rules.yar firmware.rom   # Show matching strings

Supporting file: scripts/agent.py

This file is part of the analyzing-bootkit-and-rootkit-samples skill package. Use it when SKILL.md references scripts/agent.py.

#!/usr/bin/env python3
"""Bootkit and rootkit analysis agent for MBR/VBR/UEFI inspection and rootkit detection."""

import struct
import hashlib
import os
import sys
import subprocess
import math
from collections import Counter


def read_mbr(disk_path_or_file):
    """Read and parse the first 512 bytes (MBR) from a disk image or device."""
    with open(disk_path_or_file, "rb") as f:
        mbr = f.read(512)
    return mbr


def validate_mbr_signature(mbr_data):
    """Check the MBR boot signature at bytes 510-511 (should be 0x55AA)."""
    sig = mbr_data[510:512]
    valid = sig == b"\x55\xAA"
    return valid, sig.hex()


def parse_partition_table(mbr_data):
    """Parse the four 16-byte partition table entries starting at offset 446."""
    partitions = []
    for i in range(4):
        offset = 446 + (i * 16)
        entry = mbr_data[offset:offset + 16]
        if entry == b"\x00" * 16:
            continue
        boot_flag = entry[0]
        part_type = entry[4]
        start_lba = struct.unpack_from("<I", entry, 8)[0]
        size_lba = struct.unpack_from("<I", entry, 12)[0]
        partitions.append({
            "index": i + 1,
            "active": boot_flag == 0x80,
            "type_id": f"0x{part_type:02X}",
            "start_lba": start_lba,
            "size_sectors": size_lba,
            "size_mb": round(size_lba * 512 / (1024 * 1024), 1),
        })
    return partitions


BOOTKIT_SIGNATURES = {
    b"\xE8\x00\x00\x5E\x81\xEE": "TDL4/Alureon bootkit",
    b"\xFA\x33\xC0\x8E\xD0\xBC\x00\x7C\x8B\xF4\x50\x07": "Standard Windows MBR (clean)",
    b"\xEB\x5A\x90\x4E\x54\x46\x53": "Standard NTFS VBR (clean)",
    b"\xEB\x52\x90\x4E\x54\x46\x53": "NTFS VBR variant (clean)",
    b"\x33\xC0\x8E\xD0\xBC\x00\x7C": "Windows 10 MBR (clean)",
}


def scan_bootkit_signatures(data):
    """Scan boot sector data against known bootkit signatures."""
    matches = []
    for sig, name in BOOTKIT_SIGNATURES.items():
        if sig in data:
            offset = data.find(sig)
            matches.append({"signature": name, "offset": offset, "clean": "clean" in name})
    return matches


def calculate_entropy(data):
    """Calculate Shannon entropy of binary data."""
    if not data:
        return 0.0
    counter = Counter(data)
    length = len(data)
    entropy = -sum(
        (count / length) * math.log2(count / length)
        for count in counter.values()
    )
    return round(entropy, 4)


def read_first_track(disk_path, num_sectors=63):
    """Read the first track (typically 63 sectors) for extended bootkit code."""
    with open(disk_path, "rb") as f:
        data = f.read(num_sectors * 512)
    return data


def analyze_boot_code(mbr_data):
    """Analyze MBR bootstrap code (bytes 0-445) for suspicious patterns."""
    boot_code = mbr_data[:446]
    entropy = calculate_entropy(boot_code)
    sha256 = hashlib.sha256(boot_code).hexdigest()
    suspicious_patterns = []
    # Check for INT 13h hooking (common bootkit technique)
    if b"\xCD\x13" in boot_code:
        count = boot_code.count(b"\xCD\x13")
        suspicious_patterns.append(f"INT 13h calls: {count}")
    # Check for far jumps to unusual addresses
    if b"\xEA" in boot_code:
        suspicious_patterns.append("Far JMP instruction found")
    # Check for self-modifying code patterns
    if b"\xF3\xA4" in boot_code or b"\xF3\xA5" in boot_code:
        suspicious_patterns.append("REP MOVSB/MOVSW (memory copy, possible code relocation)")
    return {
        "entropy": entropy,
        "sha256": sha256,
        "high_entropy": entropy > 6.5,
        "suspicious_patterns": suspicious_patterns,
    }


def run_volatility_rootkit_scan(memory_dump, plugin):
    """Run a Volatility 3 plugin for rootkit detection via subprocess."""
    result = subprocess.run(
        ["vol3", "-f", memory_dump, plugin],
        capture_output=True, text=True,
        timeout=120,
    )
    return result.stdout, result.stderr, result.returncode


def detect_kernel_rootkit(memory_dump):
    """Run multiple Volatility plugins to detect kernel-level rootkit artifacts."""
    plugins = [
        "windows.ssdt",
        "windows.callbacks",
        "windows.driverscan",
        "windows.modules",
        "windows.psscan",
        "windows.pslist",
    ]
    results = {}
    for plugin in plugins:
        stdout, stderr, rc = run_volatility_rootkit_scan(memory_dump, plugin)
        results[plugin] = {"output": stdout, "error": stderr, "return_code": rc}
    return results


def compare_process_lists(pslist_output, psscan_output):
    """Compare pslist and psscan output to find hidden processes (DKOM)."""
    pslist_pids = set()
    psscan_pids = set()
    for line in pslist_output.splitlines():
        parts = line.split()
        if len(parts) >= 2 and parts[1].isdigit():
            pslist_pids.add(int(parts[1]))
    for line in psscan_output.splitlines():
        parts = line.split()
        if len(parts) >= 2 and parts[1].isdigit():
            psscan_pids.add(int(parts[1]))
    hidden = psscan_pids - pslist_pids
    return hidden


if __name__ == "__main__":
    print("=" * 60)
    print("Bootkit & Rootkit Analysis Agent")
    print("MBR/VBR inspection, UEFI firmware analysis, rootkit detection")
    print("=" * 60)

    # Demo with a sample MBR file if available
    demo_mbr = "mbr.bin"
    if len(sys.argv) > 1:
        demo_mbr = sys.argv[1]

    if os.path.exists(demo_mbr):
        print(f"\n[*] Analyzing: {demo_mbr}")
        mbr = read_mbr(demo_mbr)
        valid, sig_hex = validate_mbr_signature(mbr)
        print(f"[*] MBR Signature: 0x{sig_hex.upper()} ({'Valid' if valid else 'INVALID'})")

        partitions = parse_partition_table(mbr)
        print(f"[*] Partition entries: {len(partitions)}")
        for p in partitions:
            active = "Active" if p["active"] else "Inactive"
            print(f"    Part {p['index']}: Type={p['type_id']} {active} "
                  f"Start=LBA {p['start_lba']} Size={p['size_mb']} MB")

        sigs = scan_bootkit_signatures(mbr)
        for s in sigs:
            tag = "[*]" if s["clean"] else "[!]"
            print(f"{tag} Signature match: {s['signature']} at offset {s['offset']}")

        analysis = analyze_boot_code(mbr)
        print(f"[*] Boot code entropy: {analysis['entropy']}"
              f" ({'HIGH - possible encryption' if analysis['high_entropy'] else 'Normal'})")
        print(f"[*] Boot code SHA-256: {analysis['sha256']}")
        for pat in analysis["suspicious_patterns"]:
            print(f"[!] {pat}")
    else:
        print(f"\n[DEMO] No MBR file provided. Usage: {sys.argv[0]} <mbr.bin | /dev/sda>")
        print("[DEMO] Provide a 512-byte MBR dump or disk device for analysis.")
        print("\n[*] Supported analysis:")
        print("    - MBR/VBR signature validation and bootkit detection")
        print("    - Partition table parsing and anomaly detection")
        print("    - Boot code entropy and pattern analysis")
        print("    - Volatility-based kernel rootkit detection (SSDT, callbacks, DKOM)")
        print("    - UEFI firmware module inspection via chipsec subprocess")