#!/usr/bin/env python3
import hashlib
import json
import os
from pathlib import Path
import socket
import struct
import sys
import uuid

# Published example: replace the node-a host guard only after verifying your target.
ORIGINAL_SHA256 = '262741f55220b1a69d2ae1a2f72ffe1b6a70f6c11b29e4968b52369216e5fe6e'


def require(condition, message):
    if not condition:
        raise RuntimeError(message)


def entry_info(data, modern):
    if modern:
        require(len(data) >= 24 and data[:5] == b'_SM3_' and data[6] == 24,
                'invalid SMBIOS3 entry')
        require(sum(data[:24]) % 256 == 0, 'SMBIOS3 checksum failed')
        size, address = struct.unpack_from('<IQ', data, 12)
        version = tuple(data[7:9])
    else:
        require(len(data) >= 31 and data[:4] == b'_SM_' and data[5] == 31,
                'invalid SMBIOS entry')
        require(sum(data[:31]) % 256 == 0, 'SMBIOS checksum failed')
        require(data[16:21] == b'_DMI_' and sum(data[16:31]) % 256 == 0,
                'DMI intermediate checksum failed')
        size, address = struct.unpack_from('<HI', data, 22)
        version = tuple(data[6:8])
    require(address > 0 and 0 < size <= 0x9000, 'table exceeds this probe limit')
    return address, size, version


def inspect_table(data):
    position = count = 0
    system_uuid = None
    seen = set()
    while position < len(data):
        require(position + 4 <= len(data), 'truncated structure header')
        kind, length, handle = struct.unpack_from('<BBH', data, position)
        require(length >= 4 and position + length <= len(data), 'invalid structure length')
        end = data.find(b'\0\0', position + length)
        require(end >= 0, 'unterminated structure strings')
        seen.add(kind)
        if kind == 1:
            require(length >= 24 and system_uuid is None, 'invalid or duplicate Type 1')
            system_uuid = str(uuid.UUID(bytes_le=data[position + 8:position + 24]))
        count += 1
        position = end + 2
    require({0, 1, 127} <= seen and system_uuid is not None, 'required structures missing')
    return system_uuid, count


def prepare(source, destination):
    require(socket.gethostname() == 'node-a', 'wrong host')
    require(os.uname().release == '6.8.0-100-generic', 'unexpected kernel')
    original = source.read_bytes()
    require(hashlib.sha256(original).hexdigest() == ORIGINAL_SHA256, 'unknown original binary')
    pointers = {}
    for line in Path('/sys/firmware/efi/systab').read_text().splitlines():
        key, value = line.split('=', 1)
        if key in ('SMBIOS', 'SMBIOS3'):
            pointers[key] = int(value, 16)
    require(set(pointers) == {'SMBIOS', 'SMBIOS3'}, 'both firmware entries are required')
    fd = os.open('/dev/mem', os.O_RDONLY)
    try:
        legacy = os.pread(fd, 31, pointers['SMBIOS'])
        modern = os.pread(fd, 24, pointers['SMBIOS3'])
        address, size, version = entry_info(legacy, False)
        address3, maximum3, version3 = entry_info(modern, True)
        require(address == address3 and size <= maximum3 and version == version3 == (3, 6),
                'UEFI entries do not describe the same SMBIOS 3.6 table')
        table = os.pread(fd, size, address)
    finally:
        os.close(fd)
    require(len(table) == size and table == Path('/sys/firmware/dmi/tables/DMI').read_bytes(),
            'physical table differs from kernel table')
    system_uuid, count = inspect_table(table)
    require(count == struct.unpack_from('<H', legacy, 28)[0], 'structure count differs')
    require(system_uuid == Path('/sys/class/dmi/id/product_uuid').read_text().strip().lower(),
            'physical UUID differs from sysfs')
    entry_address = pointers['SMBIOS']
    # shortcut: this probe requires the existing page-aligned 32-bit entry; revisit for SMBIOS3-only firmware.
    require(entry_address % 4096 == 0 and entry_address + 31 < 2**32 and address + size < 2**32,
            'entry/table cannot be addressed by this legacy binary')
    for raw, modern_flag, checksum_index in ((legacy, False, 4), (modern, True, 5)):
        damaged = bytearray(raw)
        damaged[checksum_index] ^= 1
        try:
            entry_info(damaged, modern_flag)
        except RuntimeError:
            pass
        else:
            raise RuntimeError('checksum rejection self-check failed')
    patched = bytearray(original)
    changes = []

    def replace(offset, expected, replacement, reason):
        require(len(expected) == len(replacement) and original[offset:offset + len(expected)] == expected,
                'unexpected binary bytes: ' + reason)
        patched[offset:offset + len(expected)] = replacement
        changes.append(dict(offset=hex(offset), before=expected.hex(), after=replacement.hex(), reason=reason))

    require(struct.unpack_from('<IIQQQQQQ', original, 64) ==
            (1, 5, 0, 0x400000, 0x400000, 0xE6496, 0xE6496, 0x200000), 'unexpected ELF load segment')
    thunk = 0x4E64A0
    code = b'\xbe' + struct.pack('<I', 31) + b'\xbf' + struct.pack('<I', entry_address)
    code += b'\xe9' + struct.pack('<i', 0x406E48 - (thunk + 15))
    replace(thunk - 0x400000, bytes(15), code, 'map the real UEFI SMBIOS entry')
    for offset in (96, 104):
        replace(offset, struct.pack('<Q', 0xE6496), struct.pack('<Q', 0xE64AF), 'include thunk in RX segment')
    replace(0xBC7B, bytes.fromhex('e8ba470100'), b'\xe8' + struct.pack('<i', thunk - 0x40BC80),
            'redirect only GetDMI entry discovery; preserve other SearchPort callers')
    replace(0xB89D, bytes.fromhex('741d'), bytes.fromhex('74cb'),
            'after a valid table load, finish read-only initialization without ROM/SMI editing setup')
    replace(0xAE04, bytes.fromhex('4883ec'), bytes.fromhex('31c0c3'),
            'omit Flash policy hardware probing from this table-only reader')
    replace(0x203F9, bytes.fromhex('555389'), bytes.fromhex('31c0c3'),
            'use the normal private-buffer fallback instead of the legacy SMI memory-hole query')
    replace(0xB1B4, bytes.fromhex('555389'), bytes.fromhex('31c0c3'),
            'disable the duplicate SMI memory-hole query in the allocation fallback')
    for offset in (0x6E6D, 0x20268):
        replace(offset, bytes.fromhex('ba03000000'), bytes.fromhex('ba01000000'),
                'make physical firmware mappings read-only')
    replace(0x218AB, bytes.fromhex('5348'), bytes.fromhex('0f0b'), 'trap SMBIOS field writes in this probe')
    require(len(patched) == len(original), 'binary length changed')
    destination.mkdir(mode=0o700)
    output = destination / 'amidelnx-uefi-uuid-readonly'
    output.write_bytes(patched)
    output.chmod(0o500)
    manifest = dict(boot_id=Path('/proc/sys/kernel/random/boot_id').read_text().strip(),
                    uuid=system_uuid, structure_count=count, table_address=hex(address), table_size=size,
                    smbios_entry=hex(entry_address), smbios3_entry=hex(pointers['SMBIOS3']),
                    legacy_entry_hex=legacy.hex(), modern_entry_hex=modern.hex(),
                    original_sha256=ORIGINAL_SHA256, patched_sha256=hashlib.sha256(patched).hexdigest(),
                    changes=changes)
    manifest_path = destination / 'manifest.json'
    manifest_path.write_text(json.dumps(manifest, indent=2) + '\n')
    manifest_path.chmod(0o600)
    print(json.dumps(manifest, indent=2))


if __name__ == '__main__':
    require(len(sys.argv) == 3, 'usage: prepare_uuid_probe.py ORIGINAL NEW_DIRECTORY')
    prepare(Path(sys.argv[1]), Path(sys.argv[2]))
