sbe-core 0.3.0

Core library for sbe — cross-platform sandbox executor for supply chain defense
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
//! Compile a [`SandboxProfile`] into a Landlock [`Ruleset`].
//!
//! All path FDs that the kernel needs are opened in the **parent** here
//! (§6 D2) and packaged in [`CompiledLandlock`]. The `pre_exec` closure
//! issues only the `landlock_restrict_self` syscall — no allocation, no FD
//! opens.
//!
//! The compiler also enforces two backend-time lints required by §8:
//! - `allow_exec` subpath entries that overlap privilege-escalation binaries (sudo, su, …) are
//!   rejected.
//! - `deny_read` is sealed as a forbidden list — when later code tries to broaden `allow_read`, an
//!   overlap with `forbidden_reads` is rejected.

use std::{
    collections::BTreeSet,
    path::{Path, PathBuf},
};

use landlock::{
    ABI, Access, AccessFs, AccessNet, BitFlags, CompatLevel, Compatible, NetPort, PathBeneath,
    PathFd, Ruleset, RulesetAttr, RulesetCreated, RulesetCreatedAttr,
};

use crate::{
    config::SandboxPath,
    error::CoreError,
    profile::SandboxProfile,
    sandbox::{
        BackendOptions,
        linux::probe::{LandlockAbi, ProbeResult},
    },
};

/// Curated baseline read-allowlist anchors. The Linux profile YAML extends
/// this with per-OS additions; here we keep the system-essentials list that
/// the orchestrator always grants, regardless of ecosystem.
///
/// Listed paths are read-only — Landlock writes are still gated by
/// `allow_write`.
pub const READ_ALLOWLIST_ANCHORS: &[&str] = &[
    // Dynamic linker, NSS, system config
    "/etc",
    "/lib",
    "/lib32",
    "/lib64",
    "/usr",
    "/proc",
    "/sys",
    // Temp
    "/tmp",
    "/var/tmp",
    // Devices we explicitly allow
    "/dev",
    // systemd-resolved stub on Ubuntu/Debian/Fedora: /etc/resolv.conf is a
    // symlink to /run/systemd/resolve/stub-resolv.conf. Landlock follows
    // symlinks to the canonical path, so the resolver can't read the
    // nameserver list without granting read on the symlink target.
    //
    // We name the SPECIFIC files used by the libc resolver rather than the
    // whole directory. The directory also contains
    // `/run/systemd/resolve/io.systemd.Resolve` — a varlink Unix-domain
    // socket. Landlock pre-ABI v6 does NOT gate UDS connect by path-based
    // access, so granting read on the directory enables a build script to
    // connect to the varlink endpoint and ask systemd-resolved to perform
    // arbitrary DNS lookups, bypassing the HTTP CONNECT proxy's domain
    // allowlist. Narrow to the two read-only stub files.
    "/run/systemd/resolve/stub-resolv.conf",
    "/run/systemd/resolve/resolv.conf",
];

/// Baseline writable paths injected into every Linux ruleset.
///
/// Matches the macOS SBPL writer's `/private/tmp` / `/private/var/folders`
/// injection: build toolchains (cc, ld, cargo) need to drop temp files in
/// `/tmp` or `/var/tmp`, and a sandbox that allows execution but not
/// temp-file creation breaks almost every compiler. `/dev/null` and
/// `/dev/zero` are routinely targeted by `Stdio::null()` in build scripts.
const BASELINE_WRITE_PATHS: &[&str] = &["/tmp", "/var/tmp", "/dev/null", "/dev/zero", "/dev/shm"];

/// Privilege-escalation binaries that must never appear under an
/// `allow_exec` subpath. The lint refuses to build the ruleset if a
/// user-supplied profile would re-enable any of these via a directory rule.
const PRIVILEGE_ESCALATION_BINARIES: &[&str] = &[
    // Direct UID change
    "/usr/bin/sudo",
    "/bin/sudo",
    "/usr/bin/su",
    "/bin/su",
    "/usr/bin/runuser",
    "/usr/sbin/runuser",
    "/usr/bin/gosu",
    "/usr/local/bin/gosu",
    "/usr/bin/doas",
    "/usr/local/bin/doas",
    "/usr/bin/pkexec",
    // Account / shell modification
    "/usr/bin/chsh",
    "/usr/bin/chfn",
    "/usr/bin/newgrp",
    "/usr/bin/sg",
    "/usr/bin/passwd",
    "/usr/bin/gpasswd",
    // Capability / namespace manipulation (NNP defangs setuid but some
    // of these are file-cap-based and can still raise privs).
    "/usr/bin/capsh",
    "/usr/sbin/capsh",
    "/usr/bin/setpriv",
    "/usr/bin/nsenter",
    "/usr/bin/unshare",
    "/usr/sbin/unshare",
    // systemd / DBus-mediated escalation
    "/usr/bin/systemd-run",
    "/usr/bin/machinectl",
    "/usr/bin/pkttyagent",
    "/usr/bin/dbus-launch",
    // Filesystem mount manipulation
    "/usr/bin/mount",
    "/usr/bin/umount",
    "/bin/mount",
    "/bin/umount",
    "/usr/bin/fusermount",
    "/usr/bin/fusermount3",
];

/// FS read access flags applied to the curated read allowlist.
fn read_access(abi: ABI) -> BitFlags<AccessFs> {
    AccessFs::from_read(abi)
}

/// FS write access flags applied to `allow_write`.
fn write_access(abi: ABI) -> BitFlags<AccessFs> {
    // From_all includes read+write+exec+make_*+ioctl_dev+truncate; sufficient
    // for an unrestricted "this directory tree is owned by the build" rule.
    AccessFs::from_all(abi)
}

/// FS execute access flags applied to `allow_exec`.
fn exec_access(abi: ABI) -> BitFlags<AccessFs> {
    BitFlags::from(AccessFs::Execute) | AccessFs::from_read(abi)
}

fn highest_abi(probe: &ProbeResult) -> ABI {
    // Land on the highest ABI the running kernel actually supports; the
    // `landlock` crate uses CompatLevel::BestEffort below to silently elide
    // bits the kernel doesn't recognise.
    match probe.abi {
        LandlockAbi::Unsupported => ABI::V1,
        LandlockAbi::V1 => ABI::V1,
        LandlockAbi::V2 => ABI::V2,
        LandlockAbi::V3 => ABI::V3,
        LandlockAbi::V4 => ABI::V4,
        LandlockAbi::V5 => ABI::V5,
        LandlockAbi::V6 => ABI::V6,
    }
}

/// A ready-to-apply Landlock ruleset. Built in the parent; the wrapped
/// [`RulesetCreated`] holds all preopened path FDs internally.
pub struct CompiledLandlock {
    /// `restrict_self` consumes this in the child.
    pub ruleset: RulesetCreated,
}

impl std::fmt::Debug for CompiledLandlock {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CompiledLandlock").finish_non_exhaustive()
    }
}

/// Compile the profile and return either a [`CompiledLandlock`] or an
/// error explaining which lint/probe step failed.
pub fn compile(
    profile: &SandboxProfile,
    proxy_port: Option<u16>,
    probe: &ProbeResult,
    options: BackendOptions,
) -> Result<CompiledLandlock, CoreError> {
    if options.allow_degraded {
        // §13 D1: --allow-degraded is a single flag that bypasses
        // *three* unrelated checks (priv-esc subpath lint, denyRead
        // forbidden-list seal, ABI-v4 net-filter gate). Surface every
        // bypass explicitly so users can't accidentally lose unrelated
        // defenses while reaching for the flag to fix a kernel-version
        // problem.
        tracing::warn!(
            "--allow-degraded ACTIVE: the following Linux sandbox checks are DISABLED for this \
             run: (1) privilege-escalation subpath lint (allowExec subpaths can include \
             sudo/su/pkexec/etc.); (2) denyRead forbidden-list seal \
             (allowRead/allowWrite/allowExec may overlap denyRead paths); (3) \
             refuse-on-missing-Landlock-ABI-v4 (kernel may run without per-port TCP filter). \
             Re-run without --allow-degraded for full enforcement."
        );
    }

    // 1. Lints.
    lint_allow_exec_for_priv_escalation(profile, options)?;
    let forbidden_reads = build_forbidden_reads(profile)?;
    lint_forbidden_reads_against_grants(profile, &forbidden_reads, options)?;

    let abi = highest_abi(probe);
    let ruleset = Ruleset::default()
        .set_compatibility(CompatLevel::BestEffort)
        .handle_access(AccessFs::from_all(abi))?;
    let ruleset = if probe.abi.supports_net_port_filter() && !profile.allow_all_network {
        ruleset.handle_access(AccessNet::ConnectTcp)?
    } else {
        ruleset
    };

    // `set_no_new_privs(false)` here because the pre_exec closure issues the
    // prctl explicitly. Calling it twice is harmless but contradicts the §6
    // invariant that the closure performs exactly the documented syscalls.
    let mut created = ruleset.create()?.set_no_new_privs(false);

    // Read allowlist. Per-entry symlink policy via `symlink_policy_for`:
    // root-owned system paths can be symlinks (usr-merge), user paths
    // cannot (TOCTOU attack vector).
    let baseline_reads: Vec<PathBuf> = READ_ALLOWLIST_ANCHORS.iter().map(PathBuf::from).collect();
    for path in &baseline_reads {
        let policy = symlink_policy_for(path);
        created = add_path_rules(
            created,
            std::slice::from_ref(path),
            read_access(abi),
            policy,
        )?;
    }
    for sp in &profile.allow_read {
        let policy = symlink_policy_for(&sp.path);
        created = add_path_rules(
            created,
            std::slice::from_ref(&sp.path),
            read_access(abi),
            policy,
        )?;
    }

    // Write allowlist: ensure each writable directory exists before opening
    // an FD — Landlock can't grant a rule on a non-existent path, and
    // tools like npm/cargo expect their cache dirs to be writable
    // even on first invocation. chmod 0700 keeps $HOME caches private.
    let user_writes: Vec<PathBuf> = profile
        .allow_write
        .iter()
        .map(|sp| sp.path.clone())
        .collect();
    let baseline_writes: Vec<PathBuf> = BASELINE_WRITE_PATHS.iter().map(PathBuf::from).collect();
    let all_writes: Vec<PathBuf> = user_writes
        .iter()
        .chain(baseline_writes.iter())
        .cloned()
        .collect();
    ensure_writable_dirs(&all_writes);
    for path in &all_writes {
        let policy = symlink_policy_for(path);
        created = add_path_rules(
            created,
            std::slice::from_ref(path),
            write_access(abi),
            policy,
        )?;
    }

    // Exec allowlist (read+exec); covers shared libraries too. Per-entry
    // policy: Follow for root-owned system paths (/lib, /usr/, /bin, …)
    // because those are symlinks on usr-merge distros and only root can
    // tamper with them; Refuse for anything else (notably $HOME-relative
    // entries like ~/.cargo/bin/, ~/.nvm/) because a hostile earlier
    // build can plant a symlink there.
    for sp in &profile.allow_exec {
        let policy = symlink_policy_for(&sp.path);
        created = add_path_rules(
            created,
            std::slice::from_ref(&sp.path),
            exec_access(abi),
            policy,
        )?;
    }

    // Net rules — only on v4+. Loopback (proxy) or :443 fallback.
    if probe.abi.supports_net_port_filter() && !profile.allow_all_network {
        if let Some(port) = proxy_port {
            created = created.add_rule(NetPort::new(port, AccessNet::ConnectTcp))?;
        } else if !profile.enable_proxy {
            created = created.add_rule(NetPort::new(443, AccessNet::ConnectTcp))?;
        }
    }

    Ok(CompiledLandlock { ruleset: created })
}

/// Per-call policy for symlinked allowlist entries. Baseline anchors
/// (`/lib`, `/usr/bin`, `/tmp`, …) are symlinks on usr-merge distros and
/// sbe ships the canonical strings — they're trusted to point where
/// they appear to point. User-derived entries (per-ecosystem additions
/// plus `.sbe.yaml` overrides plus CLI flags) are untrusted: an earlier
/// hostile build can plant `~/.npm → ~/.ssh` to redirect the next
/// Landlock grant.
#[derive(Debug, Clone, Copy)]
enum SymlinkPolicy {
    /// Trust the symlink (used for baseline anchors only).
    Follow,
    /// Refuse with a ProfileLint error.
    Refuse,
}

fn add_path_rules(
    mut created: RulesetCreated,
    paths: &[PathBuf],
    access: BitFlags<AccessFs>,
    policy: SymlinkPolicy,
) -> Result<RulesetCreated, CoreError> {
    for path in paths {
        if matches!(policy, SymlinkPolicy::Refuse) && is_symlink(path) {
            return Err(CoreError::ProfileLint(format!(
                "Landlock allowlist entry '{}' is a symlink. Refusing to open it — a symlink lets \
                 an attacker redirect the grant onto a target of their choosing. Replace the \
                 entry with the canonical target path or remove the symlink before re-running sbe.",
                path.display(),
            )));
        }

        // Skip paths that don't exist on the host: Landlock requires open()
        // on the path, and OpenAt failures here would otherwise abort the
        // whole sandbox. We log via tracing for diagnostics.
        let fd = match PathFd::new(path) {
            Ok(fd) => fd,
            Err(e) => {
                tracing::debug!(path = %path.display(), error = %e, "skipping missing landlock path");
                continue;
            }
        };
        created = created.add_rule(PathBeneath::new(fd, access))?;
    }
    Ok(created)
}

#[allow(clippy::disallowed_methods, clippy::disallowed_types)]
fn is_symlink(p: &Path) -> bool {
    std::fs::symlink_metadata(p)
        .map(|m| m.file_type().is_symlink())
        .unwrap_or(false)
}

/// Hardcoded list of root-owned filesystem roots where symlinks are
/// considered safe — only root can modify these on a stock Linux box, so
/// a path under here being a symlink reflects distro layout (usr-merge,
/// /bin → /usr/bin, /lib → /usr/lib, /sbin → /usr/sbin), not an attack.
///
/// Any path NOT under one of these prefixes is assumed user-writable
/// (notably $HOME-relative paths from ecosystem defaults like
/// ~/.cargo/bin/) and gets [`SymlinkPolicy::Refuse`].
const ROOT_TRUSTED_PREFIXES: &[&str] = &[
    "/bin",
    "/sbin",
    "/lib",
    "/lib32",
    "/lib64",
    "/usr",
    "/etc",
    "/proc",
    "/sys",
    "/dev",
    "/tmp",
    "/var/tmp",
    "/var/log",
    "/var/cache",
    "/var/lib",
    "/var/run",
    "/run",
    "/opt",
    "/boot",
    "/srv",
];

fn symlink_policy_for(p: &Path) -> SymlinkPolicy {
    if ROOT_TRUSTED_PREFIXES
        .iter()
        .any(|root| p == Path::new(root) || p.starts_with(root))
    {
        SymlinkPolicy::Follow
    } else {
        SymlinkPolicy::Refuse
    }
}

/// Create any missing directories from `allow_write` so Landlock can open
/// an FD on each one. We mode-0700 directories under $HOME to protect
/// secrets; paths outside $HOME (e.g. `/tmp`, `/var/tmp`) are left alone.
///
/// Crucial: we use [`std::fs::symlink_metadata`] (does NOT follow
/// symlinks) rather than `Path::exists` (DOES follow) so a pre-existing
/// symlink like `~/.npm → ~/.ssh` doesn't make us conclude "already
/// there" and silently grant Landlock write on the link target later.
/// If the entry itself is a symlink, we leave it alone — `add_path_rules`
/// will refuse to open it and the build aborts.
#[allow(clippy::disallowed_methods, clippy::disallowed_types)]
fn ensure_writable_dirs(paths: &[PathBuf]) {
    use std::os::unix::fs::PermissionsExt;
    let home = std::env::var_os("HOME").map(PathBuf::from);
    for p in paths {
        // If a real dir already exists at this path, nothing to do.
        // If a symlink exists, do NOT mkdir into it — add_path_rules will
        // reject it.
        match std::fs::symlink_metadata(p) {
            Ok(m) if m.file_type().is_symlink() => {
                tracing::warn!(
                    path = %p.display(),
                    "allow_write entry is a symlink; refusing to materialize. add_path_rules \
                     will reject this entry."
                );
                continue;
            }
            Ok(_) => continue, // real file or dir already exists
            Err(_) => { /* doesn't exist — fall through to mkdir */ }
        }

        // Best-effort recursive create. If any ancestor is a symlink the
        // create can land on an attacker-chosen target — we accept that
        // for the mkdir step but add_path_rules's PathFd::new will still
        // follow the symlink at open time, so the rule itself is what we
        // gate via is_symlink() at the entry level.
        let _ = std::fs::create_dir_all(p);
        if let Some(h) = home.as_ref()
            && p.starts_with(h)
            && let Ok(meta) = std::fs::symlink_metadata(p)
            && !meta.file_type().is_symlink()
            && meta.file_type().is_dir()
        {
            let mut perms = meta.permissions();
            perms.set_mode(0o700);
            let _ = std::fs::set_permissions(p, perms);
        }
    }
}

fn build_forbidden_reads(profile: &SandboxProfile) -> Result<BTreeSet<PathBuf>, CoreError> {
    let mut set = BTreeSet::new();
    for sp in &profile.deny_read {
        set.insert(sp.path.clone());
    }
    Ok(set)
}

/// Reject any **user-supplied** `allow_write` / `allow_exec` / `allow_read`
/// entry that overlaps a `denyRead` path. Landlock grants on write_access
/// ([`AccessFs::from_all`]) and exec_access
/// ([`AccessFs::Execute`] | [`AccessFs::from_read`]) **both imply read**,
/// so without this lint a user who writes
///   profiles.node.allowWrite: ["~/"]
/// would silently broaden read access onto every denyRead path under `~/`.
///
/// The lint only inspects entries appended *after* the curated defaults
/// (indices `>= first_user_*`). Built-in defaults intentionally overlap
/// denyRead in places where Landlock cannot enforce the denial (e.g.
/// `$PWD/` grants write+read, but `$PWD/.env` is in denyRead so SBPL on
/// macOS can subtract it). Linting the defaults would block every
/// project; the documented gap is in README's
/// "What sbe Does *Not* Protect Against".
fn lint_forbidden_reads_against_grants(
    profile: &SandboxProfile,
    forbidden: &BTreeSet<PathBuf>,
    options: BackendOptions,
) -> Result<(), CoreError> {
    if options.allow_degraded {
        return Ok(());
    }
    let user_slices: [(&str, &[SandboxPath]); 3] = [
        (
            "allowWrite",
            &profile.allow_write[profile.first_user_allow_write..],
        ),
        (
            "allowExec",
            &profile.allow_exec[profile.first_user_allow_exec..],
        ),
        (
            "allowRead",
            &profile.allow_read[profile.first_user_allow_read..],
        ),
    ];
    for (field, paths) in user_slices {
        for sp in paths {
            for f in forbidden {
                if path_is_under(f, &sp.path) {
                    return Err(CoreError::ProfileLint(format!(
                        "denyRead path '{}' is under user-supplied {} entry '{}'. Landlock grants \
                         on allowWrite and allowExec also imply read, so this would silently \
                         expose the denied path. Either narrow the {} entry, remove the denyRead \
                         entry, or pass --allow-degraded if you understand the threat model.",
                        f.display(),
                        field,
                        sp.path.display(),
                        field,
                    )));
                }
            }
        }
    }
    Ok(())
}

fn lint_allow_exec_for_priv_escalation(
    profile: &SandboxProfile,
    options: BackendOptions,
) -> Result<(), CoreError> {
    if options.allow_degraded {
        return Ok(());
    }

    for sp in &profile.allow_exec {
        if !is_subpath(sp) {
            continue;
        }
        for binary in PRIVILEGE_ESCALATION_BINARIES {
            let bin_path = Path::new(binary);
            if path_is_under(bin_path, &sp.path) {
                return Err(CoreError::ProfileLint(format!(
                    "allowExec entry '{}' (directory) covers privilege-escalation binary '{}'. \
                     This would defeat the threat model. Replace with explicit per-binary entries \
                     or pass --allow-degraded if you know what you are doing.",
                    sp.path.display(),
                    binary,
                )));
            }
        }
    }
    Ok(())
}

fn is_subpath(sp: &SandboxPath) -> bool {
    use crate::config::PathKind;
    matches!(sp.kind, PathKind::Subpath)
}

fn path_is_under(candidate: &Path, anchor: &Path) -> bool {
    candidate == anchor || candidate.starts_with(anchor)
}

impl From<landlock::RulesetError> for CoreError {
    fn from(err: landlock::RulesetError) -> Self {
        CoreError::Backend(format!("landlock ruleset error: {err}"))
    }
}

impl From<landlock::AddRulesError> for CoreError {
    fn from(err: landlock::AddRulesError) -> Self {
        CoreError::Backend(format!("landlock add_rules error: {err}"))
    }
}

impl From<landlock::AddRuleError<AccessFs>> for CoreError {
    fn from(err: landlock::AddRuleError<AccessFs>) -> Self {
        CoreError::Backend(format!("landlock add_rule (fs) error: {err}"))
    }
}

impl From<landlock::AddRuleError<AccessNet>> for CoreError {
    fn from(err: landlock::AddRuleError<AccessNet>) -> Self {
        CoreError::Backend(format!("landlock add_rule (net) error: {err}"))
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::*;
    use crate::{
        config::{PathKind, SandboxPath},
        detect::Ecosystem,
    };

    #[test]
    fn test_should_reject_priv_escalation_subpath() {
        let mut profile = SandboxProfile::for_ecosystem(
            Ecosystem::Rust,
            &PathBuf::from("/home/test"),
            &PathBuf::from("/home/test/pwd"),
        );
        profile.allow_exec.push(SandboxPath {
            path: PathBuf::from("/usr/bin"),
            kind: PathKind::Subpath,
        });
        let err =
            lint_allow_exec_for_priv_escalation(&profile, BackendOptions::default()).unwrap_err();
        assert!(format!("{err}").contains("privilege-escalation"));
    }

    #[test]
    fn test_should_pass_priv_escalation_with_allow_degraded() {
        let mut profile = SandboxProfile::for_ecosystem(
            Ecosystem::Rust,
            &PathBuf::from("/home/test"),
            &PathBuf::from("/home/test/pwd"),
        );
        profile.allow_exec.push(SandboxPath {
            path: PathBuf::from("/usr/bin"),
            kind: PathKind::Subpath,
        });
        let res = lint_allow_exec_for_priv_escalation(
            &profile,
            BackendOptions {
                allow_degraded: true,
            },
        );
        assert!(res.is_ok());
    }

    #[test]
    fn test_should_not_lint_baseline_anchor_overlap() {
        // §8: the seal is a "promise to never *silently broaden* a path that
        // overlaps denyRead". Baseline anchors (/etc, /tmp, /lib, …) are
        // documented in the README as readable, so they don't count as a
        // user-broadening event — the lint only inspects per-profile
        // allow_read / allow_write / allow_exec entries.
        let mut profile = SandboxProfile::for_ecosystem(
            Ecosystem::Rust,
            &PathBuf::from("/home/test"),
            &PathBuf::from("/home/test/pwd"),
        );
        profile.deny_read.clear();
        profile.deny_read.push(SandboxPath {
            path: PathBuf::from("/etc/ssh"),
            kind: PathKind::Subpath,
        });
        let forbidden = build_forbidden_reads(&profile).unwrap();
        let lint =
            lint_forbidden_reads_against_grants(&profile, &forbidden, BackendOptions::default());
        assert!(lint.is_ok(), "baseline anchor overlap must not lint");
    }

    #[test]
    fn test_should_reject_forbidden_read_overlap_with_user_allow_read() {
        let mut profile = SandboxProfile::for_ecosystem(
            Ecosystem::Rust,
            &PathBuf::from("/home/test"),
            &PathBuf::from("/home/test/pwd"),
        );
        profile.deny_read.clear();
        profile.deny_read.push(SandboxPath {
            path: PathBuf::from("/home/test/.ssh"),
            kind: PathKind::Subpath,
        });
        // User config tries to grant ~/ as readable — overlaps denyRead.
        profile.allow_read.push(SandboxPath {
            path: PathBuf::from("/home/test"),
            kind: PathKind::Subpath,
        });
        let forbidden = build_forbidden_reads(&profile).unwrap();
        let err =
            lint_forbidden_reads_against_grants(&profile, &forbidden, BackendOptions::default())
                .unwrap_err();
        assert!(format!("{err}").contains("denyRead"));
        assert!(format!("{err}").contains("allowRead"));
    }

    /// C2: a user who broadens read-access via allowWrite (not allowRead)
    /// must still trip the denyRead seal. The Landlock write_access bitmask
    /// includes read_file/read_dir, so without this check the
    /// "sealed forbidden-list" promise is bypassable trivially.
    #[test]
    fn test_should_reject_forbidden_read_overlap_with_allow_write() {
        let mut profile = SandboxProfile::for_ecosystem(
            Ecosystem::Rust,
            &PathBuf::from("/home/test"),
            &PathBuf::from("/home/test/pwd"),
        );
        profile.deny_read.clear();
        profile.deny_read.push(SandboxPath {
            path: PathBuf::from("/home/test/.ssh"),
            kind: PathKind::Subpath,
        });
        profile.allow_write.push(SandboxPath {
            path: PathBuf::from("/home/test"),
            kind: PathKind::Subpath,
        });
        let forbidden = build_forbidden_reads(&profile).unwrap();
        let err =
            lint_forbidden_reads_against_grants(&profile, &forbidden, BackendOptions::default())
                .unwrap_err();
        assert!(format!("{err}").contains("denyRead"));
        assert!(format!("{err}").contains("allowWrite"));
    }

    /// Same path-class attack but via allowExec. Landlock exec_access
    /// includes from_read so a directory under allowExec is read-visible.
    #[test]
    fn test_should_reject_forbidden_read_overlap_with_allow_exec() {
        let mut profile = SandboxProfile::for_ecosystem(
            Ecosystem::Rust,
            &PathBuf::from("/home/test"),
            &PathBuf::from("/home/test/pwd"),
        );
        profile.deny_read.clear();
        profile.deny_read.push(SandboxPath {
            path: PathBuf::from("/home/test/.aws/credentials"),
            kind: PathKind::Literal,
        });
        profile.allow_exec.push(SandboxPath {
            path: PathBuf::from("/home/test/.aws"),
            kind: PathKind::Subpath,
        });
        let forbidden = build_forbidden_reads(&profile).unwrap();
        let err =
            lint_forbidden_reads_against_grants(&profile, &forbidden, BackendOptions::default())
                .unwrap_err();
        assert!(format!("{err}").contains("allowExec"));
    }

    #[test]
    fn test_should_bypass_forbidden_read_overlap_under_allow_degraded() {
        let mut profile = SandboxProfile::for_ecosystem(
            Ecosystem::Rust,
            &PathBuf::from("/home/test"),
            &PathBuf::from("/home/test/pwd"),
        );
        profile.deny_read.clear();
        profile.deny_read.push(SandboxPath {
            path: PathBuf::from("/home/test/.ssh"),
            kind: PathKind::Subpath,
        });
        profile.allow_write.push(SandboxPath {
            path: PathBuf::from("/home/test"),
            kind: PathKind::Subpath,
        });
        let forbidden = build_forbidden_reads(&profile).unwrap();
        let res = lint_forbidden_reads_against_grants(
            &profile,
            &forbidden,
            BackendOptions {
                allow_degraded: true,
            },
        );
        assert!(res.is_ok(), "allow_degraded should bypass the seal lint");
    }
}