#!/usr/bin/python3 -I
"""Validated USB-only FIDO2 operations; check-mount is read-only/unprivileged."""

import json
import os
from pathlib import Path
import re
import stat
import subprocess
import sys
import uuid

CRYPTSETUP = "@CRYPTSETUP@"
BLKID = "@BLKID@"
PCI_DEVICES = Path("/sys/bus/pci/devices")
SYSTEM_MOUNTS = ("/boot", "/efi", "/usr", "/var", "/home", "/opt", "/srv")
USB4_HOST = "0x0c0340"


class UnsupportedDevice(ValueError):
    pass


def block_node(device):
    path = Path(device).resolve(strict=True)
    if not path.is_relative_to("/dev"):
        raise UnsupportedDevice("Expected a block device under /dev.")
    info = path.stat()
    if not stat.S_ISBLK(info.st_mode):
        raise UnsupportedDevice("Not a block device.")
    node = Path(f"/sys/dev/block/{os.major(info.st_rdev)}:{os.minor(info.st_rdev)}").resolve(strict=True)
    return path, node


def sysfs_node(device):
    # polkitd has PrivateDevices=yes: validate kernel sysfs, not its private /dev.
    path = Path(device)
    if path.parent == Path("/dev/mapper"):
        matches = [node for node in Path("/sys/class/block").glob("dm-*")
                   if (node / "dm/name").read_text().strip() == path.name]
        if len(matches) != 1:
            raise UnsupportedDevice("Mapper does not exist or is ambiguous.")
        return matches[0].resolve(strict=True)
    if path.parent != Path("/dev") or not re.fullmatch(r"[a-zA-Z0-9_.!-]+", path.name):
        raise UnsupportedDevice("Expected a kernel device path or /dev/mapper name.")
    return (Path("/sys/class/block") / path.name).resolve(strict=True)


def physical_disks(node):
    slaves = list((node / "slaves").glob("*"))
    if slaves:
        disks = set()
        for slave in slaves:
            disks.update(physical_disks(slave.resolve(strict=True)))
        return disks
    return {node.parent if (node / "partition").exists() else node}


def protected_disks():
    disks = set()
    system_btrfs = False
    for line in Path("/proc/self/mountinfo").read_text().splitlines():
        fields = line.split()
        mountpoint = fields[4]
        if mountpoint != "/" and not any(mountpoint == root or mountpoint.startswith(root + "/") for root in SYSTEM_MOUNTS):
            continue
        separator = fields.index("-")
        system_btrfs |= fields[separator + 1] == "btrfs"
        node = Path(f"/sys/dev/block/{fields[2]}")
        if node.exists():
            disks.update(physical_disks(node.resolve(strict=True)))
        # Btrfs mountinfo may use an anonymous major:minor; resolve its source too.
        source = fields[separator + 2]
        if source.startswith("/dev/"):
            try:
                source_node = sysfs_node(source)
            except (OSError, UnsupportedDevice):
                if not node.exists() and fields[separator + 1] != "btrfs":
                    raise UnsupportedDevice("Cannot establish a system mount's backing disk.")
            else:
                disks.update(physical_disks(source_node))
    if system_btrfs:
        # Fail closed for multi-device Btrfs: include every mounted Btrfs member.
        for member in Path("/sys/fs/btrfs").glob("*/devices/*/dev"):
            node = Path("/sys/dev/block") / member.read_text().strip()
            disks.update(physical_disks(node.resolve(strict=True)))
    return disks


def external_bus(node):
    for parent in (node, *node.parents):
        subsystem = parent / "subsystem"
        try:
            if subsystem.exists() and subsystem.resolve().name in {"usb", "thunderbolt"}:
                return True
        except OSError:
            pass
        # Thunderbolt NVMe has no thunderbolt subsystem; the USB4 tunnel root port does.
        for link in parent.glob("supplier:pci:*"):
            pci = PCI_DEVICES / link.name.removeprefix("supplier:pci:")
            try:
                if (pci / "class").read_text().strip().lower() == USB4_HOST:
                    return True
            except OSError:
                continue
    return False


def usb_disk(node):
    if list((node / "slaves").glob("*")):
        raise UnsupportedDevice("Stacked backing devices are not supported.")
    if not external_bus(node):
        raise UnsupportedDevice("Device is not USB- or Thunderbolt-backed.")
    disk = node.parent if (node / "partition").exists() else node
    if disk in protected_disks():
        raise UnsupportedDevice("Refusing a disk backing a mounted system filesystem.")
    return disk


def checked_mapper(device):
    node = sysfs_node(device)
    identity = (node / "dm/uuid").read_text().strip()
    match = re.fullmatch(r"CRYPT-LUKS2-([0-9a-fA-F]{32})-(.+)", identity)
    if not match:
        raise UnsupportedDevice("Not a LUKS2 mapper.")
    volume_uuid = str(uuid.UUID(match[1]))
    name = (node / "dm/name").read_text().strip()
    if name != f"luks-{volume_uuid}" or match[2] != name:
        raise UnsupportedDevice("Mapper name must be luks-<LUKS UUID>.")
    slaves = list((node / "slaves").glob("*"))
    if len(slaves) != 1:
        raise UnsupportedDevice("Expected exactly one USB backing device.")
    backing = slaves[0].resolve(strict=True)
    usb_disk(backing)
    return {"device": f"/dev/{node.name}", "name": name, "uuid": volume_uuid, "backing": str(backing)}


def probe_usb(device):
    path, node = block_node(device)
    usb_disk(node)
    result = subprocess.run(
        [BLKID, "-p", "-o", "export", str(path)],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False,
    )
    fields = dict(line.split("=", 1) for line in result.stdout.decode().splitlines() if "=" in line)
    if result.returncode or fields.get("TYPE") != "crypto_LUKS" or fields.get("VERSION") != "2":
        raise UnsupportedDevice("Expected a USB- or Thunderbolt-backed LUKS2 volume.")
    volume_uuid = str(uuid.UUID(fields["UUID"]))
    metadata = subprocess.run(
        [CRYPTSETUP, "luksDump", "--dump-json-metadata", str(path)],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True,
    )
    tokens = json.loads(metadata.stdout).get("tokens", {}).values()
    if not any(token.get("type") == "systemd-fido2" and token.get("keyslots") for token in tokens):
        raise UnsupportedDevice("No enrolled systemd FIDO2 token.")
    mapper = f"/dev/mapper/luks-{volume_uuid}"
    unlocked = Path(mapper).exists()
    if unlocked and checked_mapper(mapper)["backing"] != str(node):
        raise UnsupportedDevice("Mapper name is already used by another device.")
    return {"device": str(path), "uuid": volume_uuid, "mapper": mapper, "unlocked": unlocked}


def main(arguments):
    if len(arguments) != 2 or arguments[0] not in ("probe", "open", "close", "check-mount"):
        print("Usage: yubikey-usb-root {probe|open|close|check-mount} DEVICE", file=sys.stderr)
        return 2
    operation, device = arguments
    try:
        if operation == "check-mount":
            checked_mapper(device)
            return 0
        if os.geteuid() != 0:
            raise ValueError("Use yubikey-usb, which invokes pkexec.")
        if operation == "close":
            name = checked_mapper(device)["name"]
            # Native cryptsetup refuses busy/mounted mappings; no force/deferred options.
            os.execv(CRYPTSETUP, [CRYPTSETUP, "close", name])
            return 0
        info = probe_usb(device)
        if operation == "probe":
            print(json.dumps(info))
            return 0
        if info["unlocked"]:
            return 0
        command = [
            CRYPTSETUP, "open", "--token-only", "--token-type", "systemd-fido2",
            "--tries", "1", info["device"], f"luks-{info['uuid']}",
        ]
        os.execv(CRYPTSETUP, command)
        return 0
    except UnsupportedDevice as error:
        if operation != "check-mount":
            print(f"Unsupported device: {error}", file=sys.stderr)
        return 3
    except (OSError, ValueError, KeyError, subprocess.SubprocessError) as error:
        print(f"YubiKey USB validation failed: {error}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
