vetto 0.2.23

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
//! 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.
pub const SWEEP_BUDGET_MS: u64 = 2_000;

/// 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:
/// 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)
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = pid;
        super::sandbox_backend::HostVerification::none()
    }
}

/// 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, false)
            .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` + 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) -> 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 Some(limits) = read_proc_file(pid, "limits").as_deref() {
            if limits_field_is(limits, "Max address space", DEFAULT_RLIMIT_AS_BYTES) {
                out.rlimit_as_ok = true;
            }
            if limits_field_is(limits, "Max processes", DEFAULT_RLIMIT_NPROC) {
                out.rlimit_nproc_ok = true;
            }
            if limits_field_is(limits, "Max cpu time", DEFAULT_RLIMIT_CPU_SECS) {
                out.rlimit_cpu_ok = true;
            }
            if limits_field_is(limits, "Max file size", DEFAULT_RLIMIT_FSIZE_BYTES) {
                out.rlimit_fsize_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;
            outcome.residual = last_nonce_pids(nonce, root_pid, me);
            return outcome;
        }
        if matched.is_empty() {
            // Final complete scan already shows zero nonce bearers.
            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 {
            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) {
                    continue;
                }
                if crate::sandbox::linux::proctrack::ppid_from_status(&status) == Some(me) {
                    blind = true;
                }
                continue;
            }
        };
        if contains_slice(&env, needle) {
            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.
#[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:") {
            return rest.trim_start().starts_with('Z');
        }
    }
    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
}

/// 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);
    }
}