File size: 27,995 Bytes
fad5c43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
"""Linux kernel sandbox launcher for untrusted Harbor candidates.

The launcher is executed by the privileged verifier, installs an irreversible
Landlock/seccomp policy, drops to the opaque worker UID, and only then execs the
candidate entrypoint.  It deliberately has no dependency outside the standard
library so the formal verifier image has a small, inspectable trusted surface.
"""

from __future__ import annotations

import argparse
import array
import ctypes
import errno
import fcntl
import os
import platform
import resource
import signal
import socket
import stat
import struct
import threading
import time
from pathlib import Path
from typing import Sequence


PR_SET_NO_NEW_PRIVS = 38
PR_SET_DUMPABLE = 4
PR_SET_SECCOMP = 22
SECCOMP_MODE_FILTER = 2
SECCOMP_RET_KILL_PROCESS = 0x80000000
SECCOMP_RET_ERRNO = 0x00050000
SECCOMP_RET_USER_NOTIF = 0x7FC00000
SECCOMP_RET_ALLOW = 0x7FFF0000
SECCOMP_FILTER_FLAG_NEW_LISTENER = 1 << 3
SECCOMP_SET_MODE_FILTER = 1
SECCOMP_GET_ACTION_AVAIL = 2

BPF_LD_W_ABS = 0x20
BPF_JMP_JEQ_K = 0x15
BPF_JMP_JSET_K = 0x45
BPF_ALU_AND_K = 0x54
BPF_RET_K = 0x06

LANDLOCK_CREATE_RULESET_VERSION = 1
LANDLOCK_RULE_PATH_BENEATH = 1
LANDLOCK_RULE_NET_PORT = 2
LANDLOCK_ACCESS_FS_EXECUTE = 1 << 0
LANDLOCK_ACCESS_FS_WRITE_FILE = 1 << 1
LANDLOCK_ACCESS_FS_READ_FILE = 1 << 2
LANDLOCK_ACCESS_FS_READ_DIR = 1 << 3
LANDLOCK_ACCESS_FS_REMOVE_DIR = 1 << 4
LANDLOCK_ACCESS_FS_REMOVE_FILE = 1 << 5
LANDLOCK_ACCESS_FS_MAKE_CHAR = 1 << 6
LANDLOCK_ACCESS_FS_MAKE_DIR = 1 << 7
LANDLOCK_ACCESS_FS_MAKE_REG = 1 << 8
LANDLOCK_ACCESS_FS_MAKE_SOCK = 1 << 9
LANDLOCK_ACCESS_FS_MAKE_FIFO = 1 << 10
LANDLOCK_ACCESS_FS_MAKE_BLOCK = 1 << 11
LANDLOCK_ACCESS_FS_MAKE_SYM = 1 << 12
LANDLOCK_ACCESS_FS_REFER = 1 << 13
LANDLOCK_ACCESS_FS_TRUNCATE = 1 << 14
LANDLOCK_ACCESS_FS_IOCTL_DEV = 1 << 15
LANDLOCK_ACCESS_NET_BIND_TCP = 1 << 0
LANDLOCK_ACCESS_NET_CONNECT_TCP = 1 << 1

_FS_ABI_1 = (1 << 13) - 1
_FS_ABI_2 = _FS_ABI_1 | LANDLOCK_ACCESS_FS_REFER
_FS_ABI_3 = _FS_ABI_2 | LANDLOCK_ACCESS_FS_TRUNCATE
_FS_ABI_5 = _FS_ABI_3 | LANDLOCK_ACCESS_FS_IOCTL_DEV
_FS_READ_EXECUTE = (
    LANDLOCK_ACCESS_FS_EXECUTE
    | LANDLOCK_ACCESS_FS_READ_FILE
    | LANDLOCK_ACCESS_FS_READ_DIR
)


class _RulesetAttr(ctypes.Structure):
    _fields_ = [
        ("handled_access_fs", ctypes.c_uint64),
        ("handled_access_net", ctypes.c_uint64),
    ]


class _PathBeneathAttr(ctypes.Structure):
    _fields_ = [
        ("allowed_access", ctypes.c_uint64),
        ("parent_fd", ctypes.c_int32),
        ("reserved", ctypes.c_uint32),
    ]


class _NetPortAttr(ctypes.Structure):
    _fields_ = [("allowed_access", ctypes.c_uint64), ("port", ctypes.c_uint64)]


class _SockFilter(ctypes.Structure):
    _fields_ = [
        ("code", ctypes.c_ushort),
        ("jt", ctypes.c_ubyte),
        ("jf", ctypes.c_ubyte),
        ("k", ctypes.c_uint32),
    ]


class _SockFprog(ctypes.Structure):
    _fields_ = [("len", ctypes.c_ushort), ("filter", ctypes.POINTER(_SockFilter))]


_SECCOMP_NOTIF_FORMAT = "=QIIiIQQQQQQQ"
_SECCOMP_RESP_FORMAT = "=QqiI"
_SECCOMP_NOTIF_SIZE = struct.calcsize(_SECCOMP_NOTIF_FORMAT)
_SECCOMP_RESP_SIZE = struct.calcsize(_SECCOMP_RESP_FORMAT)


def _iowr(kind: int, number: int, size: int) -> int:
    return (3 << 30) | (size << 16) | (kind << 8) | number


_SECCOMP_IOCTL_NOTIF_RECV = _iowr(ord("!"), 0, _SECCOMP_NOTIF_SIZE)
_SECCOMP_IOCTL_NOTIF_SEND = _iowr(ord("!"), 1, _SECCOMP_RESP_SIZE)


def _architecture() -> tuple[int, int, int, int, tuple[int, ...]]:
    machine = platform.machine().lower()
    if machine in {"x86_64", "amd64"}:
        # AUDIT_ARCH_X86_64, socket(2), and shared cross-process facilities.
        return (
            0xC000003E,
            41,
            72,
            317,
            (
                29,
                30,
                31,
                57,
                58,
                64,
                65,
                66,
                67,
                68,
                69,
                70,
                71,
                109,
                112,
                240,
                241,
                242,
                243,
                244,
                245,
                248,
                249,
                250,
                253,
                254,
                255,
                294,
                298,
                300,
                301,
                425,
                73,
            ),
        )
    if machine in {"aarch64", "arm64"}:
        return (
            0xC00000B7,
            198,
            25,
            277,
            tuple(range(180, 198))
            + (26, 27, 28, 32, 154, 157, 217, 218, 219, 241, 262, 263, 425),
        )
    raise OSError(errno.ENOTSUP, f"unsupported verifier architecture: {machine}")


def _syscalls() -> tuple[int, int, int]:
    machine = platform.machine().lower()
    if machine in {"x86_64", "amd64", "aarch64", "arm64"}:
        return 444, 445, 446
    raise OSError(errno.ENOTSUP, f"unsupported verifier architecture: {machine}")


def sandbox_runtime_fingerprint() -> dict[str, object]:
    """Return trusted kernel capabilities required by the candidate sandbox."""

    audit_arch, socket_syscall, _fcntl_syscall, seccomp_syscall, _denied = (
        _architecture()
    )
    create_ruleset, _add_rule, _restrict_self = _syscalls()
    libc = ctypes.CDLL(None, use_errno=True)
    abi = int(libc.syscall(create_ruleset, 0, 0, LANDLOCK_CREATE_RULESET_VERSION))
    action = ctypes.c_uint32(SECCOMP_RET_USER_NOTIF)
    user_notification = (
        libc.syscall(
            seccomp_syscall,
            SECCOMP_GET_ACTION_AVAIL,
            0,
            ctypes.byref(action),
        )
        == 0
    )
    x32_unavailable = True
    if audit_arch == 0xC000003E:
        ctypes.set_errno(0)
        result = libc.syscall(0x40000000 | socket_syscall, -1, -1, -1)
        x32_unavailable = result == -1 and ctypes.get_errno() == errno.ENOSYS
    return {
        "schema": "websitebench.harbor.sandbox-runtime",
        "architecture": platform.machine().lower(),
        "landlock_abi": abi,
        "seccomp_user_notification": user_notification,
        "x32_unavailable": x32_unavailable,
    }


def sandbox_preflight() -> dict[str, object]:
    """Fail closed before scoring when the verifier kernel cannot sandbox."""

    fingerprint = sandbox_runtime_fingerprint()
    if (
        int(fingerprint["landlock_abi"]) < 4
        or fingerprint["seccomp_user_notification"] is not True
        or fingerprint["x32_unavailable"] is not True
    ):
        raise OSError(errno.ENOTSUP, f"candidate sandbox unavailable: {fingerprint}")
    child = os.fork()
    if child == 0:
        try:
            _landlock(Path("/"), Path("/tmp"), 65534, {65534})
            listener = _seccomp()
            os.close(listener)
            os._exit(0)
        except BaseException:
            os._exit(1)
    _waited, status = os.waitpid(child, 0)
    if not os.WIFEXITED(status) or os.WEXITSTATUS(status) != 0:
        raise OSError(errno.ENOTSUP, "candidate sandbox enforcement probe failed")
    fingerprint["enforcement_probe_passed"] = True
    return fingerprint


def _landlock(
    root: Path,
    data: Path,
    bind_port: int,
    connect_ports: set[int],
    read_paths: Sequence[Path] = (),
) -> None:
    libc = ctypes.CDLL(None, use_errno=True)
    create_ruleset, add_rule, restrict_self = _syscalls()
    abi = int(libc.syscall(create_ruleset, 0, 0, LANDLOCK_CREATE_RULESET_VERSION))
    if abi < 4:
        code = ctypes.get_errno() if abi < 0 else errno.ENOTSUP
        raise OSError(code, "Landlock ABI 4 or newer is required")

    handled_fs = _FS_ABI_1
    if abi >= 2:
        handled_fs = _FS_ABI_2
    if abi >= 3:
        handled_fs = _FS_ABI_3
    if abi >= 5:
        handled_fs = _FS_ABI_5
    handled_net = LANDLOCK_ACCESS_NET_BIND_TCP | LANDLOCK_ACCESS_NET_CONNECT_TCP
    attributes = _RulesetAttr(handled_fs, handled_net)
    ruleset_fd = int(
        libc.syscall(
            create_ruleset,
            ctypes.byref(attributes),
            ctypes.sizeof(attributes),
            0,
        )
    )
    if ruleset_fd < 0:
        raise OSError(ctypes.get_errno(), "cannot create Landlock ruleset")

    def add_path(path: Path, access: int) -> None:
        if not path.exists():
            return
        descriptor = os.open(path, os.O_PATH | os.O_CLOEXEC)
        try:
            rule = _PathBeneathAttr(access & handled_fs, descriptor, 0)
            if (
                libc.syscall(
                    add_rule,
                    ruleset_fd,
                    LANDLOCK_RULE_PATH_BENEATH,
                    ctypes.byref(rule),
                    0,
                )
                != 0
            ):
                raise OSError(ctypes.get_errno(), f"cannot allow sandbox path: {path}")
        finally:
            os.close(descriptor)

    try:
        for path in (
            root,
            Path("/usr"),
            Path("/bin"),
            Path("/lib"),
            Path("/lib64"),
            Path("/etc"),
            *read_paths,
        ):
            add_path(path, _FS_READ_EXECUTE)
        for path in (
            Path("/dev/null"),
            Path("/dev/zero"),
            Path("/dev/random"),
            Path("/dev/urandom"),
            Path("/dev/full"),
            Path("/dev/tty"),
        ):
            add_path(path, LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_WRITE_FILE)
        add_path(data, handled_fs)

        for access, port in (
            (LANDLOCK_ACCESS_NET_BIND_TCP, bind_port),
            *(
                (LANDLOCK_ACCESS_NET_CONNECT_TCP, port)
                for port in sorted(connect_ports)
            ),
        ):
            rule = _NetPortAttr(access, port)
            if (
                libc.syscall(
                    add_rule,
                    ruleset_fd,
                    LANDLOCK_RULE_NET_PORT,
                    ctypes.byref(rule),
                    0,
                )
                != 0
            ):
                raise OSError(ctypes.get_errno(), "cannot add Landlock TCP rule")

        if libc.prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0:
            raise OSError(ctypes.get_errno(), "cannot set no_new_privs")
        if libc.syscall(restrict_self, ruleset_fd, 0) != 0:
            raise OSError(ctypes.get_errno(), "cannot enforce Landlock ruleset")
    finally:
        os.close(ruleset_fd)


def _seccomp() -> int:
    """Install the filter and return its user-notification listener."""

    audit_arch, socket_syscall, fcntl_syscall, seccomp_syscall, denied = _architecture()
    instructions: list[tuple[int, int, int, int]] = [
        (BPF_LD_W_ABS, 0, 0, 4),
        (BPF_JMP_JEQ_K, 1, 0, audit_arch),
        (BPF_RET_K, 0, 0, SECCOMP_RET_KILL_PROCESS),
        (BPF_LD_W_ABS, 0, 0, 0),
    ]
    if audit_arch == 0xC000003E:
        instructions.extend(
            [
                (BPF_JMP_JSET_K, 0, 1, 0x40000000),
                (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
            ]
        )
    # Force clone3 callers onto the inspectable clone/fork fallback, then deny
    # only process-style clone(SIGCHLD). Thread creation has a zero exit-signal
    # byte and remains available to ASGI runtimes.
    clone_syscall = 56 if audit_arch == 0xC000003E else 220
    instructions.extend(
        [
            (BPF_JMP_JEQ_K, 0, 1, 435),
            (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.ENOSYS),
            (BPF_LD_W_ABS, 0, 0, 0),
            (BPF_JMP_JEQ_K, 0, 4, clone_syscall),
            (BPF_LD_W_ABS, 0, 0, 16),
            (BPF_ALU_AND_K, 0, 0, 0xFF),
            (BPF_JMP_JEQ_K, 0, 1, signal.SIGCHLD),
            (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
            (BPF_LD_W_ABS, 0, 0, 0),
        ]
    )
    for number in denied:
        instructions.extend(
            [
                (BPF_JMP_JEQ_K, 0, 1, number),
                (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
            ]
        )
    # Classic and OFD byte-range locks are executed by the trusted broker.
    # The tracee is never continued after a pathname/fd check: another tracee
    # thread could otherwise replace the descriptor between check and use.
    brokered_fcntl_commands = (5, 6, 7, 36, 37, 38)
    instructions.extend(
        [
            (
                BPF_JMP_JEQ_K,
                0,
                2 * len(brokered_fcntl_commands) + 2,
                fcntl_syscall,
            ),
            (BPF_LD_W_ABS, 0, 0, 24),
        ]
    )
    for command in brokered_fcntl_commands:
        instructions.extend(
            [
                (BPF_JMP_JEQ_K, 0, 1, command),
                (BPF_RET_K, 0, 0, SECCOMP_RET_USER_NOTIF),
            ]
        )
    instructions.append((BPF_LD_W_ABS, 0, 0, 0))
    # socket(domain, type, protocol): permit only IPv4/IPv6 SOCK_STREAM.
    instructions.extend(
        [
            (BPF_JMP_JEQ_K, 0, 8, socket_syscall),
            (BPF_LD_W_ABS, 0, 0, 16),
            (BPF_JMP_JEQ_K, 2, 0, 2),
            (BPF_JMP_JEQ_K, 1, 0, 10),
            (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
            (BPF_LD_W_ABS, 0, 0, 24),
            (BPF_ALU_AND_K, 0, 0, 0xF),
            (BPF_JMP_JEQ_K, 1, 0, 1),
            (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
            (BPF_RET_K, 0, 0, SECCOMP_RET_ALLOW),
        ]
    )
    filters = (_SockFilter * len(instructions))(
        *(_SockFilter(*instruction) for instruction in instructions)
    )
    program = _SockFprog(len(instructions), filters)
    libc = ctypes.CDLL(None, use_errno=True)
    listener = int(
        libc.syscall(
            seccomp_syscall,
            SECCOMP_SET_MODE_FILTER,
            SECCOMP_FILTER_FLAG_NEW_LISTENER,
            ctypes.byref(program),
        )
    )
    if listener < 0:
        raise OSError(ctypes.get_errno(), "cannot install candidate seccomp filter")
    return listener


def _send_fd(channel: socket.socket, descriptor: int) -> None:
    descriptors = array.array("i", [descriptor])
    channel.sendmsg(
        [b"L"],
        [(socket.SOL_SOCKET, socket.SCM_RIGHTS, descriptors.tobytes())],
    )


def _receive_fd(channel: socket.socket) -> int:
    descriptors = array.array("i")
    message, ancillary, _flags, _address = channel.recvmsg(
        1, socket.CMSG_SPACE(descriptors.itemsize)
    )
    if message != b"L":
        raise OSError(errno.EIO, "candidate sandbox listener was not delivered")
    for level, kind, payload in ancillary:
        if level == socket.SOL_SOCKET and kind == socket.SCM_RIGHTS:
            descriptors.frombytes(payload[: descriptors.itemsize])
            return int(descriptors[0])
    raise OSError(errno.EIO, "candidate sandbox listener fd is missing")


def _tracee_process_id(thread_id: int) -> int:
    try:
        for line in Path(f"/proc/{thread_id}/status").read_text().splitlines():
            if line.startswith("Tgid:"):
                return int(line.partition(":")[2].strip())
    except (OSError, ValueError):
        pass
    raise OSError(errno.ESRCH, "cannot identify candidate process")


def _capture_worker_file(pid: int, descriptor: int, data: Path) -> int:
    """Atomically capture a regular data-dir inode from a tracee descriptor."""

    captured = os.open(f"/proc/{pid}/fd/{descriptor}", os.O_RDWR | os.O_CLOEXEC)
    try:
        metadata = os.fstat(captured)
        if not stat.S_ISREG(metadata.st_mode):
            raise OSError(errno.EPERM, "candidate locks require a regular file")
        target_text = os.readlink(f"/proc/self/fd/{captured}")
        if target_text.endswith(" (deleted)"):
            target_text = target_text[: -len(" (deleted)")]
        target = Path(target_text).resolve()
        if target != data and data not in target.parents:
            raise OSError(errno.EPERM, "candidate lock target is outside data dir")
        return captured
    except BaseException:
        os.close(captured)
        raise


def _read_tracee(pid: int, address: int, size: int) -> bytes:
    descriptor = os.open(f"/proc/{pid}/mem", os.O_RDONLY | os.O_CLOEXEC)
    try:
        value = os.pread(descriptor, size, address)
    finally:
        os.close(descriptor)
    if len(value) != size:
        raise OSError(errno.EFAULT, "candidate fcntl argument is unreadable")
    return value


def _write_tracee(pid: int, address: int, value: bytes) -> None:
    descriptor = os.open(f"/proc/{pid}/mem", os.O_WRONLY | os.O_CLOEXEC)
    try:
        written = os.pwrite(descriptor, value, address)
    finally:
        os.close(descriptor)
    if written != len(value):
        raise OSError(errno.EFAULT, "candidate fcntl result is unwritable")


def _prune_closed_lock_files(
    process_id: int,
    locked_files: dict[tuple[int, int, int], int],
) -> None:
    """Release broker descriptors once the tracee has closed their inode.

    SQLite creates and removes WAL/SHM files as short-lived connections come
    and go.  Keeping one broker descriptor for every historical inode pins both
    deleted files and file descriptors until process exit, eventually turning
    ordinary repeated requests into ``SQLITE_IOERR`` under ``RLIMIT_NOFILE``.
    An OFD lock is no longer useful after the tracee has closed every descriptor
    for that inode, so prune it before brokering the next lock operation.
    """

    open_inodes: set[tuple[int, int]] = set()
    try:
        entries = list(Path(f"/proc/{process_id}/fd").iterdir())
    except OSError:
        return
    for entry in entries:
        try:
            metadata = entry.stat()
        except OSError:
            continue
        open_inodes.add((metadata.st_dev, metadata.st_ino))
    for key, descriptor in list(locked_files.items()):
        owner, device, inode = key
        if owner == process_id and (device, inode) not in open_inodes:
            os.close(descriptor)
            del locked_files[key]


def _broker_fcntl(
    pid: int,
    descriptor: int,
    command: int,
    argument: int,
    data: Path,
    locked_files: dict[tuple[int, int, int], int],
) -> int:
    """Execute a byte-range lock without continuing the untrusted syscall."""

    process_id = _tracee_process_id(pid)
    _prune_closed_lock_files(process_id, locked_files)
    captured = _capture_worker_file(pid, descriptor, data)
    metadata = os.fstat(captured)
    key = (process_id, metadata.st_dev, metadata.st_ino)
    broker_descriptor = locked_files.get(key)
    if broker_descriptor is None:
        locked_files[key] = captured
        broker_descriptor = captured
    else:
        os.close(captured)

    flock_value = bytearray(_read_tracee(pid, argument, 32))
    # Linux requires l_pid to be zero for OFD lock operations. Classic
    # F_SETLK callers do not own that output-only field, so normalize it when
    # translating the request.
    flock_value[24:28] = b"\0\0\0\0"
    translations = {
        5: 36,  # F_GETLK -> F_OFD_GETLK
        6: 37,  # F_SETLK -> F_OFD_SETLK
        7: 37,  # F_SETLKW stays fail-fast so the broker cannot deadlock.
        36: 36,
        37: 37,
        38: 37,
    }
    result = fcntl.fcntl(broker_descriptor, translations[command], bytes(flock_value))
    if command in {5, 36}:
        if not isinstance(result, bytes):
            raise OSError(errno.EIO, "candidate lock query returned no structure")
        _write_tracee(pid, argument, result.ljust(32, b"\0")[:32])
    return 0


def _lock_broker(listener: int, data: Path) -> None:
    locked_files: dict[tuple[int, int, int], int] = {}
    try:
        while True:
            request = bytearray(_SECCOMP_NOTIF_SIZE)
            try:
                fcntl.ioctl(listener, _SECCOMP_IOCTL_NOTIF_RECV, request, True)
            except OSError as exc:
                if exc.errno in {errno.EINTR, errno.ENOENT, errno.EBADF}:
                    if exc.errno == errno.EINTR:
                        continue
                    return
                raise
            unpacked = struct.unpack(_SECCOMP_NOTIF_FORMAT, request)
            identifier, pid = int(unpacked[0]), int(unpacked[1])
            try:
                value = _broker_fcntl(
                    pid,
                    int(unpacked[6]),
                    int(unpacked[7]),
                    int(unpacked[8]),
                    data,
                    locked_files,
                )
                error = 0
            except OSError as exc:
                value = 0
                error = -(exc.errno or errno.EPERM)
            response = bytearray(
                struct.pack(_SECCOMP_RESP_FORMAT, identifier, value, error, 0)
            )
            try:
                fcntl.ioctl(listener, _SECCOMP_IOCTL_NOTIF_SEND, response, True)
            except OSError as exc:
                if exc.errno != errno.ENOENT:
                    raise
    finally:
        for descriptor in locked_files.values():
            os.close(descriptor)


def _drop_credentials(uid: int | None, gid: int | None) -> None:
    """Irreversibly adopt the requested worker identity, when configured."""

    if uid is None or gid is None:
        return
    os.setgroups([])
    os.setgid(gid)
    os.setuid(uid)
    if os.geteuid() != uid or os.getegid() != gid or os.getgroups():
        raise OSError(errno.EPERM, "worker credential drop did not take effect")


def _kill_and_reap(child_pid: int) -> None:
    try:
        os.kill(child_pid, signal.SIGKILL)
    except ProcessLookupError:
        pass
    try:
        os.waitpid(child_pid, 0)
    except ChildProcessError:
        pass


def sandbox_exec(
    command: Sequence[str],
    *,
    root: Path,
    data: Path,
    bind_port: int,
    connect_ports: set[int],
    uid: int | None,
    gid: int | None,
    file_size_limit_bytes: int | None,
    read_paths: Sequence[Path] = (),
    broker_tid_fd: int | None = None,
    control_fd: int | None = None,
) -> None:
    root = root.resolve(strict=True)
    data = data.resolve(strict=True)
    parent_channel, child_channel = socket.socketpair()
    child_pid = os.fork()
    if child_pid == 0:
        parent_channel.close()
        if control_fd is not None:
            os.close(control_fd)
        if broker_tid_fd is not None:
            os.close(broker_tid_fd)
        stage = "landlock"
        try:
            _landlock(root, data, bind_port, connect_ports, read_paths)
            stage = "resource limits"
            if file_size_limit_bytes is not None:
                resource.setrlimit(
                    resource.RLIMIT_FSIZE,
                    (file_size_limit_bytes, file_size_limit_bytes),
                )
            if uid is not None and gid is not None:
                stage = "credential drop"
                _drop_credentials(uid, gid)
            stage = "lock broker access"
            libc = ctypes.CDLL(None, use_errno=True)
            if libc.prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) != 0:
                raise OSError(ctypes.get_errno(), "cannot enable lock broker access")
            stage = "seccomp"
            listener = _seccomp()
            stage = "listener handoff"
            _send_fd(child_channel, listener)
            os.close(listener)
            child_channel.close()
            stage = "candidate cwd"
            os.chdir(root)
            stage = "candidate exec"
            os.execv(command[0], list(command))
        except BaseException as exc:
            message = f"candidate sandbox setup failed during {stage}: {exc}\n".encode(
                "utf-8", "replace"
            )
            try:
                os.write(2, message)
            except OSError:
                pass
            os._exit(126)

    child_channel.close()
    try:
        listener = _receive_fd(parent_channel)
    except BaseException:
        _kill_and_reap(child_pid)
        raise
    finally:
        parent_channel.close()
    try:
        _drop_credentials(uid, gid)
    except BaseException:
        os.close(listener)
        _kill_and_reap(child_pid)
        raise
    broker_errors: list[BaseException] = []
    if control_fd is not None:
        os.set_blocking(control_fd, False)

    def broker() -> None:
        try:
            _lock_broker(listener, data)
        except BaseException as exc:
            broker_errors.append(exc)

    broker_thread = threading.Thread(target=broker, daemon=True)
    broker_thread.start()
    if broker_tid_fd is not None:
        try:
            native_id = broker_thread.native_id
            if native_id is None:
                raise OSError(errno.EIO, "lock broker thread has no native id")
            os.write(
                broker_tid_fd,
                f"{native_id} {child_pid}\n".encode("ascii"),
            )
        except BaseException:
            os.close(listener)
            _kill_and_reap(child_pid)
            broker_thread.join(timeout=1)
            if control_fd is not None:
                os.close(control_fd)
            raise
        finally:
            os.close(broker_tid_fd)
    status = 0
    while True:
        if control_fd is not None:
            try:
                requested = os.read(control_fd, 4096)
            except (BlockingIOError, OSError):
                requested = b""
            for marker in requested:
                requested_signal = {
                    ord("T"): signal.SIGTERM,
                    ord("K"): signal.SIGKILL,
                }.get(marker)
                if requested_signal is not None:
                    try:
                        os.kill(child_pid, requested_signal)
                    except ProcessLookupError:
                        pass
        waited, status = os.waitpid(child_pid, os.WNOHANG)
        if waited == child_pid:
            break
        if broker_errors:
            os.kill(child_pid, signal.SIGKILL)
            _waited, status = os.waitpid(child_pid, 0)
            break
        time.sleep(0.01)
    if control_fd is not None:
        os.close(control_fd)
    os.close(listener)
    broker_thread.join(timeout=1)
    if broker_errors:
        raise OSError(errno.EIO, "candidate lock broker failed") from broker_errors[0]
    # The trusted launcher/broker completed normally. Candidate business exit
    # status is observed through readiness/lifecycle, while a nonzero launcher
    # status remains reserved for audit infrastructure failure.
    os._exit(0)


def main(argv: Sequence[str] | None = None) -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--root", type=Path, required=True)
    parser.add_argument("--data", type=Path, required=True)
    parser.add_argument("--bind-port", type=int, required=True)
    parser.add_argument("--connect-port", type=int, action="append", default=[])
    parser.add_argument("--uid", type=int)
    parser.add_argument("--gid", type=int)
    parser.add_argument("--file-size-limit-bytes", type=int)
    parser.add_argument("--read-path", type=Path, action="append", default=[])
    parser.add_argument("--broker-tid-fd", type=int)
    parser.add_argument("--control-fd", type=int)
    parser.add_argument("command", nargs=argparse.REMAINDER)
    arguments = parser.parse_args(argv)
    command = arguments.command
    if command[:1] == ["--"]:
        command = command[1:]
    if not command:
        parser.error("candidate command is required")
    if (arguments.uid is None) != (arguments.gid is None):
        parser.error("uid and gid must be provided together")
    sandbox_exec(
        command,
        root=arguments.root,
        data=arguments.data,
        bind_port=arguments.bind_port,
        connect_ports=set(arguments.connect_port),
        uid=arguments.uid,
        gid=arguments.gid,
        file_size_limit_bytes=arguments.file_size_limit_bytes,
        read_paths=arguments.read_path,
        broker_tid_fd=arguments.broker_tid_fd,
        control_fd=arguments.control_fd,
    )
    return 127


if __name__ == "__main__":
    raise SystemExit(main())