vetto 0.3.7

Daemon-less sandbox + security layer for AI coding agents (Landlock/Seatbelt, TUI statusline, post-session audit reports)
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
//! Real Linux enforcement for the verify-ng harness (Stage 3B).
//!
//! The [`SandboxBackend`](super::sandbox_backend::SandboxBackend) boundary
//! only *reports* enforcement; this module *installs* it. The runner applies
//! [`apply_child_plan`] in the forked child before `exec` (via
//! `Command::pre_exec`), so there is exactly one authoritative spawn path:
//! a backend cannot claim `Enforced` for a child that bypassed setup.
//!
//! Mechanisms (all unprivileged, all already used by the production
//! FS-ONLY/seccomp tiers):
//!
//! - Filesystem + execution-root isolation: Landlock allowlist
//!   (`exec_root` read/write, system roots read-only, host control dir
//!   read/write, everything else denied by default).
//! - Network isolation (`--net=off`): seccomp-BPF `UnixOnly` socket policy
//!   (non-`AF_UNIX` `socket`/`socketpair` fail with `EAFNOSUPPORT`).
//! - Syscall restriction: the same seccomp filter's hardening denylist
//!   (`mount`, `ptrace`, `io_uring_*`, `userfaultfd`, `bpf`, ... deny with
//!   `EPERM`). Verified host-side via `/proc/<pid>/status` (`Seccomp: 2`).
//! - Privilege boundary: `PR_SET_NO_NEW_PRIVS` (+ Landlock, which sets it
//!   too). Verified host-side via `NoNewPrivs: 1`.
//! - Process isolation: new process group in the child (`setpgid`), so the
//!   killer can signal the whole tree with `kill(-pgid)`.
//! - Process-tree containment: group kill plus a nonce-targeted sub-reaper
//!   sweep ([`sweep_tree_by_nonce`]). Only processes whose inherited
//!   environment carries this run's session nonce are touched, so parallel
//!   test runs can never cross-kill each other.
//! - Resource limits: `setrlimit` ceilings (`RLIMIT_AS`, `RLIMIT_NPROC`,
//!   `RLIMIT_CPU`, `RLIMIT_FSIZE`) lowered before `exec`; inherited
//!   ceilings can only be lowered, never raised, by the child. Verified
//!   host-side via `/proc/<pid>/limits`.
//!
//! Honesty rules: every probe degrades to `Unsupported`/unverified instead
//! of a fake claim. Filesystem/network isolation have no per-process kernel
//! indicator, so they stay at `Enforced` (installed without error, effect
//! proven behaviorally by the adversarial tests); only host-observed state
//! promotes to `Verified`.

/// System roots the confined child may read (interpreter, loader, configs,
/// devices). Everything else — host home, `/tmp` siblings (including the
/// dedicated denied canary dirs), `/root`, `/opt`, `/srv`, `/mnt` — is
/// denied by Landlock default-deny.
///
/// NOTE: `/tmp` and `/dev/null` stay DENIED. The dynamic loader, shell and
/// Python must therefore run without them: shell payloads redirect into
/// `$VETTO_VNG_ROOT` files, and no payload may rely on `/dev/null`,
/// `/dev/zero` or `/tmp` scratch space.
#[cfg(target_os = "linux")]
pub const SYSTEM_ROOTS: &[&str] = &[
    "/bin", "/sbin", "/lib", "/lib64", "/usr", "/etc", "/dev", "/proc",
];

/// Default ceilings applied to every Linux-backend run (lowered via
/// `setrlimit` before `exec`; the child cannot raise them afterwards).
/// Generous for shell payloads, tight enough to catch abuse:
/// - address space 256 MiB (MEM test allocates past it),
/// - max user processes 128 (PID test forks past it),
/// - CPU time 5 s (CPU test busy-loops past it; normal payloads use ~0),
/// - max file size 64 MiB.
pub const DEFAULT_RLIMIT_AS_BYTES: u64 = 256 * 1024 * 1024;
pub const DEFAULT_RLIMIT_NPROC: u64 = 128;
pub const DEFAULT_RLIMIT_CPU_SECS: u64 = 5;
pub const DEFAULT_RLIMIT_FSIZE_BYTES: u64 = 64 * 1024 * 1024;

/// Budget for one nonce-targeted tree sweep. Synchronized with MAX_EXTINCTION_DEADLINE_MS.
pub const SWEEP_BUDGET_MS: u64 = crate::proctree::MAX_EXTINCTION_DEADLINE_MS;

/// Apply the enforcement plan in the forked child before `exec`.
///
/// All-or-nothing: any enabled step that fails aborts the spawn (the
/// `pre_exec` error fails `Command::spawn` in the parent), so a child can
/// never run partially confined while the backend claims enforcement.
/// Linux-only; the non-Linux stub always errors (a plan must never exist
/// there — `prepare` reports `Unsupported` instead).
pub fn apply_child_plan(
    plan: &super::sandbox_backend::ChildEnforcementPlan,
) -> std::io::Result<()> {
    #[cfg(target_os = "linux")]
    {
        apply_child_plan_linux(plan)
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = plan;
        Err(std::io::Error::new(
            std::io::ErrorKind::Unsupported,
            "linux enforcement plan requires Linux",
        ))
    }
}

/// True when this process is a child sub-reaper (`PR_SET_CHILD_SUBREAPER`).
///
/// `PR_GET_CHILD_SUBREAPER` reports via `put_user` into the `arg2` pointer
/// (return is 0 on success), so a scalar `prctl(GET, 0, ...)` call always
/// fails with `EFAULT` — the out-pointer is mandatory.
#[cfg(target_os = "linux")]
pub(crate) fn is_child_subreaper() -> bool {
    let mut flag: libc::c_int = 0;
    // SAFETY: prctl writes 0/1 into the local int on success.
    let rc = unsafe {
        libc::prctl(
            libc::PR_GET_CHILD_SUBREAPER,
            &mut flag as *mut libc::c_int as libc::c_ulong,
            0,
            0,
            0,
        )
    };
    rc == 0 && flag == 1
}

/// Host-side verification of a live confined child, read from `/proc`
/// without trusting any child output. Best-effort with a bounded wait:
/// Expected resource limits for dynamic verification.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ExpectedLimits {
    pub rlimit_as: Option<u64>,
    pub rlimit_nproc: Option<u64>,
    pub rlimit_cpu: Option<u64>,
    pub rlimit_fsize: Option<u64>,
    pub cgroup_memory_max: Option<String>,
    pub cgroup_pids_max: Option<String>,
    pub cgroup_cpu_max: Option<String>,
    pub cgroup_swap_max: Option<String>,
}

impl ExpectedLimits {
    pub fn harness_defaults() -> Self {
        Self {
            rlimit_as: Some(DEFAULT_RLIMIT_AS_BYTES),
            rlimit_nproc: Some(DEFAULT_RLIMIT_NPROC),
            rlimit_cpu: Some(DEFAULT_RLIMIT_CPU_SECS),
            rlimit_fsize: Some(DEFAULT_RLIMIT_FSIZE_BYTES),
            cgroup_memory_max: None,
            cgroup_pids_max: None,
            cgroup_cpu_max: None,
            cgroup_swap_max: None,
        }
    }

    pub fn from_policy(policy: &crate::policy::Policy) -> Self {
        let (cg_mem, cg_pids, cg_cpu, cg_swap) = match &policy.cgroup {
            Some(cg) => (
                cg.memory_max.clone(),
                cg.pids_max.clone(),
                cg.cpu_max.clone(),
                cg.swap_max.clone(),
            ),
            None => (None, None, None, None),
        };
        let cg_cpu = cg_cpu.or_else(|| policy.cpu_max.clone());
        Self {
            rlimit_as: policy.limits.address_space_bytes,
            rlimit_nproc: policy.limits.processes,
            rlimit_cpu: policy.limits.cpu_seconds,
            rlimit_fsize: policy.limits.file_size_bytes,
            cgroup_memory_max: cg_mem,
            cgroup_pids_max: cg_pids,
            cgroup_cpu_max: cg_cpu,
            cgroup_swap_max: cg_swap,
        }
    }
}

/// Host-side verification of a live confined child, read from `/proc`
/// without trusting any child output. Best-effort with a bounded wait:
/// short-lived children may exit before every field is observed, in which
/// case the corresponding flags stay false (caps remain `Enforced`, never
/// promoted to `Verified`).
pub fn verify_child_host(pid: u32) -> super::sandbox_backend::HostVerification {
    #[cfg(target_os = "linux")]
    {
        verify_child_host_linux(pid, None)
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = pid;
        super::sandbox_backend::HostVerification::none()
    }
}

/// Dynamic host-side verification of a live confined child against expected limits.
pub fn verify_child_host_with_limits(
    pid: u32,
    expected: &ExpectedLimits,
) -> super::sandbox_backend::HostVerification {
    #[cfg(target_os = "linux")]
    {
        verify_child_host_linux(pid, Some(expected))
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = (pid, expected);
        super::sandbox_backend::HostVerification::none()
    }
}

/// Policy-driven host-side verification of a live confined child.
pub fn verify_child_host_policy(
    pid: u32,
    policy: &crate::policy::Policy,
) -> super::sandbox_backend::HostVerification {
    verify_child_host_with_limits(pid, &ExpectedLimits::from_policy(policy))
}

/// Outcome of one nonce-targeted tree sweep, with diagnostics for the
/// run detail string (never a verdict input by itself).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SweepOutcome {
    /// True when no process carrying this run's session nonce survives.
    pub clean: bool,
    /// Total SIGKILLs delivered across all passes.
    pub killed: usize,
    /// Nonce-matching pids still present at the deadline (empty when clean).
    pub residual: Vec<i32>,
    /// Whether our sub-reaper flag was observed (blind without it).
    pub subreaper: bool,
    /// True when a same-UID live process had an unreadable environ, so the
    /// scan could not prove clean (fail-closed, diagnostic only).
    pub blind: bool,
}

/// Sweep this run's residual processes after the root was reaped.
///
/// Returns `None` off Linux. Only nonce-matching processes are signalled,
/// so parallel runs are never disturbed. `clean == false` covers surviving
/// residuals and blind sweeps (no sub-reaper, or a same-UID live process
/// with an unreadable environ): both fail the tree claim closed.
pub fn sweep_tree_by_nonce(nonce: &str, root_pid: u32) -> Option<SweepOutcome> {
    #[cfg(target_os = "linux")]
    {
        Some(sweep_tree_by_nonce_linux(nonce, root_pid))
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = (nonce, root_pid);
        None
    }
}

// ---------------------------------------------------------------------------
// Linux implementation
// ---------------------------------------------------------------------------

/// Install every enabled mechanism. Errors abort the spawn (fail-closed).
#[cfg(target_os = "linux")]
fn apply_child_plan_linux(
    plan: &super::sandbox_backend::ChildEnforcementPlan,
) -> std::io::Result<()> {
    // New process group first: the host kills the tree via kill(-pgid).
    if plan.new_pgroup {
        // SAFETY: setpgid(0,0) in the freshly forked child.
        if unsafe { libc::setpgid(0, 0) } != 0 {
            return Err(std::io::Error::last_os_error());
        }
    }

    // Resource ceilings (lowering only; the child cannot raise them back).
    set_rlimit_if_some(libc::RLIMIT_AS, plan.rlimit_as)?;
    set_rlimit_if_some(libc::RLIMIT_NPROC, plan.rlimit_nproc)?;
    set_rlimit_if_some(libc::RLIMIT_CPU, plan.rlimit_cpu)?;
    set_rlimit_if_some(libc::RLIMIT_FSIZE, plan.rlimit_fsize)?;

    // Filesystem isolation via Landlock (also sets NO_NEW_PRIVS itself).
    if plan.landlock {
        let mut write_roots = vec![plan.exec_root.clone()];
        write_roots.extend(plan.extra_rw.iter().cloned());
        let read_roots: Vec<std::path::PathBuf> = plan
            .system_ro
            .iter()
            .map(std::path::PathBuf::from)
            .collect();
        crate::sandbox::linux::landlock::apply_policy(
            &write_roots,
            &read_roots,
            plan.strip_read_on_write,
        )
        .map_err(|e| std::io::Error::other(format!("{e:?}")))?;
    } else {
        // SAFETY: scalar-only prctl; required before any seccomp filter.
        if unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) } != 0 {
            return Err(std::io::Error::last_os_error());
        }
    }

    // Seccomp: network socket policy plus the hardening denylist.
    // `AgentMin` additionally denies `chroot(2)` (absent from the Default
    // denylist); the syscall-escape tests require it, so install AgentMin.
    if plan.harden_syscalls {
        let socket_policy = if plan.net_deny {
            crate::sandbox::linux::seccomp_netblock::SocketPolicy::UnixOnly
        } else {
            crate::sandbox::linux::seccomp_netblock::SocketPolicy::UnixAndIp
        };
        crate::sandbox::linux::seccomp_netblock::install_for_profile(
            socket_policy,
            crate::policy::SeccompProfile::AgentMin,
        )
        .map_err(|e| std::io::Error::other(format!("{e:?}")))?;
    }
    Ok(())
}

/// Lower one rlimit (soft and hard together) when configured.
#[cfg(target_os = "linux")]
fn set_rlimit_if_some(
    resource: libc::__rlimit_resource_t,
    value: Option<u64>,
) -> std::io::Result<()> {
    let Some(value) = value else {
        return Ok(());
    };
    let limit = libc::rlimit {
        rlim_cur: value as libc::rlim_t,
        rlim_max: value as libc::rlim_t,
    };
    // SAFETY: fixed resource constant + valid local rlimit struct.
    if unsafe { libc::setrlimit(resource, &limit) } != 0 {
        return Err(std::io::Error::last_os_error());
    }
    Ok(())
}

/// Read `/proc/<pid>/status` + `/proc/<pid>/limits` + cgroup v2 controllers + own pgid/sub-reaper
/// state with a bounded wait while the child is alive.
#[cfg(target_os = "linux")]
fn verify_child_host_linux(
    pid: u32,
    expected: Option<&ExpectedLimits>,
) -> super::sandbox_backend::HostVerification {
    use super::sandbox_backend::HostVerification;
    use std::time::{Duration, Instant};
    let deadline = Instant::now() + Duration::from_secs(2);
    let mut out = HostVerification::none();
    loop {
        let status = read_proc_file(pid, "status");
        if let Some(body) = status.as_deref() {
            if proc_field_is(body, "Seccomp:", "2") {
                out.seccomp_filter = true;
            }
            if proc_field_is(body, "NoNewPrivs:", "1") {
                out.no_new_privs = true;
            }
        }
        // SAFETY: scalar getpgid on the (possibly reaped) child pid.
        let pgid = unsafe { libc::getpgid(pid as libc::pid_t) };
        if pgid == pid as libc::pid_t {
            out.pgroup_separate = true;
        }
        if let (Ok(child_netns), Ok(host_netns)) = (
            std::fs::read_link(format!("/proc/{pid}/ns/net")),
            std::fs::read_link("/proc/self/ns/net"),
        ) {
            if child_netns != host_netns {
                out.netns_isolated = true;
            }
        }
        if let Some(limits) = read_proc_file(pid, "limits").as_deref() {
            if let Some(exp) = expected {
                if let Some(val) = exp.rlimit_as {
                    out.rlimit_as_ok = limits_field_is(limits, "Max address space", val);
                } else if limits_field_is(limits, "Max address space", DEFAULT_RLIMIT_AS_BYTES) {
                    out.rlimit_as_ok = true;
                }
                if let Some(val) = exp.rlimit_nproc {
                    out.rlimit_nproc_ok = limits_field_is(limits, "Max processes", val);
                } else if limits_field_is(limits, "Max processes", DEFAULT_RLIMIT_NPROC) {
                    out.rlimit_nproc_ok = true;
                }
                if let Some(val) = exp.rlimit_cpu {
                    out.rlimit_cpu_ok = limits_field_is(limits, "Max cpu time", val);
                } else if limits_field_is(limits, "Max cpu time", DEFAULT_RLIMIT_CPU_SECS) {
                    out.rlimit_cpu_ok = true;
                }
                if let Some(val) = exp.rlimit_fsize {
                    out.rlimit_fsize_ok = limits_field_is(limits, "Max file size", val);
                } else if limits_field_is(limits, "Max file size", DEFAULT_RLIMIT_FSIZE_BYTES) {
                    out.rlimit_fsize_ok = true;
                }
            } else {
                if limits_field_is(limits, "Max address space", DEFAULT_RLIMIT_AS_BYTES) {
                    out.rlimit_as_ok = true;
                } else if let Some((soft, hard)) =
                    parse_proc_limits_value(limits, "Max address space")
                {
                    if soft == hard && soft > 0 {
                        out.rlimit_as_ok = true;
                    }
                }
                if limits_field_is(limits, "Max processes", DEFAULT_RLIMIT_NPROC) {
                    out.rlimit_nproc_ok = true;
                } else if let Some((soft, hard)) = parse_proc_limits_value(limits, "Max processes")
                {
                    if soft == hard && soft > 0 {
                        out.rlimit_nproc_ok = true;
                    }
                }
                if limits_field_is(limits, "Max cpu time", DEFAULT_RLIMIT_CPU_SECS) {
                    out.rlimit_cpu_ok = true;
                } else if let Some((soft, hard)) = parse_proc_limits_value(limits, "Max cpu time") {
                    if soft == hard && soft > 0 {
                        out.rlimit_cpu_ok = true;
                    }
                }
                if limits_field_is(limits, "Max file size", DEFAULT_RLIMIT_FSIZE_BYTES) {
                    out.rlimit_fsize_ok = true;
                } else if let Some((soft, hard)) = parse_proc_limits_value(limits, "Max file size")
                {
                    if soft == hard && soft > 0 {
                        out.rlimit_fsize_ok = true;
                    }
                }
            }
        }

        // Host inspection of cgroup v2 controller files (`memory.max`, `pids.max`, `cpu.max`):
        if let Some(cg) = inspect_child_cgroup(pid) {
            if let Some(exp) = expected {
                if let Some(want_mem) = &exp.cgroup_memory_max {
                    if let Some(actual) = &cg.memory_max {
                        out.cgroup_memory_ok = cgroup_memory_matches(actual, want_mem);
                    }
                } else if let Some(actual) = &cg.memory_max {
                    if actual != "max" && !actual.is_empty() {
                        out.cgroup_memory_ok = true;
                    }
                }
                if let Some(want_pids) = &exp.cgroup_pids_max {
                    if let Some(actual) = &cg.pids_max {
                        out.cgroup_pids_ok = cgroup_pids_matches(actual, want_pids);
                    }
                } else if let Some(actual) = &cg.pids_max {
                    if actual != "max" && !actual.is_empty() {
                        out.cgroup_pids_ok = true;
                    }
                }
                if let Some(want_cpu) = &exp.cgroup_cpu_max {
                    if let Some(actual) = &cg.cpu_max {
                        out.cgroup_cpu_ok = cgroup_cpu_matches(actual, want_cpu);
                    }
                } else if let Some(actual) = &cg.cpu_max {
                    if actual != "max 100000" && !actual.starts_with("max") && !actual.is_empty() {
                        out.cgroup_cpu_ok = true;
                    }
                }
            } else {
                if let Some(actual) = &cg.memory_max {
                    if actual != "max" && !actual.is_empty() {
                        out.cgroup_memory_ok = true;
                    }
                }
                if let Some(actual) = &cg.pids_max {
                    if actual != "max" && !actual.is_empty() {
                        out.cgroup_pids_ok = true;
                    }
                }
                if let Some(actual) = &cg.cpu_max {
                    if actual != "max 100000" && !actual.starts_with("max") && !actual.is_empty() {
                        out.cgroup_cpu_ok = true;
                    }
                }
            }
        }

        // SAFETY: scalar prctl query on our own process (see `is_child_subreaper`).
        out.subreaper_ok = is_child_subreaper();
        // A zombie's observable flags are frozen: only we can reap it, and
        // we reap after verification, so further polling burns the deadline
        // with identical output. Return immediately (Stage 3C: production
        // fast-path commands otherwise pay the full 2s here whenever their
        // policy rlimits legitimately differ from the harness ceilings —
        // caps honestly stay `Enforced`, never falsely `Verified`).
        let zombie = match status.as_deref() {
            Some(body) => pid_is_zombie(body),
            None => false,
        };
        if out.all_observed() || Instant::now() >= deadline || !pid_alive(pid) || zombie {
            return out;
        }
        std::thread::sleep(Duration::from_millis(25));
    }
}

/// Nonce-targeted orphan sweep (see [`sweep_tree_by_nonce`]).
///
/// Scans the ENTIRE `/proc` process set on every pass and selects solely by
/// the exact run nonce in `/proc/<pid>/environ` (never by ancestry: double
/// fork, `setsid` and multi-level chains all keep the inherited environ).
/// Kill pass -> nonblocking reap -> short poll -> rescan, until the final
/// scan finds zero nonce bearers (`clean=true`) or the budget expires.
/// Read races (`ENOENT`/`ESRCH`) and zombies are tolerated; a same-UID live
/// process with an unreadable environ is `blind` (fail-closed). Foreign-UID
/// processes can never carry our nonce (children inherit our UID and
/// `NO_NEW_PRIVS` blocks transitions), so they are skipped without blinding.
#[cfg(target_os = "linux")]
fn sweep_tree_by_nonce_linux(nonce: &str, root_pid: u32) -> SweepOutcome {
    use std::time::{Duration, Instant};
    // SAFETY: scalar prctl query on our own process (see `is_child_subreaper`).
    let subreaper = is_child_subreaper();
    let mut outcome = SweepOutcome {
        clean: false,
        killed: 0,
        residual: Vec::new(),
        subreaper,
        blind: false,
    };
    // Without our sub-reaper flag, escapers reparent to init and this scan
    // is blind — report not-clean (fail-closed) instead of a false clean.
    if !subreaper {
        outcome.blind = true;
        return outcome;
    }
    // SAFETY: scalar getpid/geteuid.
    let me = unsafe { libc::getpid() } as u32;
    let me_uid = unsafe { libc::geteuid() };
    let needle = nonce.as_bytes();
    let deadline = Instant::now() + Duration::from_millis(SWEEP_BUDGET_MS);
    loop {
        let (matched, blind) = scan_nonce_pids(needle, root_pid, me, me_uid);
        if blind {
            outcome.blind = true;
        }
        if matched.is_empty() {
            if !outcome.blind {
                // Final complete scan already shows zero nonce bearers and no blind spots.
                outcome.clean = true;
            }
            return outcome;
        }
        for pid in &matched {
            // SAFETY: SIGKILL only to a nonce-matching pid of this run.
            if unsafe { libc::kill(*pid, libc::SIGKILL) } == 0 {
                outcome.killed += 1;
            }
            let mut status = 0i32;
            // SAFETY: non-blocking waitpid (reaps only our children).
            unsafe { libc::waitpid(*pid, &mut status, libc::WNOHANG) };
        }
        if Instant::now() >= deadline {
            if blind {
                outcome.blind = true;
            }
            outcome.residual = last_nonce_pids(nonce, root_pid, me);
            return outcome;
        }
        std::thread::sleep(Duration::from_millis(10));
    }
}

/// One full `/proc` scan for pids whose environ carries this run's nonce.
///
/// Returns `(matched, blind)`. `blind=true` means one of OUR live processes
/// (direct or sub-reaper-adopted child, `PPid == me`) had an unreadable
/// environ — the scan cannot claim clean. Foreign same-UID processes (other
/// test runs' trees: Yama may deny their environ) are skipped without
/// blinding: any live nonce-bearer ends up reparented to us once its parent
/// dies, so the next pass observes it as our child. Only nonce-matching pids
/// are ever signalled by the caller.
#[cfg(target_os = "linux")]
fn scan_nonce_pids(needle: &[u8], root_pid: u32, me: u32, me_uid: libc::uid_t) -> (Vec<i32>, bool) {
    let mut matched = Vec::new();
    let mut blind = false;
    let Ok(entries) = std::fs::read_dir("/proc") else {
        // Cannot observe at all: fail closed, never a false clean.
        return (matched, true);
    };
    for entry in entries.flatten() {
        let Ok(name) = entry.file_name().into_string() else {
            continue;
        };
        let Ok(pid) = name.parse::<i32>() else {
            continue;
        };
        if pid <= 0 || pid as u32 == root_pid || pid as u32 == me {
            continue;
        }
        let status = match std::fs::read_to_string(format!("/proc/{pid}/status")) {
            Ok(s) => s,
            Err(e)
                if e.raw_os_error() == Some(libc::ENOENT)
                    || e.raw_os_error() == Some(libc::ESRCH) =>
            {
                continue;
            }
            Err(_) => continue,
        };
        // Foreign-UID processes can never be our descendants (same UID is
        // inherited, transitions are blocked by NO_NEW_PRIVS): skip without
        // blinding, so root daemons never fail the sweep. Unparsable Uid
        // stays conservative and proceeds to the environ attempt below.
        if let Some(uid) = status_uid(&status) {
            if uid != me_uid {
                continue;
            }
        }
        // Environ is unreadable for zombies or mid-exit races (ENOENT/ESRCH
        // — the process is going away): never blocking clean. Unconfirmed
        // zombies must not be reaped here without an exact nonce match,
        // otherwise we race with concurrent SandboxHandles in this process
        // and steal their exit status (turning exit_code into Some(-1)).
        // A hard read error (EACCES/hidepid, e.g. Yama scope) blinds only
        // for OUR live children — reparenting delivers every orphan to us,
        // so a foreign tree can never hide our nonce.
        let env = match std::fs::read(format!("/proc/{pid}/environ")) {
            Ok(env) => env,
            Err(e)
                if e.raw_os_error() == Some(libc::ENOENT)
                    || e.raw_os_error() == Some(libc::ESRCH) =>
            {
                continue;
            }
            Err(_) => {
                if pid_is_zombie(&status) || !pid_alive(pid as u32) {
                    continue;
                }
                // Process could have exited or transitioned to zombie right after reading /proc/{pid}/status
                if let Ok(latest_status) = std::fs::read_to_string(format!("/proc/{pid}/status")) {
                    if pid_is_zombie(&latest_status) {
                        continue;
                    }
                } else {
                    continue;
                }
                if crate::sandbox::linux::proctrack::ppid_from_status(&status) == Some(me) {
                    blind = true;
                }
                continue;
            }
        };
        if contains_slice(&env, needle) {
            matched.push(pid);
        } else if (env.is_empty() || !contains_slice(&env, needle))
            && pid_alive(pid as u32)
            && !pid_is_zombie(&status)
            && crate::sandbox::linux::proctrack::ppid_from_status(&status) == Some(me)
        {
            let my_sid = crate::sandbox::linux::proctrack::session_of(0);
            let their_sid = crate::sandbox::linux::proctrack::session_of(pid);
            if match (my_sid, their_sid) {
                (Some(mine), Some(theirs)) => mine != theirs,
                _ => false,
            } {
                blind = true;
                matched.push(pid);
            }
        }
    }
    (matched, blind)
}

/// Final best-effort listing of surviving nonce-matching pids for the
/// diagnostic string (no signalling here).
#[cfg(target_os = "linux")]
fn last_nonce_pids(nonce: &str, root_pid: u32, me: u32) -> Vec<i32> {
    let mut out = Vec::new();
    let needle = nonce.as_bytes();
    if let Ok(entries) = std::fs::read_dir("/proc") {
        for entry in entries.flatten() {
            let Ok(name) = entry.file_name().into_string() else {
                continue;
            };
            let Ok(pid) = name.parse::<i32>() else {
                continue;
            };
            if pid <= 0 || pid as u32 == root_pid || pid as u32 == me {
                continue;
            }
            let Ok(env) = std::fs::read(format!("/proc/{pid}/environ")) else {
                continue;
            };
            if contains_slice(&env, needle) {
                out.push(pid);
            }
        }
    }
    out.sort_unstable();
    out.truncate(8);
    out
}

/// True when a `/proc/<pid>/status` body describes a zombie or dead process.
#[cfg(target_os = "linux")]
fn pid_is_zombie(status: &str) -> bool {
    for line in status.lines() {
        if let Some(rest) = line.trim_start().strip_prefix("State:") {
            let s = rest.trim_start();
            return s.starts_with('Z') || s.starts_with('X');
        }
    }
    false
}

/// True while `kill(pid, 0)` succeeds (process exists and we may signal it).
#[cfg(target_os = "linux")]
fn pid_alive(pid: u32) -> bool {
    // SAFETY: signal 0 performs no delivery; ESRCH means gone.
    unsafe { libc::kill(pid as libc::pid_t, 0) == 0 }
}

#[cfg(target_os = "linux")]
fn read_proc_file(pid: u32, file: &str) -> Option<String> {
    std::fs::read_to_string(format!("/proc/{pid}/{file}")).ok()
}

// ---------------------------------------------------------------------------
// Pure parsers (host-side string matching; unit-tested on every platform)
// ---------------------------------------------------------------------------

/// True when a `/proc/<pid>/status` field has exactly the expected value
/// (`"Seccomp:\t2"` style; any whitespace shape accepted).
pub fn proc_field_is(status_body: &str, field: &str, expected: &str) -> bool {
    for line in status_body.lines() {
        if let Some(rest) = line.trim_start().strip_prefix(field) {
            return rest.trim() == expected;
        }
    }
    false
}

/// True when a `/proc/<pid>/limits` row for `row` carries `expected` in
/// both the soft and hard columns. Rows look like
/// `Max cpu time   5   5   seconds` (units trailing) or `unlimited`.
pub fn limits_field_is(limits_body: &str, row: &str, expected: u64) -> bool {
    for line in limits_body.lines() {
        if let Some(idx) = line.find(row) {
            let after = line[idx + row.len()..].trim_start();
            let mut cols = after.split_whitespace();
            let soft = cols.next().unwrap_or("");
            let hard = cols.next().unwrap_or("");
            let want = expected.to_string();
            return soft == want && hard == want;
        }
    }
    false
}

/// Parse soft and hard limits from a `/proc/<pid>/limits` row.
/// Returns `None` if either column is `unlimited` or cannot be parsed.
pub fn parse_proc_limits_value(limits_body: &str, row: &str) -> Option<(u64, u64)> {
    for line in limits_body.lines() {
        if let Some(idx) = line.find(row) {
            let after = line[idx + row.len()..].trim_start();
            let mut cols = after.split_whitespace();
            let soft_str = cols.next()?;
            let hard_str = cols.next()?;
            if soft_str.eq_ignore_ascii_case("unlimited")
                || hard_str.eq_ignore_ascii_case("unlimited")
            {
                return None;
            }
            let soft = soft_str.parse::<u64>().ok()?;
            let hard = hard_str.parse::<u64>().ok()?;
            return Some((soft, hard));
        }
    }
    None
}

/// Resolve the cgroup v2 directory for a given process PID.
pub fn child_cgroup_dir(pid: u32) -> Option<std::path::PathBuf> {
    let content = std::fs::read_to_string(format!("/proc/{pid}/cgroup")).ok()?;
    for line in content.lines() {
        if let Some(path_part) = line.strip_prefix("0::") {
            let rel = path_part.trim().trim_start_matches('/');
            let cgroup_dir = std::path::Path::new("/sys/fs/cgroup").join(rel);
            if cgroup_dir.exists() && cgroup_dir.join("cgroup.procs").exists() {
                return Some(cgroup_dir);
            }
        }
    }
    None
}

/// Host-inspected cgroup v2 controller values for a child process.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CgroupHostInspection {
    pub cgroup_dir: std::path::PathBuf,
    pub pid_in_procs: bool,
    pub memory_max: Option<String>,
    pub pids_max: Option<String>,
    pub cpu_max: Option<String>,
    pub swap_max: Option<String>,
}

/// Inspect cgroup v2 controller files (`memory.max`, `pids.max`, `cpu.max`)
/// and `cgroup.procs` for the child process.
pub fn inspect_child_cgroup(pid: u32) -> Option<CgroupHostInspection> {
    let dir = child_cgroup_dir(pid)?;
    let mut inspection = CgroupHostInspection {
        cgroup_dir: dir.clone(),
        pid_in_procs: false,
        memory_max: None,
        pids_max: None,
        cpu_max: None,
        swap_max: None,
    };
    if let Ok(procs) = std::fs::read_to_string(dir.join("cgroup.procs")) {
        let pid_s = pid.to_string();
        inspection.pid_in_procs = procs.lines().any(|l| l.trim() == pid_s);
    }
    if let Ok(val) = std::fs::read_to_string(dir.join("memory.max")) {
        inspection.memory_max = Some(val.trim().to_string());
    }
    if let Ok(val) = std::fs::read_to_string(dir.join("pids.max")) {
        inspection.pids_max = Some(val.trim().to_string());
    }
    if let Ok(val) = std::fs::read_to_string(dir.join("cpu.max")) {
        inspection.cpu_max = Some(val.trim().to_string());
    }
    if let Ok(val) = std::fs::read_to_string(dir.join("memory.swap.max")) {
        inspection.swap_max = Some(val.trim().to_string());
    }
    Some(inspection)
}

fn parse_memory_bytes(input: &str) -> Option<String> {
    let s = input.trim();
    if s.is_empty() || s.eq_ignore_ascii_case("max") {
        return Some("max".to_string());
    }
    let (num_part, unit_part) = match s.find(|c: char| !c.is_ascii_digit() && c != '.') {
        Some(idx) => (&s[..idx], s[idx..].trim().to_uppercase()),
        None => (s, String::new()),
    };
    let num: f64 = num_part.parse().ok()?;
    let multiplier: f64 = match unit_part.as_str() {
        "" | "B" => 1.0,
        "K" | "KB" | "KIB" => 1024.0,
        "M" | "MB" | "MIB" => 1024.0 * 1024.0,
        "G" | "GB" | "GIB" => 1024.0 * 1024.0 * 1024.0,
        "T" | "TB" | "TIB" => 1024.0 * 1024.0 * 1024.0 * 1024.0,
        _ => return None,
    };
    let bytes = (num * multiplier) as u64;
    Some(bytes.to_string())
}

fn parse_cpu_max(input: &str) -> Option<String> {
    let s = input.trim();
    if s.is_empty() || s.eq_ignore_ascii_case("max") {
        return Some("max 100000".to_string());
    }
    if s.ends_with('%') {
        let pct_str = s.trim_end_matches('%').trim();
        let pct: f64 = pct_str.parse().ok()?;
        let period = 100_000u64;
        let quota = ((pct / 100.0) * period as f64) as u64;
        return Some(format!("{quota} {period}"));
    }
    if s.contains(' ') {
        return Some(s.to_string());
    }
    if let Ok(quota) = s.parse::<u64>() {
        return Some(format!("{quota} 100000"));
    }
    None
}

pub fn cgroup_memory_matches(actual_bytes_str: &str, expected: &str) -> bool {
    let actual = actual_bytes_str.trim();
    if actual == expected.trim() {
        return true;
    }
    if let Some(parsed) = parse_memory_bytes(expected) {
        if parsed == actual {
            return true;
        }
    }
    false
}

pub fn cgroup_cpu_matches(actual_cpu_str: &str, expected: &str) -> bool {
    let actual = actual_cpu_str.trim();
    if actual == expected.trim() {
        return true;
    }
    if let Some(parsed) = parse_cpu_max(expected) {
        if parsed == actual {
            return true;
        }
    }
    false
}

pub fn cgroup_pids_matches(actual_pids_str: &str, expected: &str) -> bool {
    actual_pids_str.trim() == expected.trim()
}

/// Byte-substring search (haystack may be NUL-separated, e.g. `environ`).
pub fn contains_slice(haystack: &[u8], needle: &[u8]) -> bool {
    if needle.is_empty() || needle.len() > haystack.len() {
        return false;
    }
    haystack
        .windows(needle.len())
        .any(|window| window == needle)
}

/// Real UID from a `/proc/<pid>/status` body (`"Uid:\t1000\t1000..."`,
/// first column). `None` when the field is missing or malformed.
pub fn status_uid(status_body: &str) -> Option<u32> {
    for line in status_body.lines() {
        if let Some(rest) = line.trim_start().strip_prefix("Uid:") {
            let first = rest.split_whitespace().next().unwrap_or("");
            return first.parse::<u32>().ok();
        }
    }
    None
}

#[cfg(test)]
mod linux_enforce_tests {
    use super::*;

    #[test]
    fn proc_field_matches_status_shapes() {
        let body = "Name:\tsh\nState:\tS (sleeping)\nSeccomp:\t2\nNoNewPrivs:\t1\n";
        assert!(proc_field_is(body, "Seccomp:", "2"));
        assert!(proc_field_is(body, "NoNewPrivs:", "1"));
        assert!(!proc_field_is(body, "Seccomp:", "0"));
        assert!(!proc_field_is(body, "Missing:", "2"));
        assert!(!proc_field_is("", "Seccomp:", "2"));
    }

    #[test]
    fn limits_field_matches_both_columns() {
        let body = "Limit                     Soft Limit           Hard Limit           Units\n\
            Max cpu time              5                    5                    seconds\n\
            Max file size             67108864             67108864             bytes\n\
            Max processes             128                  128                  processes\n\
            Max address space         268435456            268435456            bytes\n\
            Max open files            1024                 1024                 files\n";
        assert!(limits_field_is(body, "Max cpu time", 5));
        assert!(limits_field_is(body, "Max file size", 67_108_864));
        assert!(limits_field_is(body, "Max processes", 128));
        assert!(limits_field_is(body, "Max address space", 268_435_456));
        assert!(!limits_field_is(body, "Max cpu time", 6));
        assert!(!limits_field_is(body, "Max open files", 512));
        assert!(!limits_field_is(body, "No such row", 0));
    }

    #[test]
    fn limits_field_rejects_unlimited_and_split() {
        let body = "Max cpu time              unlimited            unlimited            seconds\n\
            Max processes             128                  64                   processes\n";
        assert!(!limits_field_is(body, "Max cpu time", 5));
        assert!(!limits_field_is(body, "Max processes", 128));
    }

    #[test]
    fn contains_slice_finds_nonce_in_environ() {
        let env = b"PATH=/bin\x00VETTO_VNG_NONCE=abc123\x00HOME=/x\x00";
        assert!(contains_slice(env, b"abc123"));
        assert!(contains_slice(env, b"VETTO_VNG_NONCE"));
        assert!(!contains_slice(env, b"other"));
        assert!(!contains_slice(env, b""));
        assert!(!contains_slice(b"short", b"much-longer-needle"));
    }

    #[test]
    fn status_uid_parses_first_column() {
        let body = "Name:\tsleep\nState:\tS (sleeping)\nUid:\t1000\t1000\t1000\t1000\n";
        assert_eq!(status_uid(body), Some(1000));
        assert_eq!(status_uid("Uid:\t0\t0\t0\t0\n"), Some(0));
        assert_eq!(status_uid("Name:\tx\nState:\tR (running)\n"), None);
        assert_eq!(status_uid(""), None);
        assert_eq!(status_uid("Uid:\tnot-a-number\n"), None);
    }

    /// The sub-reaper query must not fail with `EFAULT`: the kernel reports
    /// through the out-pointer, so a scalar call form would always read false.
    #[cfg(target_os = "linux")]
    #[test]
    fn subreaper_query_is_deterministic() {
        let a = is_child_subreaper();
        let b = is_child_subreaper();
        assert_eq!(a, b);
    }

    #[test]
    fn parse_proc_limits_value_parses_finite_and_rejects_unlimited() {
        let body = "Limit                     Soft Limit           Hard Limit           Units\n\
            Max cpu time              5                    5                    seconds\n\
            Max file size             unlimited            unlimited            bytes\n\
            Max processes             128                  128                  processes\n";
        assert_eq!(parse_proc_limits_value(body, "Max cpu time"), Some((5, 5)));
        assert_eq!(parse_proc_limits_value(body, "Max file size"), None);
        assert_eq!(
            parse_proc_limits_value(body, "Max processes"),
            Some((128, 128))
        );
        assert_eq!(parse_proc_limits_value(body, "Max memory"), None);
    }

    #[test]
    fn cgroup_matching_handles_units_and_percentages() {
        assert!(cgroup_memory_matches("268435456", "256M"));
        assert!(cgroup_memory_matches("104857600", "100MB"));
        assert!(cgroup_memory_matches("1000", "1000"));
        assert!(!cgroup_memory_matches("268435456", "512M"));

        assert!(cgroup_cpu_matches("50000 100000", "50%"));
        assert!(cgroup_cpu_matches("100000 100000", "100%"));
        assert!(cgroup_cpu_matches("50000 100000", "50000 100000"));
        assert!(!cgroup_cpu_matches("50000 100000", "100%"));

        assert!(cgroup_pids_matches("128", "128"));
        assert!(!cgroup_pids_matches("128", "256"));
    }

    #[test]
    fn expected_limits_from_policy_maps_fields() {
        let mut policy = crate::policy::Policy::default();
        policy.limits.address_space_bytes = Some(268435456);
        policy.limits.processes = Some(128);
        policy.cgroup = Some(crate::policy::CgroupConfig {
            memory_max: Some("256M".to_string()),
            pids_max: Some("128".to_string()),
            swap_max: None,
            cpu_max: Some("50%".to_string()),
        });

        let expected = ExpectedLimits::from_policy(&policy);
        assert_eq!(expected.rlimit_as, Some(268435456));
        assert_eq!(expected.rlimit_nproc, Some(128));
        assert_eq!(expected.cgroup_memory_max.as_deref(), Some("256M"));
        assert_eq!(expected.cgroup_pids_max.as_deref(), Some("128"));
        assert_eq!(expected.cgroup_cpu_max.as_deref(), Some("50%"));
    }
}