#!/usr/bin/env python3 """Read persistent boot logs from the known USB through an authorized read-only fd.""" import argparse import fcntl import json import os from pathlib import Path import stat import struct import subprocess import sys import time from btrfs_read import Btrfs, u32, u64 from usb_device import snapshot_device, verify_device def main(): if sys.flags.optimize: raise RuntimeError('Python optimization is not allowed; safety assertions must remain enabled') parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--device', required=True) parser.add_argument('--device-fd', type=int, required=True) parser.add_argument('--output', type=Path, required=True) args = parser.parse_args() if os.geteuid() != 0: raise RuntimeError('Root is required to inspect the USB') fd = args.device_fd snapshot = snapshot_device(args.device, writable=False) device = snapshot['device'] if fcntl.fcntl(fd, fcntl.F_GETFL) & os.O_ACCMODE != os.O_RDONLY: raise ValueError('Device descriptor must be read-only') opened = os.fstat(fd) expected = os.stat(f'/dev/r{device}') if not stat.S_ISCHR(opened.st_mode) or opened.st_rdev != expected.st_rdev: raise ValueError('Passed descriptor is not the selected raw disk') snapshot = verify_device(snapshot, writable=False) device = snapshot['device'] subprocess.run(['diskutil', 'unmountDisk', f'/dev/{device}'], check=True) output = args.output if output.exists(): owner = output.stat() else: owner = output.parent.stat() output.mkdir(exist_ok=True) os.chown(output, owner.st_uid, owner.st_gid) report = {'time': time.strftime('%Y-%m-%dT%H:%M:%S%z'), 'device': device, 'read_only': True, 'files': {}} with os.fdopen(fd, 'rb', buffering=0) as disk: disk.seek(0) gpt = disk.read(4096) assert gpt[512:520] == b'EFI PART' root_start = struct.unpack_from('