Skip to main content

landlock/
lib.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2
3//! Landlock is a security feature available since Linux 5.13.
4//! The goal is to enable to restrict ambient rights
5//! (e.g., global filesystem access)
6//! for a set of processes by creating safe security sandboxes as new security layers
7//! in addition to the existing system-wide access-controls.
8//! This kind of sandbox is expected to help mitigate the security impact of bugs,
9//! unexpected or malicious behaviors in applications.
10//! Landlock empowers any process, including unprivileged ones, to securely restrict themselves.
11//! More information about Landlock can be found in the [official website](https://landlock.io).
12//!
13//! This crate provides a safe abstraction for the Landlock system calls, along with some helpers.
14//!
15//! Minimum Supported Rust Version (MSRV): 1.77
16//!
17//! # Use cases
18//!
19//! This crate is especially useful to protect users' data by sandboxing:
20//! * trusted applications dealing with potentially malicious data
21//!   (e.g., complex file format, network request) that could exploit security vulnerabilities;
22//! * sandbox managers, container runtimes or shells launching untrusted applications.
23//!
24//! # Examples
25//!
26//! A simple example can be found with the [`path_beneath_rules()`] helper.
27//! More complex examples can be found with the [`Ruleset` documentation](Ruleset)
28//! and the [sandboxer example](https://github.com/landlock-lsm/rust-landlock/blob/master/examples/sandboxer.rs).
29//!
30//! # Current limitations
31//!
32//! This crate exposes the Landlock features available as of Linux 7.2
33//! (Landlock [ABI v10](ABI::V10))
34//! and then inherits some [kernel limitations](https://www.kernel.org/doc/html/latest/userspace-api/landlock.html#current-limitations)
35//! that will be addressed with future kernel releases
36//! (e.g., arbitrary mounts are always denied).
37//!
38//! # Compatibility
39//!
40//! Types defined in this crate are designed to enable the strictest Landlock configuration
41//! for the given kernel on which the program runs.
42//! In the default [best-effort](CompatLevel::BestEffort) mode,
43//! [`Ruleset`] will determine compatibility
44//! with the intersection of the currently running kernel's features
45//! and those required by the caller.
46//! This way, callers can distinguish between
47//! Landlock compatibility issues inherent to the current system
48//! (e.g., file names that don't exist)
49//! and misconfiguration that should be fixed in the program
50//! (e.g., empty or inconsistent access rights).
51//! [`RulesetError`] identifies such kind of errors.
52//!
53//! With [`set_compatibility(CompatLevel::BestEffort)`](Compatible::set_compatibility),
54//! users of the crate may mark Landlock features that are deemed required
55//! and other features that may be downgraded to use lower security on systems
56//! where they can't be enforced.
57//! It is discouraged to compare the system's provided [Landlock ABI](ABI) version directly,
58//! as it is difficult to track detailed ABI differences
59//! which are handled thanks to the [`Compatible`] trait.
60//!
61//! To make it easier to migrate to a new version of this library,
62//! we use the builder pattern
63//! and designed objects to require the minimal set of method arguments.
64//! Most `enum` are marked as `non_exhaustive` to enable backward-compatible evolutions.
65//!
66//! ## Test strategy
67//!
68//! Developers should test their sandboxed applications
69//! with a kernel that supports all requested Landlock features
70//! and check that [`RulesetCreated::restrict_self()`] returns a status matching
71//! [`Ok(RestrictionStatus { ruleset: RulesetStatus::FullyEnforced, no_new_privs: true, })`](RestrictionStatus)
72//! to make sure everything works as expected in an enforced sandbox.
73//! Alternatively, using [`set_compatibility(CompatLevel::HardRequirement)`](Compatible::set_compatibility)
74//! will immediately inform about unsupported Landlock features.
75//! These configurations should only depend on the test environment
76//! (e.g. [by checking an environment variable](https://github.com/landlock-lsm/rust-landlock/search?q=LANDLOCK_CRATE_TEST_ABI)).
77//! However, applications should only check that no error is returned (i.e. `Ok(_)`)
78//! and optionally log and inform users that the application is not fully sandboxed
79//! because of missing features from the running kernel.
80//!
81//! ## Audit logging
82//!
83//! Landlock ABI v7 adds control over audit logging through boolean setters, especially
84//! [`log_new_exec()`](RulesetCreatedAttr::log_new_exec)) which is useful (but noisy) for sandboxer
85//! tools.
86//!
87//! ## Multithreaded processes
88//!
89//! By default `landlock_restrict_self()` only restricts the calling thread.
90//! Landlock ABI v8 adds [`all_threads()`](RestrictSelfAttr::all_threads) to
91//! atomically enforce the configuration on every thread of the process.  On
92//! an older kernel this is silently dropped in the default best-effort mode,
93//! leaving sibling and parent threads unrestricted, so multithreaded programs
94//! that need this guarantee should require it (see
95//! [`all_threads()`](RestrictSelfAttr::all_threads)).
96
97#[cfg(test)]
98#[macro_use]
99extern crate lazy_static;
100
101pub use access::{Access, HandledAccess};
102pub use compat::{CompatLevel, Compatible, LandlockStatus, ABI};
103pub use enumflags2::{make_bitflags, BitFlags};
104pub use errata::Erratum;
105pub use errors::{
106    AccessError, AddRuleError, AddRulesError, CompatError, CreateRulesetError, Errno,
107    HandleAccessError, HandleAccessesError, PathBeneathError, PathFdError, RestrictSelfError,
108    RulesetError, ScopeError, SyscallFlagError,
109};
110pub use flags::{RestrictSelfFlag, SyscallFlag};
111pub use fs::{path_beneath_rules, AccessFs, PathBeneath, PathFd};
112pub use net::{AccessNet, NetPort};
113pub use restrict_self::{RestrictSelf, RestrictSelfAttr, RestrictSelfStatus};
114pub use ruleset::{
115    RestrictionStatus, Rule, Ruleset, RulesetAttr, RulesetCreated, RulesetCreatedAttr,
116    RulesetStatus,
117};
118pub use scope::Scope;
119
120use access::PrivateHandledAccess;
121use compat::{CompatResult, CompatState, Compatibility, TailoredCompatLevel, TryCompat};
122use ruleset::PrivateRule;
123
124#[cfg(test)]
125use compat::{can_emulate, get_errno_from_landlock_status};
126#[cfg(test)]
127use errors::TestRulesetError;
128#[cfg(test)]
129use strum::IntoEnumIterator;
130
131mod access;
132mod compat;
133mod errata;
134mod errors;
135mod flags;
136mod fs;
137mod net;
138mod prctl;
139mod restrict_self;
140mod ruleset;
141mod scope;
142mod uapi;
143
144// Makes sure private traits cannot be implemented outside of this crate.
145mod private {
146    pub trait Sealed {}
147
148    impl Sealed for crate::AccessFs {}
149    impl Sealed for crate::AccessNet {}
150    impl Sealed for crate::Scope {}
151    impl Sealed for crate::RestrictSelfFlag {}
152}
153
154#[cfg(test)]
155mod tests {
156    use crate::*;
157    use std::ops::Range;
158
159    // These integration tests exercise the full builder-to-syscall path via
160    // check_ruleset_support().  Other tests in compat.rs and errata.rs make
161    // read-only kernel queries (LandlockStatus::current(), Erratum::current())
162    // but do not create rulesets or restrict threads.  All remaining tests use
163    // Ruleset::from(ABI) to exercise the builder logic and compatibility
164    // engine without kernel interaction.
165
166    // A range means that, after compatibility filtering, every mocked ABI in
167    // the range sends syscall arguments accepted since the range start.
168    trait IntoPartialSupport {
169        fn into_partial_support(self) -> (ABI, Option<ABI>);
170    }
171
172    impl IntoPartialSupport for ABI {
173        fn into_partial_support(self) -> (ABI, Option<ABI>) {
174            (self, None)
175        }
176    }
177
178    impl IntoPartialSupport for Range<ABI> {
179        fn into_partial_support(self) -> (ABI, Option<ABI>) {
180            assert!(
181                self.start < self.end,
182                "partial-support range must be non-empty"
183            );
184            (self.start, Some(self.end))
185        }
186    }
187
188    #[test]
189    #[should_panic(expected = "partial-support range must be non-empty")]
190    fn partial_support_range_empty() {
191        let _ = (ABI::V6..ABI::V6).into_partial_support();
192    }
193
194    #[test]
195    #[should_panic(expected = "a partial-support range requires full support")]
196    fn partial_support_range_requires_full() {
197        validate_partial_support(ABI::V6, Some(ABI::V9), None);
198    }
199
200    #[test]
201    #[should_panic(expected = "partial-support range must end no later than full support")]
202    fn partial_support_range_ends_after_full() {
203        validate_partial_support(ABI::V6, Some(ABI::V10), Some(ABI::V9));
204    }
205
206    fn validate_partial_support(partial: ABI, plateau_end: Option<ABI>, full: Option<ABI>) {
207        // Full support cannot precede partial support.
208        assert!(partial <= full.unwrap_or(partial));
209        if let Some(end) = plateau_end {
210            assert!(
211                end <= full.expect("a partial-support range requires full support"),
212                "partial-support range must end no later than full support"
213            );
214        }
215    }
216
217    // Emulate old kernel supports.  Iterates each ABI variant, mocks the
218    // builder via B::from(abi), runs the closure on a dedicated thread, and
219    // dispatches to the caller's assertion closures based on whether the
220    // mocked ABI is emulatable on the running kernel.  Within the half-open
221    // range ending at plateau_end, emulation uses partial instead of full.
222    // Outside that range, emulation retains the full-support boundary.
223    fn check_support<B, S, F, OkFn, ErrFn>(
224        partial: ABI,
225        plateau_end: Option<ABI>,
226        full: Option<ABI>,
227        check: F,
228        assert_ok: OkFn,
229        assert_err: ErrFn,
230    ) where
231        B: From<ABI> + Send + 'static,
232        F: Fn(B) -> Result<S, TestRulesetError> + Send + Copy + 'static,
233        S: std::fmt::Debug + Send + 'static,
234        OkFn: Fn(ABI, Result<S, TestRulesetError>),
235        ErrFn: Fn(Result<S, TestRulesetError>),
236    {
237        validate_partial_support(partial, plateau_end, full);
238        for abi in ABI::iter() {
239            // Ensures restrict_self() is called on a dedicated thread to avoid inconsistent tests.
240            let ret = std::thread::spawn(move || check(B::from(abi)))
241                .join()
242                .unwrap();
243
244            // Useful for failed tests and with cargo test -- --show-output
245            println!("Checking ABI {abi:?}: received {ret:#?}");
246            let emulation_full = if plateau_end.is_some_and(|end| partial <= abi && abi < end) {
247                Some(partial)
248            } else {
249                full
250            };
251            if can_emulate(abi, partial, emulation_full) {
252                assert_ok(abi, ret);
253            } else {
254                assert_err(ret);
255            }
256        }
257    }
258
259    fn check_ruleset_support<P, F>(
260        partial: P,
261        full: Option<ABI>,
262        check: F,
263        error_if_abi_lt_partial: bool,
264    ) where
265        P: IntoPartialSupport,
266        F: Fn(Ruleset) -> Result<RestrictionStatus, TestRulesetError> + Send + Copy + 'static,
267    {
268        let (partial, plateau_end) = partial.into_partial_support();
269        check_support(
270            partial,
271            plateau_end,
272            full,
273            check,
274            |abi, ret| {
275                if abi < partial && error_if_abi_lt_partial {
276                    // TODO: Check exact error type; this may require better error types.
277                    assert!(matches!(ret, Err(TestRulesetError::Ruleset(_))));
278                } else {
279                    let full_support = if let Some(full_inner) = full {
280                        abi >= full_inner
281                    } else {
282                        false
283                    };
284                    let ruleset_status = if full_support {
285                        RulesetStatus::FullyEnforced
286                    } else if abi >= partial {
287                        RulesetStatus::PartiallyEnforced
288                    } else {
289                        RulesetStatus::NotEnforced
290                    };
291                    let landlock_status = abi.into();
292                    println!("Expecting ruleset status {ruleset_status:?}");
293                    println!("Expecting Landlock status {landlock_status:?}");
294                    assert!(matches!(
295                        ret,
296                        Ok(RestrictionStatus {
297                            ruleset,
298                            landlock,
299                            no_new_privs: true,
300                            ..
301                        }) if ruleset == ruleset_status && landlock == landlock_status
302                    ))
303                }
304            },
305            |ret| {
306                // The errno value should be ENOSYS, EOPNOTSUPP, EINVAL (e.g. when an unknown
307                // access right is provided), or E2BIG (e.g. when there is an unknown field in a
308                // Landlock syscall attribute).
309                let errno = get_errno_from_landlock_status();
310                println!("Expecting error {errno:?}");
311                match ret {
312                    Err(
313                        ref error @ TestRulesetError::Ruleset(RulesetError::CreateRuleset(
314                            CreateRulesetError::CreateRulesetCall { ref source },
315                        )),
316                    ) => {
317                        assert_eq!(source.raw_os_error(), Some(*Errno::from(error)));
318                        match (source.raw_os_error(), errno) {
319                            (Some(e1), Some(e2)) => assert_eq!(e1, e2),
320                            (Some(e1), None) => assert!(matches!(e1, libc::EINVAL | libc::E2BIG)),
321                            _ => unreachable!(),
322                        }
323                    }
324                    // restrict_self flags may be rejected by the kernel with EINVAL
325                    // when the mock ABI is higher than the running kernel's ABI.
326                    Err(TestRulesetError::Ruleset(RulesetError::RestrictSelf(
327                        RestrictSelfError::RestrictSelfCall { ref source },
328                    ))) => {
329                        assert_eq!(source.raw_os_error(), Some(libc::EINVAL));
330                    }
331                    _ => unreachable!(),
332                }
333            },
334        );
335    }
336
337    // Emulate old kernel supports for the domain-less RestrictSelf builder.
338    //
339    // Unlike check_ruleset_support, RestrictSelf does not create a Landlock domain, so there is no
340    // ruleset enforcement status to assert.  We verify the kernel probe (status.landlock) and
341    // propagate any syscall error.  RestrictSelf::apply() enforces PR_SET_NO_NEW_PRIVS by default.
342    fn check_restrict_self_support<F>(partial: ABI, full: Option<ABI>, check: F)
343    where
344        F: Fn(RestrictSelf) -> Result<RestrictSelfStatus, TestRulesetError> + Send + Copy + 'static,
345    {
346        check_support(
347            partial,
348            None,
349            full,
350            check,
351            |abi, ret| {
352                let landlock_status: LandlockStatus = abi.into();
353                println!("Expecting Landlock status {landlock_status:?}");
354                assert!(matches!(
355                    ret,
356                    Ok(RestrictSelfStatus { landlock, .. }) if landlock == landlock_status
357                ));
358            },
359            |ret| {
360                // The errno value should be ENOSYS, EOPNOTSUPP, or EINVAL (e.g. when actual_flags
361                // carries bits unknown to the running kernel).  Unlike check_ruleset_support,
362                // landlock_restrict_self() is the first syscall here, so ENOSYS is possible when
363                // Landlock is unavailable.
364                let errno = get_errno_from_landlock_status();
365                println!("Expecting error {errno:?}");
366                match ret {
367                    Err(
368                        ref error @ TestRulesetError::Ruleset(RulesetError::RestrictSelf(
369                            RestrictSelfError::RestrictSelfCall { ref source },
370                        )),
371                    ) => {
372                        assert_eq!(source.raw_os_error(), Some(*Errno::from(error)));
373                        match (source.raw_os_error(), errno) {
374                            (Some(e1), Some(e2)) => assert_eq!(e1, e2),
375                            (Some(e1), None) => assert!(matches!(e1, libc::EINVAL | libc::E2BIG)),
376                            _ => unreachable!(),
377                        }
378                    }
379                    _ => unreachable!(),
380                }
381            },
382        );
383    }
384
385    #[test]
386    fn allow_root_compat() {
387        let abi = ABI::V1;
388
389        check_ruleset_support(
390            abi,
391            Some(abi),
392            move |ruleset: Ruleset| -> _ {
393                Ok(ruleset
394                    .handle_access(AccessFs::from_all(abi))?
395                    .create()?
396                    .add_rule(PathBeneath::new(PathFd::new("/")?, AccessFs::from_all(abi)))?
397                    .restrict_self()?)
398            },
399            false,
400        );
401    }
402
403    #[test]
404    fn too_much_access_rights_for_a_file() {
405        let abi = ABI::V1;
406
407        check_ruleset_support(
408            abi,
409            Some(abi),
410            move |ruleset: Ruleset| -> _ {
411                Ok(ruleset
412                    .handle_access(AccessFs::from_all(abi))?
413                    .create()?
414                    // Same code as allow_root_compat() but with /etc/passwd instead of /
415                    .add_rule(PathBeneath::new(
416                        PathFd::new("/etc/passwd")?,
417                        // Only allow legitimate access rights on a file.
418                        AccessFs::from_file(abi),
419                    ))?
420                    .restrict_self()?)
421            },
422            false,
423        );
424
425        check_ruleset_support(
426            abi,
427            None,
428            move |ruleset: Ruleset| -> _ {
429                Ok(ruleset
430                    .handle_access(AccessFs::from_all(abi))?
431                    .create()?
432                    // Same code as allow_root_compat() but with /etc/passwd instead of /
433                    .add_rule(PathBeneath::new(
434                        PathFd::new("/etc/passwd")?,
435                        // Tries to allow all access rights on a file.
436                        AccessFs::from_all(abi),
437                    ))?
438                    .restrict_self()?)
439            },
440            false,
441        );
442    }
443
444    #[test]
445    fn path_beneath_rules_with_too_much_access_rights_for_a_file() {
446        let abi = ABI::V1;
447
448        check_ruleset_support(
449            abi,
450            Some(abi),
451            move |ruleset: Ruleset| -> _ {
452                Ok(ruleset
453                    .handle_access(AccessFs::from_all(ABI::V1))?
454                    .create()?
455                    // Same code as too_much_access_rights_for_a_file() but using path_beneath_rules()
456                    .add_rules(path_beneath_rules(["/etc/passwd"], AccessFs::from_all(abi)))?
457                    .restrict_self()?)
458            },
459            false,
460        );
461    }
462
463    #[test]
464    fn allow_root_fragile() {
465        let abi = ABI::V1;
466
467        check_ruleset_support(
468            abi,
469            Some(abi),
470            move |ruleset: Ruleset| -> _ {
471                // Sets default support requirement: abort the whole sandboxing for any Landlock error.
472                Ok(ruleset
473                    // Must have at least the execute check…
474                    .set_compatibility(CompatLevel::HardRequirement)
475                    .handle_access(AccessFs::Execute)?
476                    // …and possibly others.
477                    .set_compatibility(CompatLevel::BestEffort)
478                    .handle_access(AccessFs::from_all(abi))?
479                    .create()?
480                    .no_new_privs(true)
481                    .add_rule(PathBeneath::new(PathFd::new("/")?, AccessFs::from_all(abi)))?
482                    .restrict_self()?)
483            },
484            true,
485        );
486    }
487
488    #[test]
489    fn ruleset_enforced() {
490        let abi = ABI::V1;
491
492        check_ruleset_support(
493            abi,
494            Some(abi),
495            move |ruleset: Ruleset| -> _ {
496                Ok(ruleset
497                    // Restricting without rule exceptions is legitimate to forbid a set of actions.
498                    .handle_access(AccessFs::Execute)?
499                    .create()?
500                    .restrict_self()?)
501            },
502            false,
503        );
504    }
505
506    #[test]
507    fn abi_v2_exec_refer() {
508        check_ruleset_support(
509            ABI::V1,
510            Some(ABI::V2),
511            move |ruleset: Ruleset| -> _ {
512                Ok(ruleset
513                    .handle_access(AccessFs::Execute)?
514                    // AccessFs::Refer is not supported by ABI::V1 (best-effort).
515                    .handle_access(AccessFs::Refer)?
516                    .create()?
517                    .restrict_self()?)
518            },
519            false,
520        );
521    }
522
523    #[test]
524    fn abi_v2_refer_only() {
525        // When no access is handled, do not try to create a ruleset without access.
526        check_ruleset_support(
527            ABI::V2,
528            Some(ABI::V2),
529            move |ruleset: Ruleset| -> _ {
530                Ok(ruleset
531                    .handle_access(AccessFs::Refer)?
532                    .create()?
533                    .restrict_self()?)
534            },
535            false,
536        );
537    }
538
539    #[test]
540    fn abi_v3_truncate() {
541        check_ruleset_support(
542            ABI::V2,
543            Some(ABI::V3),
544            move |ruleset: Ruleset| -> _ {
545                Ok(ruleset
546                    .handle_access(AccessFs::Refer)?
547                    .handle_access(AccessFs::Truncate)?
548                    .create()?
549                    .add_rule(PathBeneath::new(PathFd::new("/")?, AccessFs::Refer))?
550                    .restrict_self()?)
551            },
552            false,
553        );
554    }
555
556    #[test]
557    fn ruleset_created_try_clone() {
558        check_ruleset_support(
559            ABI::V1,
560            Some(ABI::V1),
561            move |ruleset: Ruleset| -> _ {
562                Ok(ruleset
563                    .handle_access(AccessFs::Execute)?
564                    .create()?
565                    .add_rule(PathBeneath::new(PathFd::new("/")?, AccessFs::Execute))?
566                    .try_clone()?
567                    .restrict_self()?)
568            },
569            false,
570        );
571    }
572
573    #[test]
574    fn abi_v4_tcp() {
575        check_ruleset_support(
576            ABI::V3,
577            Some(ABI::V4),
578            move |ruleset: Ruleset| -> _ {
579                Ok(ruleset
580                    .handle_access(AccessFs::Truncate)?
581                    .handle_access(AccessNet::BindTcp | AccessNet::ConnectTcp)?
582                    .create()?
583                    .add_rule(NetPort::new(1, AccessNet::ConnectTcp))?
584                    .restrict_self()?)
585            },
586            false,
587        );
588    }
589
590    #[test]
591    fn abi_v5_ioctl_dev() {
592        check_ruleset_support(
593            ABI::V4,
594            Some(ABI::V5),
595            move |ruleset: Ruleset| -> _ {
596                Ok(ruleset
597                    .handle_access(AccessNet::BindTcp)?
598                    .handle_access(AccessFs::IoctlDev)?
599                    .create()?
600                    .add_rule(PathBeneath::new(PathFd::new("/")?, AccessFs::IoctlDev))?
601                    .restrict_self()?)
602            },
603            false,
604        );
605    }
606
607    #[test]
608    fn abi_v6_scope_mix() {
609        check_ruleset_support(
610            ABI::V5,
611            Some(ABI::V6),
612            move |ruleset: Ruleset| -> _ {
613                Ok(ruleset
614                    .handle_access(AccessFs::IoctlDev)?
615                    .scope(Scope::AbstractUnixSocket | Scope::Signal)?
616                    .create()?
617                    .restrict_self()?)
618            },
619            false,
620        );
621    }
622
623    #[test]
624    fn abi_v6_scope_only() {
625        check_ruleset_support(
626            ABI::V6,
627            Some(ABI::V6),
628            move |ruleset: Ruleset| -> _ {
629                Ok(ruleset
630                    .scope(Scope::AbstractUnixSocket | Scope::Signal)?
631                    .create()?
632                    .restrict_self()?)
633            },
634            false,
635        );
636    }
637
638    #[test]
639    fn abi_v7_log_flags() {
640        // Uses Scope::Signal to get partial enforcement at V6 (scopes supported
641        // but log flags not).
642        check_ruleset_support(
643            ABI::V6,
644            Some(ABI::V7),
645            move |ruleset: Ruleset| -> _ {
646                let status = ruleset
647                    .scope(Scope::Signal)?
648                    .create()?
649                    .log_same_exec(false)?
650                    .log_new_exec(true)?
651                    .log_subdomains(false)?
652                    .restrict_self()?;
653
654                if status.ruleset == RulesetStatus::FullyEnforced {
655                    assert!(!status.log_same_exec);
656                    assert!(status.log_new_exec);
657                    assert!(!status.log_subdomains);
658                } else {
659                    assert!(status.log_same_exec);
660                    assert!(!status.log_new_exec);
661                    assert!(status.log_subdomains);
662                }
663
664                Ok(status)
665            },
666            false,
667        );
668    }
669
670    #[test]
671    fn ruleset_created_try_clone_ownedfd() {
672        use std::os::unix::io::{AsRawFd, OwnedFd};
673
674        let abi = ABI::V1;
675        check_ruleset_support(
676            abi,
677            Some(abi),
678            move |ruleset: Ruleset| -> _ {
679                let ruleset1 = ruleset.handle_access(AccessFs::from_all(abi))?.create()?;
680                let ruleset2 = ruleset1.try_clone().unwrap();
681                let ruleset3 = ruleset2.try_clone().unwrap();
682
683                let some1: Option<OwnedFd> = ruleset1.into();
684                if let Some(fd1) = some1 {
685                    assert!(fd1.as_raw_fd() >= 0);
686
687                    let some2: Option<OwnedFd> = ruleset2.into();
688                    let fd2 = some2.unwrap();
689                    assert!(fd2.as_raw_fd() >= 0);
690
691                    assert_ne!(fd1.as_raw_fd(), fd2.as_raw_fd());
692                }
693                Ok(ruleset3.restrict_self()?)
694            },
695            false,
696        );
697    }
698
699    #[test]
700    fn restrict_self_log_subdomains() {
701        check_restrict_self_support(ABI::V7, Some(ABI::V7), move |rs: RestrictSelf| -> _ {
702            Ok(rs.log_subdomains(false)?.apply()?)
703        });
704    }
705
706    // ABI v8's LANDLOCK_RESTRICT_SELF_TSYNC (exposed as all_threads()) applies
707    // the domain to every thread of the process, not just the calling one.
708    // Enforcing that in the cargo-test runner would restrict every test thread,
709    // so each all_threads() setting runs in its own forked child (restrict_self
710    // is irreversible and, with TSYNC, process-wide) that hosts exactly two
711    // threads: its main thread and one sibling.  Both threads list "/" (which
712    // needs AccessFs::ReadDir, handled by from_all(ABI::V1)) before and after
713    // enforcement.
714    //
715    // Expected outcomes are pinned from TEST_ABI, the running kernel's Landlock
716    // ABI: set per kernel by CI, auto-detected locally, and asserted to match
717    // the kernel by current_kernel_abi().  It is an oracle independent of the
718    // restrict_self() status under test: the calling thread must be denied iff
719    // Landlock is enforced at all, and the sibling must be denied iff TSYNC is
720    // both requested and supported (ABI v8+).  Both the kernel's real behavior
721    // and the crate's reported status are checked against this truth, so a
722    // silently dropped or otherwise ineffective TSYNC is caught on every kernel
723    // in the CI matrix, from unsupported up to v8.
724    #[test]
725    fn abi_v8_all_threads() {
726        use crate::compat::TEST_ABI;
727        use std::sync::{Arc, Barrier};
728        use std::thread;
729
730        // Child exit code: OK, the OR of the mismatched checks, or PANICKED.
731        const OK: i32 = 0;
732        const MAIN_BEFORE_DENIED: i32 = 1 << 0;
733        const SIBLING_BEFORE_DENIED: i32 = 1 << 1;
734        const MAIN_AFTER_MISMATCH: i32 = 1 << 2;
735        const SIBLING_AFTER_MISMATCH: i32 = 1 << 3;
736        const STATUS_RULESET_MISMATCH: i32 = 1 << 4;
737        const STATUS_TSYNC_MISMATCH: i32 = 1 << 5;
738        const PANICKED: i32 = 1 << 6;
739
740        // Listing "/" needs AccessFs::ReadDir: allowed before enforcement,
741        // denied afterwards for every thread the domain covers.
742        fn can_list_root() -> bool {
743            std::fs::read_dir("/").is_ok()
744        }
745
746        // Ground truth for the running kernel, independent of the status object.
747        let landlock_supported = *TEST_ABI != ABI::Unsupported;
748        let tsync_supported = *TEST_ABI >= ABI::V8;
749
750        for all_threads in [false, true] {
751            // The sibling is covered only when TSYNC is requested and supported.
752            let expect_sibling_denied = all_threads && tsync_supported;
753
754            match unsafe { libc::fork() } {
755                -1 => panic!("fork() failed: {}", std::io::Error::last_os_error()),
756                0 => {
757                    // Any panic (builder error, spawn/join failure) becomes a
758                    // non-zero code rather than being swallowed as a pass.
759                    let code = std::panic::catch_unwind(|| {
760                        let barrier = Arc::new(Barrier::new(2));
761                        let sibling = {
762                            let barrier = Arc::clone(&barrier);
763                            thread::spawn(move || {
764                                let before = can_list_root();
765                                // Both threads probed before enforcing.
766                                barrier.wait();
767                                // Main has called restrict_self().
768                                barrier.wait();
769                                (before, can_list_root())
770                            })
771                        };
772
773                        let main_before = can_list_root();
774                        barrier.wait();
775
776                        let status = Ruleset::default()
777                            .handle_access(AccessFs::from_all(ABI::V1))
778                            .unwrap()
779                            .create()
780                            .unwrap()
781                            .all_threads(all_threads)
782                            .unwrap()
783                            .restrict_self()
784                            .unwrap();
785                        barrier.wait();
786
787                        let main_denied = !can_list_root();
788                        let (sibling_before, sibling_after) = sibling.join().unwrap();
789                        let sibling_denied = !sibling_after;
790                        let ruleset_enforced = status.ruleset != RulesetStatus::NotEnforced;
791
792                        let mut code = OK;
793                        // Both threads can list "/" before enforcement.
794                        if !main_before {
795                            code |= MAIN_BEFORE_DENIED;
796                        }
797                        if !sibling_before {
798                            code |= SIBLING_BEFORE_DENIED;
799                        }
800                        // Kernel reality matches the independent expectation.
801                        if main_denied != landlock_supported {
802                            code |= MAIN_AFTER_MISMATCH;
803                        }
804                        if sibling_denied != expect_sibling_denied {
805                            code |= SIBLING_AFTER_MISMATCH;
806                        }
807                        // The crate's reported status matches it too.
808                        if ruleset_enforced != landlock_supported {
809                            code |= STATUS_RULESET_MISMATCH;
810                        }
811                        if status.all_threads != expect_sibling_denied {
812                            code |= STATUS_TSYNC_MISMATCH;
813                        }
814                        code
815                    })
816                    .unwrap_or(PANICKED);
817                    // _exit avoids atexit handlers and destructors inherited from
818                    // the test harness.
819                    unsafe { libc::_exit(code) };
820                }
821                pid => {
822                    let mut wstatus: libc::c_int = 0;
823                    let ret = unsafe { libc::waitpid(pid, &mut wstatus, 0) };
824                    assert_eq!(ret, pid);
825                    assert!(libc::WIFEXITED(wstatus));
826                    assert_eq!(libc::WEXITSTATUS(wstatus), OK, "all_threads({all_threads})");
827                }
828            }
829        }
830    }
831
832    #[test]
833    fn abi_v9_resolve_unix() {
834        // ResolveUnix is the only access right added in ABI v9, and ABI v8 added
835        // no filesystem access right, so there is no access from a lower ABI to
836        // combine it with while keeping `partial` and `full` adjacent.  It is
837        // therefore tested on its own with partial == full == V9, like
838        // abi_v2_refer_only.  Pairing it with a non-adjacent lower right (e.g.
839        // IoctlDev from V5) would leave mocked ABIs V6..=V8 where only that lower
840        // right is enforced (PartiallyEnforced); can_emulate() expects an error
841        // whenever the runner kernel's ABI is below the mocked one, so such a
842        // test would pass or fail depending on the runner kernel.
843        //
844        // For a mocked ABI below V9, ResolveUnix is dropped by best-effort
845        // compatibility: no access is handled, create() builds no kernel ruleset
846        // and add_rule() is a no-op, so restrict_self() reports NotEnforced (not
847        // an error).  At mocked ABI V9 the ruleset is fully enforced on a v9
848        // kernel, or the create()/add_rule() syscall is rejected on an older one
849        // (asserted through can_emulate()'s error path).
850        check_ruleset_support(
851            ABI::V9,
852            Some(ABI::V9),
853            move |ruleset: Ruleset| -> _ {
854                Ok(ruleset
855                    .handle_access(AccessFs::ResolveUnix)?
856                    .create()?
857                    .add_rule(PathBeneath::new(PathFd::new("/")?, AccessFs::ResolveUnix))?
858                    .restrict_self()?)
859            },
860            false,
861        );
862    }
863
864    #[test]
865    fn abi_v10_udp() {
866        // ResolveUnix keeps ABI v9 partially enforced before UDP support in v10.
867        check_ruleset_support(
868            ABI::V9,
869            Some(ABI::V10),
870            move |ruleset: Ruleset| -> _ {
871                Ok(ruleset
872                    .handle_access(AccessFs::ResolveUnix)?
873                    .handle_access(AccessNet::BindUdp | AccessNet::ConnectSendUdp)?
874                    .create()?
875                    .add_rule(NetPort::new(1, AccessNet::ConnectSendUdp))?
876                    .restrict_self()?)
877            },
878            false,
879        );
880    }
881
882    #[test]
883    fn abi_v10_quiet() {
884        // This test requests no v7 or v8 feature, so these mocks form an
885        // ABI-v6 emulation plateau.
886        check_ruleset_support(
887            ABI::V6..ABI::V9,
888            Some(ABI::V10),
889            move |ruleset: Ruleset| -> _ {
890                Ok(ruleset
891                    .handle_access(AccessFs::ResolveUnix)?
892                    .quiet_access(AccessFs::ResolveUnix)?
893                    .handle_access(AccessNet::BindUdp)?
894                    .quiet_access(AccessNet::BindUdp)?
895                    .scope(Scope::Signal)?
896                    .quiet_scope(Scope::Signal)?
897                    .create()?
898                    .add_rule(
899                        PathBeneath::new(PathFd::new("/")?, BitFlags::<AccessFs>::EMPTY)
900                            .quiet(true),
901                    )?
902                    .add_rule(NetPort::new(1, BitFlags::<AccessNet>::EMPTY).quiet(true))?
903                    .restrict_self()?)
904            },
905            false,
906        );
907    }
908}