tapid-runner 0.0.6

Policy-aware package execution foundations for Tapid
Documentation
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
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
use super::{
    AssuranceLevel, BackendIdentity, CleanupConfidence, CompletionEvidence, ContainmentSupport,
    DimensionEvidence, EnforcementDimensions, EnforcementReceipt, ExecutionBackend, ExecutionError,
    ExecutionErrorCategory, ExecutionLifecycle, ExecutionOutcome, ExecutionRequest,
    FilesystemAccess, FilesystemBindings, FilesystemGrantKind, OwnedExecutionAttempt,
    PreparationError, ResolvedSandboxPolicy, RuntimeFilesystemAdditions, Termination,
    ValidatedPreflight, evidence_for_dimensions,
};
use std::ffi::{OsStr, OsString};
use std::fs::{self, File, OpenOptions};
use std::io::{self, Read, Write};
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::os::unix::net::UnixStream;
use std::os::unix::process::{CommandExt, ExitStatusExt};
use std::path::Path;
use std::process::{Command, Stdio};

const LANDLOCK_CREATE_RULESET_VERSION: libc::c_uint = 1;
const LANDLOCK_RULE_PATH_BENEATH: libc::c_int = 1;
const LANDLOCK_EXECUTE: u64 = 1 << 0;
const LANDLOCK_WRITE_FILE: u64 = 1 << 1;
const LANDLOCK_READ_FILE: u64 = 1 << 2;
const LANDLOCK_READ_DIR: u64 = 1 << 3;
const LANDLOCK_REMOVE_DIR: u64 = 1 << 4;
const LANDLOCK_REMOVE_FILE: u64 = 1 << 5;
const LANDLOCK_MAKE_CHAR: u64 = 1 << 6;
const LANDLOCK_MAKE_DIR: u64 = 1 << 7;
const LANDLOCK_MAKE_REG: u64 = 1 << 8;
const LANDLOCK_MAKE_SOCK: u64 = 1 << 9;
const LANDLOCK_MAKE_FIFO: u64 = 1 << 10;
const LANDLOCK_MAKE_BLOCK: u64 = 1 << 11;
const LANDLOCK_MAKE_SYM: u64 = 1 << 12;
const LANDLOCK_REFER: u64 = 1 << 13;
const LANDLOCK_TRUNCATE: u64 = 1 << 14;
const LANDLOCK_READ: u64 = LANDLOCK_EXECUTE | LANDLOCK_READ_FILE | LANDLOCK_READ_DIR;
const LANDLOCK_WRITE: u64 = LANDLOCK_WRITE_FILE
    | LANDLOCK_REMOVE_DIR
    | LANDLOCK_REMOVE_FILE
    | LANDLOCK_MAKE_CHAR
    | LANDLOCK_MAKE_DIR
    | LANDLOCK_MAKE_REG
    | LANDLOCK_MAKE_SOCK
    | LANDLOCK_MAKE_FIFO
    | LANDLOCK_MAKE_BLOCK
    | LANDLOCK_MAKE_SYM
    | LANDLOCK_REFER
    | LANDLOCK_TRUNCATE;
const LANDLOCK_HANDLED: u64 = LANDLOCK_READ | LANDLOCK_WRITE;
const SECCOMP_RET_KILL_PROCESS: u32 = 0x8000_0000;
const SECCOMP_RET_ERRNO: u32 = 0x0005_0000;
const SECCOMP_RET_ALLOW: u32 = 0x7fff_0000;
const PR_SET_NO_NEW_PRIVS: libc::c_int = 38;
const PR_SET_SECCOMP: libc::c_int = 22;
const PRIVATE_LAUNCHER_MARKER: &str = "--tapid-private-linux-procfs-v1";
const LANDLOCK_RULESET_FD: libc::c_int = 198;
const PRIVATE_REPORT_FD: libc::c_int = 199;
const MANAGED_SUPERVISOR_FD: libc::c_int = 200;
const PRIVATE_REPORT_MAGIC: &[u8; 4] = b"TPMS";
const PRIVATE_REPORT_FRAME_BYTES: usize = 12;
const PRIVATE_REPORT_READY: u32 = 1;
const PRIVATE_REPORT_SETUP_ERROR: u32 = 2;
const PRIVATE_REPORT_EXEC_ERROR: u32 = 3;
const LIMITATIONS: &[&str] = &[
    "Restricted only; ManagedTree and configured resource limits remain unsupported",
    "Landlock grants use path bindings checked against held filesystem identities before setup",
    "network-disabled policy denies Internet socket creation, connection, binding, listening, accepts, sendto, and recvfrom; AF_UNIX socketpairs with sendmsg/recvmsg and shutdown remain available for local runtime IPC; enabled networking is unrestricted",
    "Restricted does not own or guarantee cleanup of detached descendants",
    "standard streams remain connected; other inherited descriptors are closed",
];

#[path = "linux_restricted/managed.rs"]
mod managed;
#[path = "linux_restricted/toolchain.rs"]
mod toolchain;
pub(super) fn toolchain_identity() -> Result<String, ExecutionError> {
    toolchain::identity(&system_runtime_paths(true))
}

fn system_runtime_paths(managed_tree: bool) -> Vec<std::path::PathBuf> {
    let mut paths = [
        "/usr/bin",
        "/usr/lib",
        "/usr/lib64",
        "/lib",
        "/lib64",
        "/etc/ld.so.cache",
        "/etc/ssl/certs",
        "/etc/ssl/openssl.cnf",
        "/etc/localtime",
    ]
    .into_iter()
    .filter_map(|path| fs::canonicalize(path).ok())
    .collect::<Vec<_>>();
    if managed_tree {
        paths.extend(
            [
                "/dev/null",
                "/dev/zero",
                "/dev/random",
                "/dev/urandom",
                "/usr/include",
                "/usr/libexec",
                "/usr/share/ca-certificates",
                "/usr/share/nodejs",
            ]
            .into_iter()
            .filter_map(|path| fs::canonicalize(path).ok()),
        );
    }
    paths.sort();
    paths.dedup();
    paths
}

#[repr(C)]
struct RulesetAttr {
    handled_access_fs: u64,
}
#[repr(C)]
struct PathBeneathAttr {
    allowed_access: u64,
    parent_fd: libc::c_int,
    reserved: u32,
}

struct LandlockRuleset(OwnedFd);

impl LandlockRuleset {
    fn new() -> Result<Self, ExecutionError> {
        let abi = landlock_abi().ok_or_else(|| unsupported("Landlock is unavailable"))?;
        if abi < 3 {
            return Err(unsupported("Landlock ABI 3 or newer is required"));
        }
        let attr = RulesetAttr {
            handled_access_fs: LANDLOCK_HANDLED,
        };
        let fd = unsafe {
            libc::syscall(
                libc::SYS_landlock_create_ruleset,
                &attr,
                std::mem::size_of::<RulesetAttr>(),
                0u32,
            ) as libc::c_int
        };
        if fd < 0 {
            return Err(unsupported("cannot create Landlock ruleset"));
        }
        Ok(Self(unsafe { OwnedFd::from_raw_fd(fd) }))
    }

    fn add_grants(
        &self,
        policy: &ResolvedSandboxPolicy,
        bindings: &FilesystemBindings,
    ) -> Result<(), ExecutionError> {
        let grants = policy.read.iter().chain(&policy.write).collect::<Vec<_>>();
        if grants.len() != bindings.grants.len() {
            return Err(policy_error(
                "filesystem bindings differ from resolved policy",
            ));
        }
        for (grant, binding) in grants.into_iter().zip(&bindings.grants) {
            let held = binding.held.as_ref().ok_or_else(|| {
                unsupported("Landlock requires held native filesystem identities")
            })?;
            let original = held
                .metadata()
                .map_err(|e| policy_error(&format!("cannot inspect held filesystem grant: {e}")))?;
            let path = open_path(&grant.path)?;
            let current = path
                .metadata()
                .map_err(|e| policy_error(&format!("cannot inspect filesystem grant: {e}")))?;
            if (original.dev(), original.ino()) != (current.dev(), current.ino()) {
                return Err(policy_error(
                    "filesystem grant identity changed before Landlock setup",
                ));
            }
            let access = match grant.access {
                FilesystemAccess::Read => {
                    if matches!(
                        grant.kind,
                        FilesystemGrantKind::ExactFile | FilesystemGrantKind::CharacterDevice
                    ) {
                        LANDLOCK_READ_FILE
                    } else {
                        LANDLOCK_READ
                    }
                }
                FilesystemAccess::ReadData => LANDLOCK_READ_FILE,
                FilesystemAccess::ReadMetadata => {
                    return Err(unsupported("Landlock cannot enforce metadata-only grants"));
                }
                FilesystemAccess::Write => {
                    if grant.kind == FilesystemGrantKind::CharacterDevice {
                        LANDLOCK_WRITE_FILE
                    } else if grant.kind == FilesystemGrantKind::ExactFile {
                        LANDLOCK_WRITE_FILE | LANDLOCK_TRUNCATE
                    } else {
                        LANDLOCK_WRITE
                    }
                }
            };
            let attr = PathBeneathAttr {
                allowed_access: access,
                parent_fd: path.as_raw_fd(),
                reserved: 0,
            };
            let result = unsafe {
                libc::syscall(
                    libc::SYS_landlock_add_rule,
                    self.0.as_raw_fd(),
                    LANDLOCK_RULE_PATH_BENEATH,
                    &attr,
                    0u32,
                )
            };
            if result < 0 {
                return Err(unsupported("cannot add required Landlock path rule"));
            }
        }
        Ok(())
    }
}

fn open_path(path: &Path) -> Result<File, ExecutionError> {
    use std::os::unix::fs::OpenOptionsExt;
    let mut options = OpenOptions::new();
    options
        .read(true)
        .custom_flags(libc::O_PATH | libc::O_CLOEXEC | libc::O_NOFOLLOW);
    options.open(path).map_err(|e| {
        policy_error(&format!(
            "cannot open filesystem grant {}: {e}",
            path.display()
        ))
    })
}

fn landlock_abi() -> Option<i32> {
    let result = unsafe {
        libc::syscall(
            libc::SYS_landlock_create_ruleset,
            std::ptr::null::<RulesetAttr>(),
            0usize,
            LANDLOCK_CREATE_RULESET_VERSION,
        ) as i32
    };
    (result >= 0).then_some(result)
}

#[cfg(target_arch = "x86_64")]
const AUDIT_ARCH: u32 = 0xc000_003e;
#[cfg(target_arch = "aarch64")]
const AUDIT_ARCH: u32 = 0xc000_00b7;

fn seccomp_filter(
    network: bool,
    subprocess: bool,
) -> Result<Vec<libc::sock_filter>, ExecutionError> {
    #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
    return Err(unsupported(
        "seccomp is supported only on x86_64 and aarch64",
    ));
    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
    {
        let mut filter = vec![
            libc::sock_filter {
                code: (libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16,
                jt: 0,
                jf: 0,
                k: 4,
            },
            libc::sock_filter {
                code: (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16,
                jt: 1,
                jf: 0,
                k: AUDIT_ARCH,
            },
            libc::sock_filter {
                code: (libc::BPF_RET | libc::BPF_K) as u16,
                jt: 0,
                jf: 0,
                k: SECCOMP_RET_KILL_PROCESS,
            },
            libc::sock_filter {
                code: (libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16,
                jt: 0,
                jf: 0,
                k: 0,
            },
        ];
        // x32 uses the same audit architecture as x86_64 but different syscall
        // numbers. Restricted supports the native ABI only; reject all x32
        // calls before the native denylist, including process_vm's 539/540.
        #[cfg(target_arch = "x86_64")]
        filter.extend([
            libc::sock_filter {
                code: (libc::BPF_JMP | libc::BPF_JSET | libc::BPF_K) as u16,
                jt: 0,
                jf: 1,
                k: 0x4000_0000,
            },
            libc::sock_filter {
                code: (libc::BPF_RET | libc::BPF_K) as u16,
                jt: 0,
                jf: 0,
                k: SECCOMP_RET_ERRNO | libc::EPERM as u32,
            },
        ]);
        let mut denied = vec![
            libc::SYS_bpf,
            libc::SYS_ptrace,
            libc::SYS_process_vm_readv,
            libc::SYS_process_vm_writev,
            libc::SYS_pidfd_open,
            libc::SYS_pidfd_getfd,
            libc::SYS_mount,
            libc::SYS_umount2,
            libc::SYS_open_tree,
            libc::SYS_move_mount,
            libc::SYS_fsopen,
            libc::SYS_fsconfig,
            libc::SYS_fsmount,
            libc::SYS_mount_setattr,
            libc::SYS_pivot_root,
            libc::SYS_setns,
            libc::SYS_unshare,
            libc::SYS_keyctl,
            libc::SYS_perf_event_open,
            libc::SYS_open_by_handle_at,
            libc::SYS_io_uring_setup,
        ];
        if !network {
            // AF_UNIX socketpairs are allowed; sendmsg/recvmsg/shutdown support local runtime IPC.
            // socket(), binding, listening, connecting, accepting, sendto, and recvfrom stay denied.
            filter.extend([
                libc::sock_filter {
                    code: (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16,
                    jt: 0,
                    jf: 3,
                    k: libc::SYS_socketpair as u32,
                },
                libc::sock_filter {
                    code: (libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16,
                    jt: 0,
                    jf: 0,
                    k: 16, // seccomp_data.args[0] (domain)
                },
                libc::sock_filter {
                    code: (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16,
                    jt: 1,
                    jf: 0,
                    k: libc::AF_UNIX as u32,
                },
                libc::sock_filter {
                    code: (libc::BPF_RET | libc::BPF_K) as u16,
                    jt: 0,
                    jf: 0,
                    k: SECCOMP_RET_ERRNO | libc::EPERM as u32,
                },
            ]);
            denied.extend([
                libc::SYS_socket,
                libc::SYS_connect,
                libc::SYS_accept,
                libc::SYS_accept4,
                libc::SYS_bind,
                libc::SYS_listen,
                libc::SYS_sendto,
                libc::SYS_recvfrom,
            ]);
        }
        if !subprocess {
            denied.extend([libc::SYS_clone, libc::SYS_clone3]);
            #[cfg(target_arch = "x86_64")]
            denied.extend([libc::SYS_fork, libc::SYS_vfork]);
        }
        for syscall in denied {
            filter.push(libc::sock_filter {
                code: (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16,
                jt: 0,
                jf: 1,
                k: syscall as u32,
            });
            filter.push(libc::sock_filter {
                code: (libc::BPF_RET | libc::BPF_K) as u16,
                jt: 0,
                jf: 0,
                k: SECCOMP_RET_ERRNO | libc::EPERM as u32,
            });
        }
        filter.push(libc::sock_filter {
            code: (libc::BPF_RET | libc::BPF_K) as u16,
            jt: 0,
            jf: 0,
            k: SECCOMP_RET_ALLOW,
        });
        if filter.len() > u16::MAX as usize {
            return Err(unsupported("seccomp filter exceeds kernel limit"));
        }
        Ok(filter)
    }
}

fn install_restrictions(
    ruleset: libc::c_int,
    filter: &[libc::sock_filter],
    preserve_fd: Option<libc::c_int>,
) -> io::Result<()> {
    if unsafe { libc::prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) } != 0 {
        return Err(io::Error::last_os_error());
    }
    if unsafe { libc::syscall(libc::SYS_landlock_restrict_self, ruleset, 0u32) } < 0 {
        return Err(io::Error::last_os_error());
    }
    match preserve_fd {
        Some(fd) if fd > 3 => {
            if unsafe { libc::syscall(libc::SYS_close_range, 3u32, (fd - 1) as u32, 0u32) } < 0 {
                return Err(io::Error::last_os_error());
            }
            if unsafe { libc::syscall(libc::SYS_close_range, (fd + 1) as u32, u32::MAX, 0u32) } < 0
            {
                return Err(io::Error::last_os_error());
            }
        }
        Some(_) => {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "invalid preserved descriptor",
            ));
        }
        None => {
            if unsafe { libc::syscall(libc::SYS_close_range, 3u32, u32::MAX, 0u32) } < 0 {
                return Err(io::Error::last_os_error());
            }
        }
    }
    let mut program = libc::sock_fprog {
        len: filter.len() as u16,
        filter: filter.as_ptr() as *mut libc::sock_filter,
    };
    if unsafe { libc::prctl(PR_SET_SECCOMP, 2, &mut program) } != 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}

fn add_private_procfs_read_rule(ruleset: libc::c_int) -> io::Result<()> {
    const PROC_ROOT: &[u8] = b"/proc\0";
    let fd = unsafe {
        libc::syscall(
            libc::SYS_openat,
            libc::AT_FDCWD,
            PROC_ROOT.as_ptr(),
            libc::O_PATH | libc::O_CLOEXEC | libc::O_NOFOLLOW,
            0,
        ) as libc::c_int
    };
    if fd < 0 {
        return Err(io::Error::last_os_error());
    }
    let attr = PathBeneathAttr {
        allowed_access: LANDLOCK_READ,
        parent_fd: fd,
        reserved: 0,
    };
    let result = unsafe {
        libc::syscall(
            libc::SYS_landlock_add_rule,
            ruleset,
            LANDLOCK_RULE_PATH_BENEATH,
            &attr,
            0u32,
        )
    };
    let error = (result < 0).then(io::Error::last_os_error);
    unsafe {
        libc::close(fd);
    }
    if let Some(error) = error {
        Err(error)
    } else {
        Ok(())
    }
}

fn namespace_identity(name: &str) -> io::Result<(u64, u64)> {
    let metadata = fs::metadata(format!("/proc/self/ns/{name}"))?;
    Ok((metadata.dev(), metadata.ino()))
}

fn establish_private_read_only_procfs(
    parent_pid_namespace: (u64, u64),
    parent_mount_namespace: (u64, u64),
) -> io::Result<()> {
    if namespace_identity("pid")? == parent_pid_namespace
        || namespace_identity("mnt")? == parent_mount_namespace
        || unsafe { libc::getpid() } != 1
    {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            "private PID or mount namespace was not established",
        ));
    }
    if unsafe {
        libc::mount(
            std::ptr::null(),
            c"/".as_ptr(),
            std::ptr::null(),
            libc::MS_REC | libc::MS_PRIVATE,
            std::ptr::null(),
        )
    } != 0
    {
        return Err(io::Error::last_os_error());
    }
    if unsafe {
        libc::mount(
            std::ptr::null(),
            c"/proc".as_ptr(),
            std::ptr::null(),
            libc::MS_REMOUNT | libc::MS_RDONLY | libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC,
            std::ptr::null(),
        )
    } != 0
    {
        return Err(io::Error::last_os_error());
    }
    let mut proc_stats: libc::statvfs = unsafe { std::mem::zeroed() };
    if unsafe { libc::statvfs(c"/proc".as_ptr(), &mut proc_stats) } != 0 {
        return Err(io::Error::last_os_error());
    }
    if proc_stats.f_flag & libc::ST_RDONLY as libc::c_ulong == 0 {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            "private procfs mount is not read-only",
        ));
    }
    Ok(())
}

fn write_private_report(fd: libc::c_int, kind: u32, value: i32) -> io::Result<()> {
    let mut frame = [0_u8; PRIVATE_REPORT_FRAME_BYTES];
    frame[..4].copy_from_slice(PRIVATE_REPORT_MAGIC);
    frame[4..8].copy_from_slice(&kind.to_le_bytes());
    frame[8..12].copy_from_slice(&value.to_le_bytes());
    let mut offset = 0;
    while offset < frame.len() {
        let result =
            unsafe { libc::write(fd, frame[offset..].as_ptr().cast(), frame.len() - offset) };
        if result < 0 {
            let error = io::Error::last_os_error();
            if error.kind() == io::ErrorKind::Interrupted {
                continue;
            }
            return Err(error);
        }
        if result == 0 {
            return Err(io::Error::new(
                io::ErrorKind::WriteZero,
                "private launcher report pipe closed",
            ));
        }
        offset += result as usize;
    }
    Ok(())
}

fn parse_private_bool(value: OsString, name: &str) -> io::Result<bool> {
    match value.to_str() {
        Some("0") => Ok(false),
        Some("1") => Ok(true),
        _ => Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("invalid private launcher {name}"),
        )),
    }
}

fn parse_private_number<T: std::str::FromStr>(value: OsString, name: &str) -> io::Result<T> {
    value
        .to_str()
        .and_then(|value| value.parse().ok())
        .ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("invalid private launcher {name}"),
            )
        })
}

fn private_launcher_setup(
    arguments: Vec<OsString>,
) -> io::Result<(libc::c_int, OsString, Vec<OsString>)> {
    let mut arguments = arguments.into_iter();
    if arguments.next().as_deref() != Some(OsStr::new(PRIVATE_LAUNCHER_MARKER)) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "private launcher marker is missing",
        ));
    }
    let network = parse_private_bool(
        arguments
            .next()
            .ok_or_else(|| io::Error::other("missing network flag"))?,
        "network flag",
    )?;
    let subprocess = parse_private_bool(
        arguments
            .next()
            .ok_or_else(|| io::Error::other("missing subprocess flag"))?,
        "subprocess flag",
    )?;
    let ruleset = parse_private_number::<libc::c_int>(
        arguments
            .next()
            .ok_or_else(|| io::Error::other("missing ruleset descriptor"))?,
        "ruleset descriptor",
    )?;
    let report_fd = parse_private_number::<libc::c_int>(
        arguments
            .next()
            .ok_or_else(|| io::Error::other("missing report descriptor"))?,
        "report descriptor",
    )?;
    let parent_pid_namespace = (
        parse_private_number::<u64>(
            arguments
                .next()
                .ok_or_else(|| io::Error::other("missing PID namespace device"))?,
            "PID namespace device",
        )?,
        parse_private_number::<u64>(
            arguments
                .next()
                .ok_or_else(|| io::Error::other("missing PID namespace inode"))?,
            "PID namespace inode",
        )?,
    );
    let parent_mount_namespace = (
        parse_private_number::<u64>(
            arguments
                .next()
                .ok_or_else(|| io::Error::other("missing mount namespace device"))?,
            "mount namespace device",
        )?,
        parse_private_number::<u64>(
            arguments
                .next()
                .ok_or_else(|| io::Error::other("missing mount namespace inode"))?,
            "mount namespace inode",
        )?,
    );
    let managed_tree = parse_private_bool(
        arguments
            .next()
            .ok_or_else(|| io::Error::other("missing managed-tree flag"))?,
        "managed-tree flag",
    )?;
    let read_procfs = parse_private_bool(
        arguments
            .next()
            .ok_or_else(|| io::Error::other("missing procfs flag"))?,
        "procfs flag",
    )?;
    let write_count = parse_private_number::<usize>(
        arguments
            .next()
            .ok_or_else(|| io::Error::other("missing write binding count"))?,
        "write binding count",
    )?;
    if write_count > crate::config::MAX_GRANT_COUNT || (!managed_tree && write_count != 0) {
        return Err(io::Error::other("invalid managed write bindings"));
    }
    let mut writes = Vec::with_capacity(write_count);
    for _ in 0..write_count {
        let path = std::path::PathBuf::from(
            arguments
                .next()
                .ok_or_else(|| io::Error::other("missing write path"))?,
        );
        let device = parse_private_number(
            arguments
                .next()
                .ok_or_else(|| io::Error::other("missing write device"))?,
            "write device",
        )?;
        let inode = parse_private_number(
            arguments
                .next()
                .ok_or_else(|| io::Error::other("missing write inode"))?,
            "write inode",
        )?;
        writes.push((path, device, inode));
    }
    let view = if managed_tree {
        let path = std::path::PathBuf::from(
            arguments
                .next()
                .ok_or_else(|| io::Error::other("missing filesystem view"))?,
        );
        let device = parse_private_number(
            arguments
                .next()
                .ok_or_else(|| io::Error::other("missing view device"))?,
            "view device",
        )?;
        let inode = parse_private_number(
            arguments
                .next()
                .ok_or_else(|| io::Error::other("missing view inode"))?,
            "view inode",
        )?;
        Some((path, device, inode))
    } else {
        None
    };
    let program = arguments
        .next()
        .ok_or_else(|| io::Error::other("missing target program"))?;
    let program_arguments = arguments.collect::<Vec<_>>();
    if ruleset < 3 || report_fd < 3 || ruleset == report_fd {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "invalid private launcher descriptors",
        ));
    }
    let mut report_stat: libc::stat = unsafe { std::mem::zeroed() };
    if unsafe { libc::fstat(report_fd, &mut report_stat) } != 0
        || report_stat.st_mode & libc::S_IFMT != libc::S_IFSOCK
    {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "private launcher report descriptor is not a socket",
        ));
    }
    establish_private_read_only_procfs(parent_pid_namespace, parent_mount_namespace)?;
    if read_procfs {
        add_private_procfs_read_rule(ruleset)?;
    }
    if managed_tree {
        managed::protect_namespace_init(&writes, view.as_ref().unwrap())?;
    }
    let filter = if managed_tree {
        managed::filter(network, subprocess)
    } else {
        seccomp_filter(network, subprocess)
    }
    .map_err(|error| io::Error::new(io::ErrorKind::Unsupported, error.to_string()))?;
    install_restrictions(ruleset, &filter, Some(report_fd))?;
    Ok((report_fd, program, program_arguments))
}

fn private_launcher_entry(arguments: Vec<OsString>, report_fd: Option<libc::c_int>) -> ! {
    match private_launcher_setup(arguments) {
        Ok((report_fd, program, program_arguments)) => {
            if unsafe { libc::fcntl(report_fd, libc::F_SETFD, libc::FD_CLOEXEC) } < 0 {
                let error = io::Error::last_os_error();
                let _ = write_private_report(
                    report_fd,
                    PRIVATE_REPORT_SETUP_ERROR,
                    error.raw_os_error().unwrap_or(libc::EIO),
                );
                eprintln!("tapid: cannot protect private launcher report descriptor: {error}");
                unsafe { libc::_exit(125) }
            }
            if let Err(error) = write_private_report(report_fd, PRIVATE_REPORT_READY, 0) {
                eprintln!("tapid: cannot confirm private procfs setup: {error}");
                unsafe { libc::_exit(125) }
            }
            let error = Command::new(program).args(program_arguments).exec();
            let _ = write_private_report(
                report_fd,
                PRIVATE_REPORT_EXEC_ERROR,
                error.raw_os_error().unwrap_or(libc::EIO),
            );
            eprintln!("tapid: cannot exec restricted project script: {error}");
            unsafe { libc::_exit(127) }
        }
        Err(error) => {
            if let Some(report_fd) = report_fd {
                let _ = write_private_report(
                    report_fd,
                    PRIVATE_REPORT_SETUP_ERROR,
                    error.raw_os_error().unwrap_or(libc::EIO),
                );
            }
            eprintln!("tapid: cannot establish private read-only procfs: {error}");
            unsafe { libc::_exit(125) }
        }
    }
}

pub(crate) fn dispatch_private_launcher() {
    let arguments = std::env::args_os().skip(1).collect::<Vec<_>>();
    if arguments.first().map(OsString::as_os_str) != Some(OsStr::new(PRIVATE_LAUNCHER_MARKER)) {
        return;
    }
    let report_fd = arguments
        .get(4)
        .and_then(|value| value.to_str())
        .and_then(|value| value.parse::<libc::c_int>().ok());
    private_launcher_entry(arguments, report_fd);
}

fn parse_private_report(mut report: UnixStream) -> Result<(), ExecutionError> {
    let mut bytes = Vec::new();
    Read::by_ref(&mut report)
        .take((2 * PRIVATE_REPORT_FRAME_BYTES + 1) as u64)
        .read_to_end(&mut bytes)
        .map_err(|error| {
            unsupported(&format!("cannot read private procfs setup report: {error}"))
        })?;
    if bytes.is_empty()
        || bytes.len() > 2 * PRIVATE_REPORT_FRAME_BYTES
        || bytes.len() % PRIVATE_REPORT_FRAME_BYTES != 0
    {
        return Err(unsupported(
            "private PID/mount namespace setup did not provide confirmation",
        ));
    }
    let mut ready = false;
    let (frames, remainder) = bytes.as_chunks::<PRIVATE_REPORT_FRAME_BYTES>();
    if !remainder.is_empty() {
        return Err(unsupported("private procfs setup report was invalid"));
    }
    for frame in frames {
        if &frame[..4] != PRIVATE_REPORT_MAGIC {
            return Err(unsupported("private procfs setup report was invalid"));
        }
        let kind = u32::from_le_bytes(frame[4..8].try_into().expect("fixed report field"));
        let value = i32::from_le_bytes(frame[8..12].try_into().expect("fixed report field"));
        match kind {
            PRIVATE_REPORT_READY if !ready => ready = true,
            PRIVATE_REPORT_SETUP_ERROR => {
                return Err(unsupported(&format!(
                    "private read-only procfs setup failed (errno {value})"
                )));
            }
            PRIVATE_REPORT_EXEC_ERROR => {
                return Err(ExecutionError::new(
                    ExecutionErrorCategory::Spawn,
                    format!("cannot exec restricted project script (errno {value})"),
                ));
            }
            _ => return Err(unsupported("private procfs setup report was invalid")),
        }
    }
    if ready {
        Ok(())
    } else {
        Err(unsupported(
            "private PID/mount namespace setup did not provide confirmation",
        ))
    }
}

fn locate_unshare() -> Result<std::path::PathBuf, ExecutionError> {
    for candidate in ["/usr/bin/unshare", "/bin/unshare"] {
        let path = Path::new(candidate);
        let Ok(metadata) = fs::metadata(path) else {
            continue;
        };
        if metadata.is_file() && metadata.permissions().mode() & 0o111 != 0 {
            return fs::canonicalize(path).map_err(|error| {
                unsupported(&format!("cannot resolve util-linux unshare: {error}"))
            });
        }
    }
    Err(unsupported(
        "process-memory-stat opt-in requires the util-linux unshare command",
    ))
}

fn unshare_namespace_arguments(is_root: bool) -> Vec<&'static str> {
    let mut arguments = Vec::with_capacity(8);
    if !is_root {
        arguments.extend(["--user", "--map-root-user"]);
    }
    arguments.extend([
        "--mount",
        "--pid",
        "--fork",
        "--kill-child",
        "--mount-proc",
        "--propagation",
        "private",
        "--",
    ]);
    arguments
}

fn duplicate_fd_above_private_range(fd: libc::c_int) -> Result<OwnedFd, ExecutionError> {
    let duplicate = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, PRIVATE_REPORT_FD + 1) };
    if duplicate < 0 {
        return Err(unsupported(&format!(
            "cannot duplicate private launcher descriptor: {}",
            io::Error::last_os_error()
        )));
    }
    Ok(unsafe { OwnedFd::from_raw_fd(duplicate) })
}

fn private_memory_stats_command(
    request: &ExecutionRequest,
    ruleset: &OwnedFd,
    managed_preflight: Option<&ValidatedPreflight>,
    view: Option<(&Path, u64, u64)>,
) -> Result<(Command, UnixStream), ExecutionError> {
    let managed_tree = managed_preflight.is_some();
    let writes = if let Some(preflight) = managed_preflight {
        preflight
            .policy
            .read
            .iter()
            .chain(&preflight.policy.write)
            .zip(&preflight.bindings.grants)
            .filter(|(grant, _)| {
                grant.access == FilesystemAccess::Write
                    && grant.kind != FilesystemGrantKind::CharacterDevice
            })
            .map(|(grant, binding)| {
                binding
                    .held
                    .as_ref()
                    .ok_or_else(|| unsupported("managed writes require held identities"))?
                    .metadata()
                    .map(|metadata| (grant.path.clone(), metadata.dev(), metadata.ino()))
                    .map_err(|error| unsupported(&error.to_string()))
            })
            .collect::<Result<Vec<_>, _>>()?
    } else {
        Vec::new()
    };
    let launcher = request
        .private_launcher_executable()
        .ok_or_else(|| unsupported("private launcher was not initialized"))?;
    let unshare = locate_unshare()?;
    let parent_pid_namespace = namespace_identity("pid")
        .map_err(|error| unsupported(&format!("cannot identify parent PID namespace: {error}")))?;
    let parent_mount_namespace = namespace_identity("mnt").map_err(|error| {
        unsupported(&format!("cannot identify parent mount namespace: {error}"))
    })?;
    let (report_reader, report_writer) = UnixStream::pair().map_err(|error| {
        unsupported(&format!(
            "cannot create private launcher report channel: {error}"
        ))
    })?;
    let ruleset_copy = duplicate_fd_above_private_range(ruleset.as_raw_fd())?;
    let report_copy = duplicate_fd_above_private_range(report_writer.as_raw_fd())?;
    let mut command = Command::new(unshare);
    command
        .args(unshare_namespace_arguments(unsafe { libc::geteuid() == 0 }))
        .arg(launcher)
        .arg(PRIVATE_LAUNCHER_MARKER)
        .arg(if request.policy().network() { "1" } else { "0" })
        .arg(if request.policy().subprocess() {
            "1"
        } else {
            "0"
        })
        .arg(LANDLOCK_RULESET_FD.to_string())
        .arg(PRIVATE_REPORT_FD.to_string())
        .arg(parent_pid_namespace.0.to_string())
        .arg(parent_pid_namespace.1.to_string())
        .arg(parent_mount_namespace.0.to_string())
        .arg(parent_mount_namespace.1.to_string())
        .arg(if managed_tree { "1" } else { "0" })
        .arg(if request.allow_process_memory_stats() {
            "1"
        } else {
            "0"
        })
        .arg(writes.len().to_string());
    for (path, device, inode) in writes {
        command
            .arg(path)
            .arg(device.to_string())
            .arg(inode.to_string());
    }
    if managed_tree {
        let (path, device, inode) =
            view.ok_or_else(|| unsupported("managed filesystem view is missing"))?;
        command
            .arg(path)
            .arg(device.to_string())
            .arg(inode.to_string());
    }
    command.arg(request.program()).args(request.arguments());
    let ruleset_source = ruleset_copy.as_raw_fd();
    let report_source = report_copy.as_raw_fd();
    unsafe {
        command.pre_exec(move || {
            let _keep_open = (&ruleset_copy, &report_copy);
            if libc::dup2(ruleset_source, LANDLOCK_RULESET_FD) < 0
                || libc::dup2(report_source, PRIVATE_REPORT_FD) < 0
            {
                return Err(io::Error::last_os_error());
            }
            for fd in [LANDLOCK_RULESET_FD, PRIVATE_REPORT_FD] {
                let flags = libc::fcntl(fd, libc::F_GETFD);
                if flags < 0 || libc::fcntl(fd, libc::F_SETFD, flags & !libc::FD_CLOEXEC) < 0 {
                    return Err(io::Error::last_os_error());
                }
            }
            Ok(())
        });
    }
    drop(report_writer);
    Ok((command, report_reader))
}

fn is_process_memory_stats_permission_error(stderr: &[u8]) -> bool {
    let contains = |needle: &[u8]| stderr.windows(needle.len()).any(|window| window == needle);
    contains(b"uv_resident_set_memory") && (contains(b"EACCES") || contains(b"permission denied"))
}

fn unsupported(message: &str) -> ExecutionError {
    ExecutionError::new(ExecutionErrorCategory::UnsupportedContainment, message)
}
fn policy_error(message: &str) -> ExecutionError {
    ExecutionError::new(ExecutionErrorCategory::PolicyViolation, message)
}

pub(super) struct PlatformBackend;
impl ExecutionBackend for PlatformBackend {
    fn containment_support(&self, request: &ExecutionRequest) -> ContainmentSupport {
        containment_support(request)
    }

    fn runtime_filesystem_additions(
        &self,
        request: &ExecutionRequest,
    ) -> Result<RuntimeFilesystemAdditions, ExecutionError> {
        let paths =
            system_runtime_paths(request.policy().assurance() == AssuranceLevel::ManagedTree);
        if request.policy().assurance() == AssuranceLevel::ManagedTree {
            return RuntimeFilesystemAdditions::checked(
                paths,
                vec![Path::new("/dev/null").to_path_buf()],
            );
        }
        RuntimeFilesystemAdditions::checked(paths, Vec::new())
    }

    fn bind_filesystem(
        &self,
        _request: &ExecutionRequest,
        policy: &ResolvedSandboxPolicy,
    ) -> Result<FilesystemBindings, ExecutionError> {
        FilesystemBindings::native_objects(policy)
    }

    fn prepare<'a>(
        &'a self,
        request: &ExecutionRequest,
        preflight: &'a ValidatedPreflight,
    ) -> Result<OwnedExecutionAttempt<'a>, PreparationError> {
        let ruleset = LandlockRuleset::new().map_err(PreparationError::from)?;
        ruleset
            .add_grants(&preflight.policy, &preflight.bindings)
            .map_err(PreparationError::from)?;
        if request.policy().assurance() == AssuranceLevel::ManagedTree {
            return managed::prepare(request, preflight, ruleset);
        }
        let filter = seccomp_filter(request.policy().network(), request.policy().subprocess())
            .map_err(PreparationError::from)?;
        Ok(OwnedExecutionAttempt::new(
            preflight,
            Box::new(LinuxLifecycle {
                request: request.clone(),
                preflight,
                ruleset,
                filter,
                termination: None,
            }),
        ))
    }
}

fn backend_identity() -> BackendIdentity {
    BackendIdentity::new(
        "tapid-runner/linux-landlock-seccomp-restricted",
        format!(
            "{}; Landlock ABI {}",
            env!("CARGO_PKG_VERSION"),
            landlock_abi().unwrap_or(0)
        ),
        None,
    )
    .expect("static Linux identity is valid")
}

pub(super) fn containment_support(request: &ExecutionRequest) -> ContainmentSupport {
    if request.policy().assurance() == AssuranceLevel::ManagedTree {
        return managed::containment_support(request);
    }
    let requested = EnforcementDimensions::requested_by(request.policy());
    let identity = backend_identity();
    let unsupported = |reason: &str| {
        ContainmentSupport::unsupported(
            identity.clone(),
            "linux",
            reason,
            requested.clone(),
            EnforcementDimensions::none(),
            EnforcementDimensions::none(),
        )
    };
    if request.policy().assurance() != AssuranceLevel::Restricted {
        return unsupported("Linux ManagedTree containment is unavailable");
    }
    if landlock_abi().is_none_or(|abi| abi < 3) {
        return unsupported("Landlock ABI 3 or newer is unavailable");
    }
    let limits = request.policy().limits();
    if limits.timeout_seconds().is_some()
        || limits.max_output_bytes().is_some()
        || limits.max_processes().is_some()
        || limits.max_memory_bytes().is_some()
    {
        return unsupported("Linux Restricted does not enforce configured resource limits");
    }
    if seccomp_filter(request.policy().network(), request.policy().subprocess()).is_err() {
        return unsupported("required seccomp architecture or filter is unavailable");
    }
    let evidence = evidence_for_dimensions(
        &requested,
        "Landlock ABI 3, no_new_privs, seccomp, explicit environment and close_range descriptor sanitation",
        LIMITATIONS,
    );
    ContainmentSupport::supported(
        identity,
        requested.clone(),
        requested.clone(),
        requested,
        evidence.clone(),
        evidence,
    )
}

struct LinuxLifecycle<'a> {
    request: ExecutionRequest,
    preflight: &'a ValidatedPreflight,
    ruleset: LandlockRuleset,
    filter: Vec<libc::sock_filter>,
    termination: Option<Termination>,
}
impl ExecutionLifecycle for LinuxLifecycle<'_> {
    fn execute(&mut self) -> Result<Box<ExecutionOutcome>, ExecutionError> {
        let allow_process_memory_stats = self.request.allow_process_memory_stats();
        let (mut command, private_report) = if allow_process_memory_stats {
            let (command, report) =
                private_memory_stats_command(&self.request, &self.ruleset.0, None, None)?;
            (command, Some(report))
        } else {
            let mut command = Command::new(self.request.program());
            command.args(self.request.arguments());
            let ruleset = self.ruleset.0.try_clone().map_err(|e| {
                ExecutionError::new(
                    ExecutionErrorCategory::Spawn,
                    format!("cannot duplicate Landlock ruleset: {e}"),
                )
            })?;
            let filter = self.filter.clone();
            unsafe {
                command.pre_exec(move || install_restrictions(ruleset.as_raw_fd(), &filter, None));
            }
            (command, None)
        };
        command
            .current_dir(self.request.working_directory())
            .env_clear()
            .envs(&self.preflight.child_environment)
            .stdin(Stdio::null())
            .stdout(Stdio::inherit())
            .stderr(Stdio::piped());
        let mut child = command.spawn().map_err(|e| {
            ExecutionError::new(
                ExecutionErrorCategory::Spawn,
                format!("cannot launch restricted project script: {e}"),
            )
        })?;
        drop(command);
        let mut child_stderr = child
            .stderr
            .take()
            .expect("stderr was configured as a pipe");
        let stderr_reader = std::thread::spawn(move || {
            const DETECTION_WINDOW: usize = 128;
            let mut output = io::stderr().lock();
            let mut carry = Vec::with_capacity(DETECTION_WINDOW);
            let mut buffer = [0_u8; 4096];
            let mut denied = false;
            loop {
                let count = child_stderr.read(&mut buffer)?;
                if count == 0 {
                    break;
                }
                let _ = output.write_all(&buffer[..count]);
                let mut window = std::mem::take(&mut carry);
                window.extend_from_slice(&buffer[..count]);
                denied |= is_process_memory_stats_permission_error(&window);
                carry.extend_from_slice(&window[window.len().saturating_sub(DETECTION_WINDOW)..]);
            }
            let _ = output.flush();
            Ok::<bool, io::Error>(denied)
        });
        let status = child.wait().map_err(|e| {
            ExecutionError::new(
                ExecutionErrorCategory::Spawn,
                format!("cannot wait for restricted project script: {e}"),
            )
        })?;
        let memory_stats_denied = stderr_reader
            .join()
            .map_err(|_| {
                ExecutionError::new(
                    ExecutionErrorCategory::Internal,
                    "stderr diagnostic reader panicked",
                )
            })?
            .map_err(|e| {
                ExecutionError::new(
                    ExecutionErrorCategory::Internal,
                    format!("cannot read restricted project script stderr: {e}"),
                )
            })?;
        if let Some(report) = private_report {
            parse_private_report(report)?;
        }
        self.termination = Some(if let Some(code) = status.code() {
            Termination::Exited(code)
        } else {
            Termination::Signaled(status.signal().unwrap_or(0))
        });
        let requested = self.preflight.support.requested();
        let process_memory_stats_evidence = if allow_process_memory_stats {
            "; explicit opt-in created private PID and mount namespaces, remounted procfs read-only, and granted Landlock read access only within that namespace-scoped procfs"
        } else {
            ""
        };
        let receipt = EnforcementReceipt::checked(
            self.preflight,
            requested.clone(),
            evidence_for_dimensions(
                requested,
                &format!(
                    "Landlock and seccomp restrictions installed before target exec{process_memory_stats_evidence}"
                ),
                LIMITATIONS,
            ),
        )?;
        let completion = completion_for(self.preflight)?;
        Ok(Box::new(
            ExecutionOutcome::checked(
                self.termination.clone().unwrap(),
                Vec::new(),
                Vec::new(),
                receipt,
                completion,
            )?
            .with_process_memory_stats_hint(
                memory_stats_denied && !self.request.allow_process_memory_stats(),
            ),
        ))
    }

    fn cleanup(&mut self) -> CompletionEvidence {
        completion_for(self.preflight).expect("Restricted completion evidence is valid")
    }
}

fn completion_for(preflight: &ValidatedPreflight) -> Result<CompletionEvidence, ExecutionError> {
    CompletionEvidence::checked(
        preflight,
        EnforcementDimensions::completion_required(preflight.support.requested()),
        Vec::<DimensionEvidence>::new(),
        CleanupConfidence::NotGuaranteed,
    )
}

#[cfg(test)]
#[path = "linux_restricted/tests.rs"]
mod tests;