Skip to main content

landlock/
ruleset.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2
3use crate::access::{Requested, RulesetMasks};
4use crate::compat::private::OptionCompatLevelMut;
5use crate::flags::{RestrictSelfFlag, SyscallFlagExt};
6use crate::prctl::try_set_no_new_privs;
7use crate::restrict_self::private::RestrictSelfFlagsState;
8use crate::{
9    uapi, AccessFs, AccessNet, AddRuleError, AddRulesError, BitFlags, CompatLevel, CompatState,
10    Compatibility, Compatible, CreateRulesetError, HandledAccess, LandlockStatus,
11    PrivateHandledAccess, RestrictSelfAttr, RestrictSelfError, RulesetError, Scope, ScopeError,
12    TryCompat,
13};
14use std::io::Error;
15use std::mem::size_of_val;
16use std::os::unix::io::{AsRawFd, FromRawFd, OwnedFd};
17
18#[cfg(test)]
19use crate::*;
20
21/// A rule that can be added to a Landlock ruleset.
22///
23/// This trait is sealed and cannot be implemented outside of this crate.
24pub trait Rule<T>: PrivateRule<T>
25where
26    T: HandledAccess,
27{
28    /// Configures whether denials related to this rule should be omitted from audit logs.
29    ///
30    /// Quiet rules require a non-empty quiet access mask for the corresponding rule category,
31    /// configured with [`RulesetAttr::quiet_access()`].  This is supported since Landlock ABI v10.
32    /// If compatibility handling removes every quiet access in the category, quieting has no
33    /// effect and a rule without allowed accesses is ignored.
34    fn quiet(mut self, quiet: bool) -> Self {
35        self.set_quiet(quiet);
36        self
37    }
38}
39
40/// Kernel support and ruleset effectiveness for quiet rules.
41#[derive(Clone, Copy, Debug)]
42pub enum QuietRuleCompatibility {
43    Unsupported,
44    SupportedIneffective,
45    SupportedEffective,
46}
47
48// PrivateRule is not public outside this crate.
49pub trait PrivateRule<T>
50where
51    Self: TryCompat<T> + Compatible,
52    T: HandledAccess,
53{
54    const TYPE_ID: uapi::landlock_rule_type;
55
56    /// Returns a raw pointer to the rule's inner attribute.
57    ///
58    /// The caller must ensure that the rule outlives the pointer this function returns, or else it
59    /// will end up pointing to garbage.
60    fn as_ptr(&mut self) -> *const libc::c_void;
61
62    fn check_consistency(&self, ruleset: &RulesetCreated) -> Result<(), AddRulesError>;
63
64    fn set_quiet(&mut self, quiet: bool);
65
66    fn set_quiet_compatibility(&mut self, compatibility: QuietRuleCompatibility);
67
68    fn add_rule_flags(&self) -> u32;
69}
70
71/// Enforcement status of a ruleset.
72#[derive(Debug, PartialEq, Eq)]
73pub enum RulesetStatus {
74    /// All requested restrictions are enforced.
75    FullyEnforced,
76    /// Some requested restrictions are enforced,
77    /// following a best-effort approach.
78    PartiallyEnforced,
79    /// The running system doesn't support Landlock
80    /// or a subset of the requested Landlock features.
81    NotEnforced,
82}
83
84impl From<CompatState> for RulesetStatus {
85    fn from(state: CompatState) -> Self {
86        match state {
87            CompatState::Init | CompatState::No | CompatState::Dummy => RulesetStatus::NotEnforced,
88            CompatState::Full => RulesetStatus::FullyEnforced,
89            CompatState::Partial => RulesetStatus::PartiallyEnforced,
90        }
91    }
92}
93
94// The Debug, PartialEq and Eq implementations are useful for crate users to debug and check the
95// result of a Landlock ruleset enforcement.
96/// Status of a [`RulesetCreated`]
97/// after calling [`restrict_self()`](RulesetCreated::restrict_self).
98#[derive(Debug, PartialEq, Eq)]
99#[non_exhaustive]
100pub struct RestrictionStatus {
101    /// Status of the Landlock ruleset enforcement.
102    pub ruleset: RulesetStatus,
103    /// Status of `prctl(2)`'s `PR_SET_NO_NEW_PRIVS` enforcement.
104    pub no_new_privs: bool,
105    /// Status of Landlock for the running kernel.
106    pub landlock: LandlockStatus,
107    /// Same-exec logging is enabled (default: true).
108    pub log_same_exec: bool,
109    /// New-exec logging is enabled (default: false).
110    pub log_new_exec: bool,
111    /// Subdomain logging is enabled (default: true).
112    pub log_subdomains: bool,
113    /// The ruleset was applied to all threads of the process (default: false).
114    pub all_threads: bool,
115}
116
117/// Landlock ruleset builder.
118///
119/// `Ruleset` enables to create a Landlock ruleset in a flexible way
120/// following the builder pattern.
121/// Most build steps return a [`Result`] with [`RulesetError`].
122///
123/// You should probably not create more than one ruleset per application.
124/// Creating multiple rulesets is only useful when gradually restricting an application
125/// (e.g., a first set of generic restrictions before reading any file,
126/// then a second set of tailored restrictions after reading the configuration).
127///
128/// # Simple example
129///
130/// Simple helper handling only Landlock-related errors.
131///
132/// ```
133/// use landlock::{
134///     Access, AccessFs, PathBeneath, PathFd, RestrictionStatus, Ruleset, RulesetAttr,
135///     RulesetCreatedAttr, RulesetError, ABI,
136/// };
137/// use std::os::unix::io::AsFd;
138///
139/// fn restrict_fd<T>(hierarchy: T) -> Result<RestrictionStatus, RulesetError>
140/// where
141///     T: AsFd,
142/// {
143///     // The Landlock ABI should be incremented (and tested) regularly.
144///     let abi = ABI::V1;
145///     let access_all = AccessFs::from_all(abi);
146///     let access_read = AccessFs::from_read(abi);
147///     Ok(Ruleset::default()
148///         .handle_access(access_all)?
149///         .create()?
150///         .add_rule(PathBeneath::new(hierarchy, access_read))?
151///         .restrict_self()?)
152/// }
153///
154/// let fd = PathFd::new("/home").expect("failed to open /home");
155/// let status = restrict_fd(fd).expect("failed to build the ruleset");
156/// ```
157///
158/// # Generic example
159///
160/// More generic helper handling a set of file hierarchies
161/// and multiple types of error (i.e. [`RulesetError`](crate::RulesetError)
162/// and [`PathFdError`](crate::PathFdError).
163///
164/// ```
165/// use landlock::{
166///     Access, AccessFs, PathBeneath, PathFd, PathFdError, RestrictionStatus, Ruleset,
167///     RulesetAttr, RulesetCreatedAttr, RulesetError, ABI,
168/// };
169/// use thiserror::Error;
170///
171/// #[derive(Debug, Error)]
172/// enum MyRestrictError {
173///     #[error(transparent)]
174///     Ruleset(#[from] RulesetError),
175///     #[error(transparent)]
176///     AddRule(#[from] PathFdError),
177/// }
178///
179/// fn restrict_paths(hierarchies: &[&str]) -> Result<RestrictionStatus, MyRestrictError> {
180///     // The Landlock ABI should be incremented (and tested) regularly.
181///     let abi = ABI::V1;
182///     let access_all = AccessFs::from_all(abi);
183///     let access_read = AccessFs::from_read(abi);
184///     Ok(Ruleset::default()
185///         .handle_access(access_all)?
186///         .create()?
187///         .add_rules(
188///             hierarchies
189///                 .iter()
190///                 .map::<Result<_, MyRestrictError>, _>(|p| {
191///                     Ok(PathBeneath::new(PathFd::new(p)?, access_read))
192///                 }),
193///         )?
194///         .restrict_self()?)
195/// }
196///
197/// let status = restrict_paths(&["/usr", "/home"]).expect("failed to build the ruleset");
198/// ```
199#[derive(Debug)]
200pub struct Ruleset {
201    pub(crate) fs: RulesetMasks<AccessFs, Requested>,
202    pub(crate) net: RulesetMasks<AccessNet, Requested>,
203    pub(crate) scoped: RulesetMasks<Scope, Requested>,
204    pub(crate) compat: Compatibility,
205}
206
207impl From<Compatibility> for Ruleset {
208    fn from(compat: Compatibility) -> Self {
209        Ruleset {
210            // Empty requests force users to explicitly configure handled accesses.
211            fs: Default::default(),
212            net: Default::default(),
213            scoped: Default::default(),
214            compat,
215        }
216    }
217}
218
219#[cfg(test)]
220impl From<ABI> for Ruleset {
221    fn from(abi: ABI) -> Self {
222        Ruleset::from(Compatibility::from(abi))
223    }
224}
225
226#[test]
227fn ruleset_add_rule_iter() {
228    assert!(matches!(
229        Ruleset::from(ABI::Unsupported)
230            .handle_access(AccessFs::Execute)
231            .unwrap()
232            .create()
233            .unwrap()
234            .add_rule(PathBeneath::new(
235                PathFd::new("/").unwrap(),
236                AccessFs::ReadFile
237            ))
238            .unwrap_err(),
239        RulesetError::AddRules(AddRulesError::Fs(AddRuleError::UnhandledAccess { .. }))
240    ));
241}
242
243#[test]
244fn quiet_rule_requires_category_mask() {
245    let ruleset = Ruleset::from(ABI::V10)
246        .handle_access(AccessFs::ReadFile)
247        .unwrap();
248    assert!(matches!(
249        RulesetCreated::new(ruleset, None)
250            .add_rule(
251                PathBeneath::new(PathFd::new("/").unwrap(), BitFlags::<AccessFs>::EMPTY)
252                    .quiet(true)
253            )
254            .unwrap_err(),
255        RulesetError::AddRules(AddRulesError::Fs(AddRuleError::MissingQuietAccess))
256    ));
257
258    let ruleset = Ruleset::from(ABI::V10)
259        .handle_access(AccessNet::BindUdp)
260        .unwrap();
261    assert!(matches!(
262        RulesetCreated::new(ruleset, None)
263            .add_rule(NetPort::new(0, BitFlags::<AccessNet>::EMPTY).quiet(true))
264            .unwrap_err(),
265        RulesetError::AddRules(AddRulesError::Net(AddRuleError::MissingQuietAccess))
266    ));
267}
268
269#[test]
270fn quiet_rule_uses_effective_mask() {
271    let mut ruleset = Ruleset::from(ABI::V10)
272        .handle_access(AccessFs::ReadFile)
273        .unwrap()
274        .quiet_access(AccessFs::ReadFile)
275        .unwrap();
276    // Exercise effective quiet-rule compatibility without issuing a syscall.
277    ruleset.compat.state = CompatState::Dummy;
278    let ruleset_created = RulesetCreated::new(ruleset, None)
279        .add_rule(
280            PathBeneath::new(PathFd::new("/").unwrap(), BitFlags::<AccessFs>::EMPTY).quiet(true),
281        )
282        .unwrap();
283    assert_eq!(ruleset_created.compat.state, CompatState::Dummy);
284
285    let ruleset = Ruleset::from(ABI::V9)
286        .handle_access(AccessFs::ReadFile)
287        .unwrap()
288        .quiet_access(AccessFs::ReadFile)
289        .unwrap();
290    let ruleset_created = RulesetCreated::new(ruleset, None)
291        .add_rule(
292            PathBeneath::new(PathFd::new("/").unwrap(), BitFlags::<AccessFs>::EMPTY).quiet(true),
293        )
294        .unwrap();
295    assert_eq!(ruleset_created.compat.state, CompatState::Partial);
296
297    let ruleset = Ruleset::from(ABI::V9)
298        .handle_access(AccessFs::ReadFile)
299        .unwrap()
300        .quiet_access(AccessFs::ReadFile)
301        .unwrap();
302    assert!(matches!(
303        RulesetCreated::new(ruleset, None)
304            .set_compatibility(CompatLevel::HardRequirement)
305            .add_rule(
306                PathBeneath::new(PathFd::new("/").unwrap(), BitFlags::<AccessFs>::EMPTY)
307                    .quiet(true)
308            )
309            .unwrap_err(),
310        RulesetError::AddRules(AddRulesError::Fs(AddRuleError::Compat(
311            CompatError::QuietNotSupported
312        )))
313    ));
314
315    // Models a future access right that degrades away on an ABI-v10 kernel,
316    // which still supports quiet rules.  The unknown bit stands in for a
317    // future enum variant while bypassing today's public compatibility check.
318    let future_fs = unsafe { BitFlags::<AccessFs>::from_bits_unchecked(1 << 63) };
319    let mut ruleset = Ruleset::from(ABI::V10);
320    ruleset.fs.access = future_fs;
321    ruleset.fs.quiet = future_fs;
322    ruleset.compat.state = CompatState::Partial;
323    let ruleset_created = RulesetCreated::new(ruleset, None)
324        .set_compatibility(CompatLevel::HardRequirement)
325        .add_rule(
326            PathBeneath::new(PathFd::new("/").unwrap(), BitFlags::<AccessFs>::EMPTY).quiet(true),
327        )
328        .unwrap();
329    assert_eq!(ruleset_created.compat.state, CompatState::Partial);
330
331    let future_net = unsafe { BitFlags::<AccessNet>::from_bits_unchecked(1 << 63) };
332    let mut ruleset = Ruleset::from(ABI::V10);
333    ruleset.net.access = future_net;
334    ruleset.net.quiet = future_net;
335    ruleset.compat.state = CompatState::Partial;
336    let ruleset_created = RulesetCreated::new(ruleset, None)
337        .set_compatibility(CompatLevel::HardRequirement)
338        .add_rule(NetPort::new(0, BitFlags::<AccessNet>::EMPTY).quiet(true))
339        .unwrap();
340    assert_eq!(ruleset_created.compat.state, CompatState::Partial);
341}
342
343impl Default for Ruleset {
344    /// Returns a new `Ruleset`.
345    /// This call automatically probes the running kernel to know if it supports Landlock.
346    ///
347    /// To be able to successfully call [`create()`](Ruleset::create),
348    /// it is required to set the handled accesses with
349    /// [`handle_access()`](Ruleset::handle_access).
350    fn default() -> Self {
351        // The API should be future-proof: one Rust program or library should have the same
352        // behavior if built with an old or a newer crate (e.g. with an extended ruleset_attr
353        // enum).  It should then not be possible to give an "all-possible-handled-accesses" to the
354        // Ruleset builder because this value would be relative to the running kernel.
355        Compatibility::new().into()
356    }
357}
358
359impl Ruleset {
360    fn validate_quiet_masks(&self) -> Result<(), CreateRulesetError> {
361        let incompatible_fs = self.fs.incompatible_quiet();
362        if !incompatible_fs.is_empty() {
363            return Err(CreateRulesetError::UnhandledQuietAccessFs {
364                access: self.fs.quiet,
365                incompatible: incompatible_fs,
366            });
367        }
368
369        let incompatible_net = self.net.incompatible_quiet();
370        if !incompatible_net.is_empty() {
371            return Err(CreateRulesetError::UnhandledQuietAccessNet {
372                access: self.net.quiet,
373                incompatible: incompatible_net,
374            });
375        }
376
377        let incompatible_scoped = self.scoped.incompatible_quiet();
378        if !incompatible_scoped.is_empty() {
379            return Err(CreateRulesetError::UnhandledQuietScope {
380                access: self.scoped.quiet,
381                incompatible: incompatible_scoped,
382            });
383        }
384        Ok(())
385    }
386
387    #[allow(clippy::new_without_default)]
388    #[deprecated(note = "Use Ruleset::default() instead")]
389    pub fn new() -> Self {
390        Ruleset::default()
391    }
392
393    /// Attempts to create a real Landlock ruleset (if supported by the running kernel).
394    /// The returned [`RulesetCreated`] is also a builder.
395    ///
396    /// On error, returns a wrapped [`CreateRulesetError`].
397    pub fn create(mut self) -> Result<RulesetCreated, RulesetError> {
398        let body = || -> Result<RulesetCreated, CreateRulesetError> {
399            self.validate_quiet_masks()?;
400            match self.compat.state {
401                CompatState::Init => {
402                    // Checks that there is at least one requested access: one
403                    // call to handle_access() or scope().
404                    Err(CreateRulesetError::MissingHandledAccess)
405                }
406                CompatState::No | CompatState::Dummy => {
407                    // There is at least one requested access.
408                    #[cfg(test)]
409                    assert!(
410                        !self.fs.access.is_empty()
411                            || !self.net.access.is_empty()
412                            || !self.scoped.access.is_empty()
413                    );
414
415                    // CompatState::No should be handled as CompatState::Dummy because it is not
416                    // possible to create an actual ruleset.
417                    self.compat.update(CompatState::Dummy);
418                    match self.compat.level.into() {
419                        CompatLevel::HardRequirement => {
420                            Err(CreateRulesetError::MissingHandledAccess)
421                        }
422                        _ => Ok(RulesetCreated::new(self, None)),
423                    }
424                }
425                CompatState::Full | CompatState::Partial => {
426                    let abi = self.compat.abi();
427                    let effective_fs = self.fs.resolve(abi);
428                    let effective_net = self.net.resolve(abi);
429                    let effective_scoped = self.scoped.resolve(abi);
430                    // There is at least one effective handled access.
431                    #[cfg(test)]
432                    assert!(
433                        !effective_fs.access.is_empty()
434                            || !effective_net.access.is_empty()
435                            || !effective_scoped.access.is_empty()
436                    );
437
438                    let attr = uapi::landlock_ruleset_attr {
439                        handled_access_fs: effective_fs.access.bits(),
440                        handled_access_net: effective_net.access.bits(),
441                        scoped: effective_scoped.access.bits(),
442                        quiet_access_fs: effective_fs.quiet.bits(),
443                        quiet_access_net: effective_net.quiet.bits(),
444                        quiet_scoped: effective_scoped.quiet.bits(),
445                    };
446                    match unsafe { uapi::landlock_create_ruleset(&attr, size_of_val(&attr), 0) } {
447                        fd if fd >= 0 => Ok(RulesetCreated::new(
448                            self,
449                            Some(unsafe { OwnedFd::from_raw_fd(fd) }),
450                        )),
451                        _ => Err(CreateRulesetError::CreateRulesetCall {
452                            source: Error::last_os_error(),
453                        }),
454                    }
455                }
456            }
457        };
458        Ok(body()?)
459    }
460}
461
462impl OptionCompatLevelMut for Ruleset {
463    fn as_option_compat_level_mut(&mut self) -> &mut Option<CompatLevel> {
464        &mut self.compat.level
465    }
466}
467
468impl OptionCompatLevelMut for &mut Ruleset {
469    fn as_option_compat_level_mut(&mut self) -> &mut Option<CompatLevel> {
470        &mut self.compat.level
471    }
472}
473
474impl Compatible for Ruleset {}
475
476impl Compatible for &mut Ruleset {}
477
478impl AsMut<Ruleset> for Ruleset {
479    fn as_mut(&mut self) -> &mut Ruleset {
480        self
481    }
482}
483
484// Tests unambiguous type.
485#[test]
486fn ruleset_as_mut() {
487    let mut ruleset = Ruleset::from(ABI::Unsupported);
488    let _ = ruleset.as_mut();
489
490    let mut ruleset_created = Ruleset::from(ABI::Unsupported)
491        .handle_access(AccessFs::Execute)
492        .unwrap()
493        .create()
494        .unwrap();
495    let _ = ruleset_created.as_mut();
496}
497
498pub trait RulesetAttr: Sized + AsMut<Ruleset> + Compatible {
499    /// Attempts to add a set of access rights that will be supported by this ruleset.
500    /// By default, all actions requiring these access rights will be denied.
501    /// Consecutive calls to `handle_access()` will be interpreted as logical ORs
502    /// with the previous handled accesses.
503    ///
504    /// On error, returns a wrapped [`HandleAccessesError`](crate::HandleAccessesError).
505    /// E.g., `RulesetError::HandleAccesses(HandleAccessesError::Fs(HandleAccessError<AccessFs>))`
506    fn handle_access<T, U>(mut self, access: T) -> Result<Self, RulesetError>
507    where
508        T: Into<BitFlags<U>>,
509        U: HandledAccess + PrivateHandledAccess,
510    {
511        U::ruleset_handle_access(self.as_mut(), access.into())?;
512        Ok(self)
513    }
514
515    /// Selects handled access rights whose denials may be omitted from audit logs.
516    ///
517    /// The selected rights must also be configured with [`handle_access()`](Self::handle_access),
518    /// but the two methods may be called in either order.  Filesystem and network quieting apply
519    /// only to objects marked with [`Rule::quiet()`].  This is supported since Landlock ABI v10.
520    ///
521    /// Consecutive calls are interpreted as logical ORs.  On error, returns a wrapped
522    /// [`HandleAccessesError`](crate::HandleAccessesError).
523    fn quiet_access<T, U>(mut self, access: T) -> Result<Self, RulesetError>
524    where
525        T: Into<BitFlags<U>>,
526        U: HandledAccess + PrivateHandledAccess,
527    {
528        U::ruleset_quiet_access(self.as_mut(), access.into())?;
529        Ok(self)
530    }
531
532    /// Attempts to add a set of scopes that will be supported by this ruleset.
533    /// Consecutive calls to `scope()` will be interpreted as logical ORs
534    /// with the previous scopes.
535    ///
536    /// On error, returns a wrapped [`ScopeError`](crate::ScopeError).
537    /// E.g., `RulesetError::Scope(ScopeError)`
538    fn scope<T>(mut self, scope: T) -> Result<Self, RulesetError>
539    where
540        T: Into<BitFlags<Scope>>,
541    {
542        let scope = scope.into();
543        let ruleset = self.as_mut();
544        ruleset
545            .scoped
546            .request(scope, &mut ruleset.compat)
547            .map_err(ScopeError::Compat)?;
548        Ok(self)
549    }
550
551    /// Selects scoped accesses whose denials should be omitted from audit logs.
552    ///
553    /// The selected scopes must also be configured with [`scope()`](Self::scope), but the two
554    /// methods may be called in either order.  Unlike filesystem and network quiet accesses,
555    /// scopes do not use per-object rules.  This is supported since Landlock ABI v10.
556    ///
557    /// Consecutive calls are interpreted as logical ORs.  On error, returns a wrapped
558    /// [`ScopeError`](crate::ScopeError).
559    fn quiet_scope<T>(mut self, scope: T) -> Result<Self, RulesetError>
560    where
561        T: Into<BitFlags<Scope>>,
562    {
563        let scope = scope.into();
564        let ruleset = self.as_mut();
565        ruleset
566            .scoped
567            .request_quiet(scope, &mut ruleset.compat)
568            .map_err(ScopeError::Compat)?;
569        Ok(self)
570    }
571}
572
573impl RulesetAttr for Ruleset {}
574
575impl RulesetAttr for &mut Ruleset {}
576
577#[test]
578fn ruleset_attr() {
579    let mut ruleset = Ruleset::from(ABI::Unsupported);
580    let ruleset_ref = &mut ruleset;
581
582    // Can pass this reference to prepare the ruleset...
583    ruleset_ref
584        .set_compatibility(CompatLevel::BestEffort)
585        .handle_access(AccessFs::Execute)
586        .unwrap()
587        .handle_access(AccessFs::ReadFile)
588        .unwrap();
589
590    // ...and finally create the ruleset (thanks to non-lexical lifetimes).
591    ruleset
592        .set_compatibility(CompatLevel::BestEffort)
593        .handle_access(AccessFs::Execute)
594        .unwrap()
595        .handle_access(AccessFs::WriteFile)
596        .unwrap()
597        .create()
598        .unwrap();
599}
600
601#[test]
602fn ruleset_created_handle_access_fs() {
603    let access = make_bitflags!(AccessFs::{Execute | ReadDir});
604
605    // Tests AccessFs::ruleset_handle_access()
606    let ruleset = Ruleset::from(ABI::V1).handle_access(access).unwrap();
607    assert_eq!(ruleset.fs.access, access);
608    assert_eq!(ruleset.fs.resolve(ruleset.compat.abi()).access, access);
609
610    // Tests composition (binary OR) of handled accesses.
611    let ruleset = Ruleset::from(ABI::V1)
612        .handle_access(AccessFs::Execute)
613        .unwrap()
614        .handle_access(AccessFs::ReadDir)
615        .unwrap()
616        .handle_access(AccessFs::Execute)
617        .unwrap();
618    assert_eq!(ruleset.fs.access, access);
619    assert_eq!(ruleset.fs.resolve(ruleset.compat.abi()).access, access);
620
621    // Tests that only the required handled accesses are reported as incompatible:
622    // access should not contains AccessFs::Execute.
623    assert!(matches!(Ruleset::from(ABI::Unsupported)
624        .handle_access(AccessFs::Execute)
625        .unwrap()
626        .set_compatibility(CompatLevel::HardRequirement)
627        .handle_access(AccessFs::ReadDir)
628        .unwrap_err(),
629        RulesetError::HandleAccesses(HandleAccessesError::Fs(HandleAccessError::Compat(
630            CompatError::Access(AccessError::Incompatible { access })
631        ))) if access == AccessFs::ReadDir
632    ));
633}
634
635#[test]
636fn ruleset_created_handle_access_net_tcp() {
637    let access = make_bitflags!(AccessNet::{BindTcp | ConnectTcp});
638
639    // Tests AccessNet::ruleset_handle_access() with ABI that doesn't support TCP rights.
640    let ruleset = Ruleset::from(ABI::V3).handle_access(access).unwrap();
641    assert_eq!(ruleset.net.access, access);
642    assert_eq!(
643        ruleset.net.resolve(ruleset.compat.abi()).access,
644        BitFlags::<AccessNet>::EMPTY
645    );
646
647    // Tests AccessNet::ruleset_handle_access() with ABI that supports TCP rights.
648    let ruleset = Ruleset::from(ABI::V4).handle_access(access).unwrap();
649    assert_eq!(ruleset.net.access, access);
650    assert_eq!(ruleset.net.resolve(ruleset.compat.abi()).access, access);
651
652    // Tests composition (binary OR) of handled accesses.
653    let ruleset = Ruleset::from(ABI::V4)
654        .handle_access(AccessNet::BindTcp)
655        .unwrap()
656        .handle_access(AccessNet::ConnectTcp)
657        .unwrap()
658        .handle_access(AccessNet::BindTcp)
659        .unwrap();
660    assert_eq!(ruleset.net.access, access);
661    assert_eq!(ruleset.net.resolve(ruleset.compat.abi()).access, access);
662
663    // Tests that only the required handled accesses are reported as incompatible:
664    // access should not contains AccessNet::BindTcp.
665    assert!(matches!(Ruleset::from(ABI::Unsupported)
666        .handle_access(AccessNet::BindTcp)
667        .unwrap()
668        .set_compatibility(CompatLevel::HardRequirement)
669        .handle_access(AccessNet::ConnectTcp)
670        .unwrap_err(),
671        RulesetError::HandleAccesses(HandleAccessesError::Net(HandleAccessError::Compat(
672            CompatError::Access(AccessError::Incompatible { access })
673        ))) if access == AccessNet::ConnectTcp
674    ));
675}
676
677#[test]
678fn ruleset_created_scope() {
679    let scopes = make_bitflags!(Scope::{AbstractUnixSocket | Signal});
680
681    // Tests Ruleset::scope() with ABI that doesn't support scopes.
682    let ruleset = Ruleset::from(ABI::V5).scope(scopes).unwrap();
683    assert_eq!(ruleset.scoped.access, scopes);
684    assert_eq!(
685        ruleset.scoped.resolve(ruleset.compat.abi()).access,
686        BitFlags::<Scope>::EMPTY
687    );
688
689    // Tests Ruleset::scope() with ABI that supports scopes.
690    let ruleset = Ruleset::from(ABI::V6).scope(scopes).unwrap();
691    assert_eq!(ruleset.scoped.access, scopes);
692    assert_eq!(ruleset.scoped.resolve(ruleset.compat.abi()).access, scopes);
693
694    // Tests composition (binary OR) of scopes.
695    let ruleset = Ruleset::from(ABI::V6)
696        .scope(Scope::AbstractUnixSocket)
697        .unwrap()
698        .scope(Scope::Signal)
699        .unwrap()
700        .scope(Scope::AbstractUnixSocket)
701        .unwrap();
702    assert_eq!(ruleset.scoped.access, scopes);
703    assert_eq!(ruleset.scoped.resolve(ruleset.compat.abi()).access, scopes);
704
705    // Tests that only the required scopes are reported as incompatible:
706    // scope should not contain Scope::AbstractUnixSocket.
707    assert!(matches!(Ruleset::from(ABI::Unsupported)
708        .scope(Scope::AbstractUnixSocket)
709        .unwrap()
710        .set_compatibility(CompatLevel::HardRequirement)
711        .scope(Scope::Signal)
712        .unwrap_err(),
713        RulesetError::Scope(ScopeError::Compat(
714            CompatError::Access(AccessError::Incompatible { access })
715        )) if access == Scope::Signal
716    ));
717}
718
719#[test]
720fn ruleset_quiet_masks() {
721    let ruleset = Ruleset::from(ABI::V10)
722        .quiet_access(AccessFs::ReadFile)
723        .unwrap()
724        .handle_access(AccessFs::ReadFile | AccessFs::WriteFile)
725        .unwrap()
726        .quiet_access(AccessNet::BindUdp)
727        .unwrap()
728        .handle_access(AccessNet::BindUdp)
729        .unwrap()
730        .quiet_scope(Scope::Signal)
731        .unwrap()
732        .scope(Scope::Signal)
733        .unwrap();
734    assert_eq!(ruleset.fs.quiet, AccessFs::ReadFile);
735    assert_eq!(ruleset.fs.resolve(ABI::V10).quiet, AccessFs::ReadFile);
736    assert_eq!(ruleset.net.quiet, AccessNet::BindUdp);
737    assert_eq!(ruleset.net.resolve(ABI::V10).quiet, AccessNet::BindUdp);
738    assert_eq!(ruleset.scoped.quiet, Scope::Signal);
739    assert_eq!(ruleset.scoped.resolve(ABI::V10).quiet, Scope::Signal);
740    ruleset.validate_quiet_masks().unwrap();
741    let ruleset_created = RulesetCreated::new(ruleset, None).try_clone().unwrap();
742    assert_eq!(ruleset_created.fs.quiet, AccessFs::ReadFile);
743    assert_eq!(
744        ruleset_created.fs.resolve(ABI::V10).quiet,
745        AccessFs::ReadFile
746    );
747    assert_eq!(ruleset_created.net.quiet, AccessNet::BindUdp);
748    assert_eq!(
749        ruleset_created.net.resolve(ABI::V10).quiet,
750        AccessNet::BindUdp
751    );
752
753    let ruleset = Ruleset::from(ABI::V9)
754        .handle_access(AccessFs::ReadFile)
755        .unwrap()
756        .quiet_access(AccessFs::ReadFile)
757        .unwrap();
758    assert_eq!(ruleset.fs.quiet, AccessFs::ReadFile);
759    assert_eq!(ruleset.fs.resolve(ABI::V9).quiet, BitFlags::EMPTY);
760    assert_eq!(ruleset.compat.state, CompatState::Partial);
761
762    let ruleset = Ruleset::from(ABI::V9)
763        .handle_access(AccessFs::ReadFile)
764        .unwrap()
765        .set_compatibility(CompatLevel::SoftRequirement)
766        .quiet_access(AccessFs::ReadFile)
767        .unwrap();
768    assert_eq!(ruleset.compat.state, CompatState::Dummy);
769
770    assert!(matches!(
771        Ruleset::from(ABI::V9)
772            .handle_access(AccessFs::ReadFile)
773            .unwrap()
774            .set_compatibility(CompatLevel::HardRequirement)
775            .quiet_access(AccessFs::ReadFile)
776            .unwrap_err(),
777        RulesetError::HandleAccesses(HandleAccessesError::Fs(HandleAccessError::Compat(
778            CompatError::QuietNotSupported
779        )))
780    ));
781
782    assert!(matches!(
783        Ruleset::from(ABI::V9)
784            .handle_access(AccessNet::BindTcp)
785            .unwrap()
786            .set_compatibility(CompatLevel::HardRequirement)
787            .quiet_access(AccessNet::BindTcp)
788            .unwrap_err(),
789        RulesetError::HandleAccesses(HandleAccessesError::Net(HandleAccessError::Compat(
790            CompatError::QuietNotSupported
791        )))
792    ));
793
794    assert!(matches!(
795        Ruleset::from(ABI::V9)
796            .scope(Scope::Signal)
797            .unwrap()
798            .set_compatibility(CompatLevel::HardRequirement)
799            .quiet_scope(Scope::Signal)
800            .unwrap_err(),
801        RulesetError::Scope(ScopeError::Compat(CompatError::QuietNotSupported))
802    ));
803
804    assert!(matches!(
805        Ruleset::from(ABI::V10)
806            .quiet_access(BitFlags::<AccessFs>::EMPTY)
807            .unwrap_err(),
808        RulesetError::HandleAccesses(HandleAccessesError::Fs(HandleAccessError::Compat(
809            CompatError::Access(AccessError::Empty)
810        )))
811    ));
812    assert!(matches!(
813        Ruleset::from(ABI::V10)
814            .quiet_scope(BitFlags::<Scope>::EMPTY)
815            .unwrap_err(),
816        RulesetError::Scope(ScopeError::Compat(CompatError::Access(AccessError::Empty)))
817    ));
818}
819
820#[test]
821fn quiet_mask_validation() {
822    let access_fs = AccessFs::ReadFile | AccessFs::WriteFile;
823    assert!(matches!(
824        Ruleset::from(ABI::V10)
825            .handle_access(AccessFs::ReadFile)
826            .unwrap()
827            .quiet_access(access_fs)
828            .unwrap()
829            .create()
830            .unwrap_err(),
831        RulesetError::CreateRuleset(CreateRulesetError::UnhandledQuietAccessFs {
832            access,
833            incompatible,
834        }) if access == access_fs && incompatible == AccessFs::WriteFile
835    ));
836
837    let access_net = AccessNet::BindTcp | AccessNet::BindUdp;
838    assert!(matches!(
839        Ruleset::from(ABI::V10)
840            .handle_access(AccessNet::BindTcp)
841            .unwrap()
842            .quiet_access(access_net)
843            .unwrap()
844            .create()
845            .unwrap_err(),
846        RulesetError::CreateRuleset(CreateRulesetError::UnhandledQuietAccessNet {
847            access,
848            incompatible,
849        }) if access == access_net && incompatible == AccessNet::BindUdp
850    ));
851
852    let scopes = Scope::AbstractUnixSocket | Scope::Signal;
853    assert!(matches!(
854        Ruleset::from(ABI::V10)
855            .scope(Scope::Signal)
856            .unwrap()
857            .quiet_scope(scopes)
858            .unwrap()
859            .create()
860            .unwrap_err(),
861        RulesetError::CreateRuleset(CreateRulesetError::UnhandledQuietScope {
862            access,
863            incompatible,
864        }) if access == scopes && incompatible == Scope::AbstractUnixSocket
865    ));
866}
867
868#[test]
869fn ruleset_created_fs_net_scope() {
870    let access_fs = make_bitflags!(AccessFs::{Execute | ReadDir});
871    let access_net = make_bitflags!(AccessNet::{BindTcp | ConnectTcp});
872    let scopes = make_bitflags!(Scope::{AbstractUnixSocket | Signal});
873
874    // Tests composition (binary OR) of handled accesses.
875    let ruleset = Ruleset::from(ABI::V5)
876        .handle_access(access_fs)
877        .unwrap()
878        .scope(scopes)
879        .unwrap()
880        .handle_access(access_net)
881        .unwrap();
882    assert_eq!(ruleset.fs.access, access_fs);
883    assert_eq!(ruleset.fs.resolve(ruleset.compat.abi()).access, access_fs);
884    assert_eq!(ruleset.net.access, access_net);
885    assert_eq!(ruleset.net.resolve(ruleset.compat.abi()).access, access_net);
886    assert_eq!(ruleset.scoped.access, scopes);
887    assert_eq!(
888        ruleset.scoped.resolve(ruleset.compat.abi()).access,
889        BitFlags::<Scope>::EMPTY
890    );
891
892    // Tests composition (binary OR) of handled accesses and scopes.
893    let ruleset = Ruleset::from(ABI::V6)
894        .handle_access(access_fs)
895        .unwrap()
896        .scope(scopes)
897        .unwrap()
898        .handle_access(access_net)
899        .unwrap();
900    assert_eq!(ruleset.fs.access, access_fs);
901    assert_eq!(ruleset.fs.resolve(ruleset.compat.abi()).access, access_fs);
902    assert_eq!(ruleset.net.access, access_net);
903    assert_eq!(ruleset.net.resolve(ruleset.compat.abi()).access, access_net);
904    assert_eq!(ruleset.scoped.access, scopes);
905    assert_eq!(ruleset.scoped.resolve(ruleset.compat.abi()).access, scopes);
906}
907
908#[test]
909fn ruleset_created_log_flags() {
910    let all_raw = uapi::LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF
911        | uapi::LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON
912        | uapi::LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF;
913
914    // Tests log flags with BestEffort on unsupported ABI: flags are requested but not applied.
915    let ruleset_created = Ruleset::from(ABI::Unsupported)
916        .handle_access(AccessFs::Execute)
917        .unwrap()
918        .create()
919        .unwrap()
920        .log_same_exec(false)
921        .unwrap()
922        .log_new_exec(true)
923        .unwrap()
924        .log_subdomains(false)
925        .unwrap();
926    assert_eq!(ruleset_created.requested_restrict_self_flags, all_raw);
927    assert_eq!(ruleset_created.actual_restrict_self_flags, 0);
928
929    // Tests that calling with default values is a no-op.
930    let ruleset_created = Ruleset::from(ABI::Unsupported)
931        .handle_access(AccessFs::Execute)
932        .unwrap()
933        .create()
934        .unwrap()
935        .log_same_exec(true)
936        .unwrap()
937        .log_new_exec(false)
938        .unwrap()
939        .log_subdomains(true)
940        .unwrap();
941    assert_eq!(ruleset_created.requested_restrict_self_flags, 0);
942    assert_eq!(ruleset_created.actual_restrict_self_flags, 0);
943
944    // Tests SoftRequirement on unsupported ABI: flag silently dropped, state becomes Dummy.
945    let ruleset_created = Ruleset::from(ABI::Unsupported)
946        .handle_access(AccessFs::Execute)
947        .unwrap()
948        .create()
949        .unwrap()
950        .set_compatibility(CompatLevel::SoftRequirement)
951        .log_same_exec(false)
952        .unwrap();
953    assert_eq!(
954        ruleset_created.requested_restrict_self_flags,
955        uapi::LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF
956    );
957    assert_eq!(ruleset_created.actual_restrict_self_flags, 0);
958
959    // Default values with HardRequirement on unsupported ABI: no-ops bypass compat entirely.
960    Ruleset::from(ABI::Unsupported)
961        .handle_access(AccessFs::Execute)
962        .unwrap()
963        .create()
964        .unwrap()
965        .set_compatibility(CompatLevel::HardRequirement)
966        .log_same_exec(true)
967        .unwrap()
968        .log_new_exec(false)
969        .unwrap()
970        .log_subdomains(true)
971        .unwrap();
972
973    // Tests HardRequirement error for unsupported log flags.
974    assert!(matches!(
975        Ruleset::from(ABI::Unsupported)
976            .handle_access(AccessFs::Execute)
977            .unwrap()
978            .create()
979            .unwrap()
980            .set_compatibility(CompatLevel::HardRequirement)
981            .log_same_exec(false)
982            .unwrap_err(),
983        RulesetError::RestrictSelfFlags(SyscallFlagError::NotSupported {
984            flag: RestrictSelfFlag::LogSameExec,
985            set: false,
986        })
987    ));
988}
989
990#[test]
991fn ruleset_created_all_threads() {
992    // Uses ABI::Unsupported throughout so create() does not call the real
993    // landlock_create_ruleset() syscall.  The "flag applied" path on a
994    // supported ABI is covered by the RestrictSelf mock test and the forked
995    // integration test.
996
997    // all_threads(true) requested but dropped by BestEffort on an unsupported
998    // ABI: only the calling thread would be restricted.
999    let ruleset_created = Ruleset::from(ABI::Unsupported)
1000        .handle_access(AccessFs::Execute)
1001        .unwrap()
1002        .create()
1003        .unwrap()
1004        .all_threads(true)
1005        .unwrap();
1006    assert_eq!(
1007        ruleset_created.requested_restrict_self_flags,
1008        uapi::LANDLOCK_RESTRICT_SELF_TSYNC
1009    );
1010    assert_eq!(ruleset_created.actual_restrict_self_flags, 0);
1011
1012    // all_threads(false) is the default: a no-op that bypasses the compat
1013    // check, so it never errors even under HardRequirement on an unsupported
1014    // ABI.
1015    let ruleset_created = Ruleset::from(ABI::Unsupported)
1016        .handle_access(AccessFs::Execute)
1017        .unwrap()
1018        .create()
1019        .unwrap()
1020        .set_compatibility(CompatLevel::HardRequirement)
1021        .all_threads(false)
1022        .unwrap();
1023    assert_eq!(ruleset_created.requested_restrict_self_flags, 0);
1024    assert_eq!(ruleset_created.actual_restrict_self_flags, 0);
1025
1026    // HardRequirement errors when all_threads(true) is unsupported.
1027    assert!(matches!(
1028        Ruleset::from(ABI::Unsupported)
1029            .handle_access(AccessFs::Execute)
1030            .unwrap()
1031            .create()
1032            .unwrap()
1033            .set_compatibility(CompatLevel::HardRequirement)
1034            .all_threads(true)
1035            .unwrap_err(),
1036        RulesetError::RestrictSelfFlags(SyscallFlagError::NotSupported {
1037            flag: RestrictSelfFlag::AllThreads,
1038            set: true,
1039        })
1040    ));
1041}
1042
1043impl OptionCompatLevelMut for RulesetCreated {
1044    fn as_option_compat_level_mut(&mut self) -> &mut Option<CompatLevel> {
1045        &mut self.compat.level
1046    }
1047}
1048
1049impl OptionCompatLevelMut for &mut RulesetCreated {
1050    fn as_option_compat_level_mut(&mut self) -> &mut Option<CompatLevel> {
1051        &mut self.compat.level
1052    }
1053}
1054
1055impl Compatible for RulesetCreated {}
1056
1057impl Compatible for &mut RulesetCreated {}
1058
1059impl RestrictSelfFlagsState for RulesetCreated {
1060    fn try_set_flag(&mut self, flag: RestrictSelfFlag, set: bool) -> Result<(), RulesetError> {
1061        let raw_bit = flag.raw_bit();
1062        // Last-call-wins: requested tracks non-default user intent, actual
1063        // tracks the bit that will be passed to the kernel.
1064        //
1065        // requested_restrict_self_flags is updated unconditionally; the
1066        // actual bitmask is updated only if try_compat succeeds.  On
1067        // HardRequirement + unsupported, try_compat returns Err and
1068        // requested_restrict_self_flags is left in a "user requested this"
1069        // state; the builder is consumed by `?` on error so this
1070        // inconsistency is not observable.
1071        if set == flag.default_value() {
1072            self.requested_restrict_self_flags &= !raw_bit;
1073        } else {
1074            self.requested_restrict_self_flags |= raw_bit;
1075        }
1076        if flag.try_compat(set, &mut self.compat)? {
1077            self.actual_restrict_self_flags |= raw_bit;
1078        } else {
1079            self.actual_restrict_self_flags &= !raw_bit;
1080        }
1081        Ok(())
1082    }
1083}
1084
1085impl RestrictSelfFlagsState for &mut RulesetCreated {
1086    fn try_set_flag(&mut self, flag: RestrictSelfFlag, set: bool) -> Result<(), RulesetError> {
1087        (**self).try_set_flag(flag, set)
1088    }
1089}
1090
1091impl RestrictSelfAttr for RulesetCreated {}
1092impl RestrictSelfAttr for &mut RulesetCreated {}
1093
1094pub trait RulesetCreatedAttr:
1095    Sized + AsMut<RulesetCreated> + Compatible + RestrictSelfAttr
1096{
1097    /// Attempts to add a new rule to the ruleset.
1098    ///
1099    /// On error, returns a wrapped [`AddRulesError`].
1100    fn add_rule<T, U>(mut self, mut rule: T) -> Result<Self, RulesetError>
1101    where
1102        T: Rule<U>,
1103        U: HandledAccess + PrivateHandledAccess,
1104    {
1105        let body = || -> Result<Self, AddRulesError> {
1106            let self_ref = self.as_mut();
1107            rule.check_consistency(self_ref)?;
1108            let abi = self_ref.compat.abi();
1109            let quiet_compatibility = if RulesetMasks::<U, Requested>::supports_quiet(abi) {
1110                if U::ruleset_has_effective_quiet_access(self_ref, abi) {
1111                    QuietRuleCompatibility::SupportedEffective
1112                } else {
1113                    QuietRuleCompatibility::SupportedIneffective
1114                }
1115            } else {
1116                QuietRuleCompatibility::Unsupported
1117            };
1118            rule.set_quiet_compatibility(quiet_compatibility);
1119            let mut compat_rule = match rule
1120                .try_compat(abi, self_ref.compat.level, &mut self_ref.compat.state)
1121                .map_err(AddRuleError::Compat)?
1122            {
1123                Some(r) => r,
1124                None => return Ok(self),
1125            };
1126            match self_ref.compat.state {
1127                CompatState::Init | CompatState::No | CompatState::Dummy => Ok(self),
1128                CompatState::Full | CompatState::Partial => {
1129                    #[cfg(test)]
1130                    assert!(self_ref.fd.is_some());
1131                    let fd = self_ref.fd.as_ref().map(|f| f.as_raw_fd()).unwrap_or(-1);
1132                    match unsafe {
1133                        uapi::landlock_add_rule(
1134                            fd,
1135                            T::TYPE_ID,
1136                            compat_rule.as_ptr(),
1137                            compat_rule.add_rule_flags(),
1138                        )
1139                    } {
1140                        0 => Ok(self),
1141                        _ => Err(AddRuleError::<U>::AddRuleCall {
1142                            source: Error::last_os_error(),
1143                        }
1144                        .into()),
1145                    }
1146                }
1147            }
1148        };
1149        Ok(body()?)
1150    }
1151
1152    /// Attempts to add a set of new rules to the ruleset.
1153    ///
1154    /// On error, returns a (double) wrapped [`AddRulesError`].
1155    ///
1156    /// # Example
1157    ///
1158    /// Create a custom iterator to read paths from environment variable.
1159    ///
1160    /// ```
1161    /// use landlock::{
1162    ///     Access, AccessFs, BitFlags, PathBeneath, PathFd, PathFdError, RestrictionStatus, Ruleset,
1163    ///     RulesetAttr, RulesetCreatedAttr, RulesetError, ABI,
1164    /// };
1165    /// use std::env;
1166    /// use std::ffi::OsStr;
1167    /// use std::os::unix::ffi::{OsStrExt, OsStringExt};
1168    /// use thiserror::Error;
1169    ///
1170    /// #[derive(Debug, Error)]
1171    /// enum PathEnvError<'a> {
1172    ///     #[error(transparent)]
1173    ///     Ruleset(#[from] RulesetError),
1174    ///     #[error(transparent)]
1175    ///     AddRuleIter(#[from] PathFdError),
1176    ///     #[error("missing environment variable {0}")]
1177    ///     MissingVar(&'a str),
1178    /// }
1179    ///
1180    /// struct PathEnv {
1181    ///     paths: Vec<u8>,
1182    ///     access: BitFlags<AccessFs>,
1183    /// }
1184    ///
1185    /// impl PathEnv {
1186    ///     // env_var is the name of an environment variable
1187    ///     // containing paths requested to be allowed.
1188    ///     // Paths are separated with ":", e.g. "/bin:/lib:/usr:/proc".
1189    ///     // In case an empty string is provided,
1190    ///     // no restrictions are applied.
1191    ///     // `access` is the set of access rights allowed for each of the parsed paths.
1192    ///     fn new<'a>(
1193    ///         env_var: &'a str, access: BitFlags<AccessFs>
1194    ///     ) -> Result<Self, PathEnvError<'a>> {
1195    ///         Ok(Self {
1196    ///             paths: env::var_os(env_var)
1197    ///                 .ok_or(PathEnvError::MissingVar(env_var))?
1198    ///                 .into_vec(),
1199    ///             access,
1200    ///         })
1201    ///     }
1202    ///
1203    ///     fn iter(
1204    ///         &self,
1205    ///     ) -> impl Iterator<Item = Result<PathBeneath<PathFd>, PathEnvError<'static>>> + '_ {
1206    ///         let is_empty = self.paths.is_empty();
1207    ///         self.paths
1208    ///             .split(|b| *b == b':')
1209    ///             // Skips the first empty element from of an empty string.
1210    ///             .skip_while(move |_| is_empty)
1211    ///             .map(OsStr::from_bytes)
1212    ///             .map(move |path|
1213    ///                 Ok(PathBeneath::new(PathFd::new(path)?, self.access)))
1214    ///     }
1215    /// }
1216    ///
1217    /// fn restrict_env() -> Result<RestrictionStatus, PathEnvError<'static>> {
1218    ///     Ok(Ruleset::default()
1219    ///         .handle_access(AccessFs::from_all(ABI::V1))?
1220    ///         .create()?
1221    ///         // In the shell: export EXECUTABLE_PATH="/usr:/bin:/sbin"
1222    ///         .add_rules(PathEnv::new("EXECUTABLE_PATH", AccessFs::Execute.into())?.iter())?
1223    ///         .restrict_self()?)
1224    /// }
1225    /// ```
1226    fn add_rules<I, T, U, E>(mut self, rules: I) -> Result<Self, E>
1227    where
1228        I: IntoIterator<Item = Result<T, E>>,
1229        T: Rule<U>,
1230        U: HandledAccess + PrivateHandledAccess,
1231        E: From<RulesetError>,
1232    {
1233        for rule in rules {
1234            self = self.add_rule(rule?)?;
1235        }
1236        Ok(self)
1237    }
1238
1239    /// Configures the ruleset to call `prctl(2)` with the `PR_SET_NO_NEW_PRIVS` command
1240    /// in [`restrict_self()`](RulesetCreated::restrict_self).
1241    ///
1242    /// This `prctl(2)` call is never ignored, even if an error was encountered on a [`Ruleset`] or
1243    /// [`RulesetCreated`] method call while [`CompatLevel::SoftRequirement`] was set.
1244    fn no_new_privs(mut self, yes: bool) -> Self {
1245        <Self as AsMut<RulesetCreated>>::as_mut(&mut self).no_new_privs = yes;
1246        self
1247    }
1248
1249    /// Alias for [`no_new_privs()`](Self::no_new_privs).
1250    #[deprecated(note = "Use no_new_privs() instead.")]
1251    fn set_no_new_privs(self, yes: bool) -> Self {
1252        self.no_new_privs(yes)
1253    }
1254
1255    /// Controls logging of denied accesses for the creating thread and its children
1256    /// running the same executable (before `execve(2)`).
1257    /// Logging is **enabled** by default.  See
1258    /// [kernel documentation](https://docs.kernel.org/userspace-api/landlock.html#enforcing-a-ruleset).
1259    ///
1260    /// Calling with `false` sets the `LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF` flag.
1261    /// Calling with `true` is a no-op (the default behavior).
1262    ///
1263    /// This setter only applies when restricting with a domain.
1264    ///
1265    /// On error, returns a wrapped
1266    /// [`SyscallFlagError<RestrictSelfFlag>`](crate::SyscallFlagError).
1267    fn log_same_exec(mut self, set: bool) -> Result<Self, RulesetError> {
1268        self.try_set_flag(RestrictSelfFlag::LogSameExec, set)?;
1269        Ok(self)
1270    }
1271
1272    /// Controls logging of denied accesses after an `execve(2)` call.
1273    /// Logging is **disabled** by default.  See
1274    /// [kernel documentation](https://docs.kernel.org/userspace-api/landlock.html#enforcing-a-ruleset).
1275    ///
1276    /// Calling with `true` sets the `LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON` flag.
1277    /// Calling with `false` is a no-op (the default behavior).
1278    ///
1279    /// This setter only applies when restricting with a domain.
1280    ///
1281    /// On error, returns a wrapped
1282    /// [`SyscallFlagError<RestrictSelfFlag>`](crate::SyscallFlagError).
1283    fn log_new_exec(mut self, set: bool) -> Result<Self, RulesetError> {
1284        self.try_set_flag(RestrictSelfFlag::LogNewExec, set)?;
1285        Ok(self)
1286    }
1287}
1288
1289/// Ruleset created with [`Ruleset::create()`].
1290#[derive(Debug)]
1291pub struct RulesetCreated {
1292    fd: Option<OwnedFd>,
1293    no_new_privs: bool,
1294    pub(crate) fs: RulesetMasks<AccessFs, Requested>,
1295    pub(crate) net: RulesetMasks<AccessNet, Requested>,
1296    requested_restrict_self_flags: u32,
1297    actual_restrict_self_flags: u32,
1298    compat: Compatibility,
1299}
1300
1301impl RulesetCreated {
1302    pub(crate) fn new(ruleset: Ruleset, fd: Option<OwnedFd>) -> Self {
1303        // The compatibility state is initialized by Ruleset::create().
1304        #[cfg(test)]
1305        {
1306            assert!(!matches!(ruleset.compat.state, CompatState::Init));
1307            assert!(ruleset.fs.access.contains(ruleset.fs.quiet));
1308            assert!(ruleset.net.access.contains(ruleset.net.quiet));
1309        }
1310
1311        RulesetCreated {
1312            fd,
1313            no_new_privs: true,
1314            fs: ruleset.fs,
1315            net: ruleset.net,
1316            requested_restrict_self_flags: 0,
1317            actual_restrict_self_flags: 0,
1318            compat: ruleset.compat,
1319        }
1320    }
1321
1322    /// Attempts to restrict the calling thread with the ruleset
1323    /// according to the best-effort configuration
1324    /// (see [`RulesetCreated::set_compatibility()`] and [`CompatLevel::BestEffort`]).
1325    /// Call `prctl(2)` with the `PR_SET_NO_NEW_PRIVS`
1326    /// according to the ruleset configuration.
1327    ///
1328    /// On error, returns a wrapped [`RestrictSelfError`].
1329    pub fn restrict_self(mut self) -> Result<RestrictionStatus, RulesetError> {
1330        let mut body = || -> Result<RestrictionStatus, RestrictSelfError> {
1331            // Enforce no_new_privs even if something failed with SoftRequirement. The rationale is
1332            // that no_new_privs should not be an issue on its own if it is not explicitly
1333            // deactivated.
1334            let enforced_nnp = if self.no_new_privs {
1335                try_set_no_new_privs(&mut self.compat)?
1336            } else {
1337                false
1338            };
1339
1340            let raw = self.actual_restrict_self_flags;
1341            let log_same_exec = RestrictSelfFlag::LogSameExec.is_set(raw);
1342            let log_new_exec = RestrictSelfFlag::LogNewExec.is_set(raw);
1343            let log_subdomains = RestrictSelfFlag::LogSubdomains.is_set(raw);
1344            let all_threads = RestrictSelfFlag::AllThreads.is_set(raw);
1345
1346            match self.compat.state {
1347                CompatState::Init | CompatState::No | CompatState::Dummy => Ok(RestrictionStatus {
1348                    ruleset: self.compat.state.into(),
1349                    landlock: self.compat.status(),
1350                    no_new_privs: enforced_nnp,
1351                    log_same_exec,
1352                    log_new_exec,
1353                    log_subdomains,
1354                    all_threads,
1355                }),
1356                CompatState::Full | CompatState::Partial => {
1357                    #[cfg(test)]
1358                    assert!(self.fd.is_some());
1359                    // Does not consume ruleset FD, which will be automatically closed after this block.
1360                    let fd = self.fd.as_ref().map(|f| f.as_raw_fd()).unwrap_or(-1);
1361                    match unsafe {
1362                        uapi::landlock_restrict_self(fd, self.actual_restrict_self_flags)
1363                    } {
1364                        0 => {
1365                            self.compat.update(CompatState::Full);
1366                            Ok(RestrictionStatus {
1367                                ruleset: self.compat.state.into(),
1368                                landlock: self.compat.status(),
1369                                no_new_privs: enforced_nnp,
1370                                log_same_exec,
1371                                log_new_exec,
1372                                log_subdomains,
1373                                all_threads,
1374                            })
1375                        }
1376                        // TODO: match specific Landlock restrict self errors
1377                        _ => Err(RestrictSelfError::RestrictSelfCall {
1378                            source: Error::last_os_error(),
1379                        }),
1380                    }
1381                }
1382            }
1383        };
1384        Ok(body()?)
1385    }
1386
1387    /// Creates a new `RulesetCreated` instance by duplicating the underlying file descriptor.
1388    /// Rule modification will affect both `RulesetCreated` instances simultaneously.
1389    ///
1390    /// On error, returns [`std::io::Error`].
1391    pub fn try_clone(&self) -> std::io::Result<Self> {
1392        Ok(RulesetCreated {
1393            fd: self.fd.as_ref().map(|f| f.try_clone()).transpose()?,
1394            no_new_privs: self.no_new_privs,
1395            fs: self.fs,
1396            net: self.net,
1397            requested_restrict_self_flags: self.requested_restrict_self_flags,
1398            actual_restrict_self_flags: self.actual_restrict_self_flags,
1399            compat: self.compat,
1400        })
1401    }
1402}
1403
1404impl From<RulesetCreated> for Option<OwnedFd> {
1405    fn from(ruleset: RulesetCreated) -> Self {
1406        ruleset.fd
1407    }
1408}
1409
1410#[test]
1411fn ruleset_created_ownedfd_none() {
1412    let ruleset = Ruleset::from(ABI::Unsupported)
1413        .handle_access(AccessFs::Execute)
1414        .unwrap()
1415        .create()
1416        .unwrap();
1417    let fd: Option<OwnedFd> = ruleset.into();
1418    assert!(fd.is_none());
1419}
1420
1421impl AsMut<RulesetCreated> for RulesetCreated {
1422    fn as_mut(&mut self) -> &mut RulesetCreated {
1423        self
1424    }
1425}
1426
1427impl RulesetCreatedAttr for RulesetCreated {}
1428
1429impl RulesetCreatedAttr for &mut RulesetCreated {}
1430
1431#[test]
1432fn ruleset_created_attr() {
1433    let mut ruleset_created = Ruleset::from(ABI::Unsupported)
1434        .handle_access(AccessFs::Execute)
1435        .unwrap()
1436        .create()
1437        .unwrap();
1438    let ruleset_created_ref = &mut ruleset_created;
1439
1440    // Can pass this reference to populate the ruleset...
1441    ruleset_created_ref
1442        .set_compatibility(CompatLevel::BestEffort)
1443        .add_rule(PathBeneath::new(
1444            PathFd::new("/usr").unwrap(),
1445            AccessFs::Execute,
1446        ))
1447        .unwrap()
1448        .add_rule(PathBeneath::new(
1449            PathFd::new("/etc").unwrap(),
1450            AccessFs::Execute,
1451        ))
1452        .unwrap();
1453
1454    // ...and finally restrict with the last rules (thanks to non-lexical lifetimes).
1455    assert_eq!(
1456        ruleset_created
1457            .set_compatibility(CompatLevel::BestEffort)
1458            .add_rule(PathBeneath::new(
1459                PathFd::new("/tmp").unwrap(),
1460                AccessFs::Execute,
1461            ))
1462            .unwrap()
1463            .add_rule(PathBeneath::new(
1464                PathFd::new("/var").unwrap(),
1465                AccessFs::Execute,
1466            ))
1467            .unwrap()
1468            .restrict_self()
1469            .unwrap(),
1470        RestrictionStatus {
1471            ruleset: RulesetStatus::NotEnforced,
1472            landlock: LandlockStatus::NotImplemented,
1473            no_new_privs: true,
1474            log_same_exec: true,
1475            log_new_exec: false,
1476            log_subdomains: true,
1477            all_threads: false,
1478        }
1479    );
1480}
1481
1482#[test]
1483fn ruleset_compat_dummy() {
1484    for level in [CompatLevel::BestEffort, CompatLevel::SoftRequirement] {
1485        println!("level: {:?}", level);
1486
1487        // ABI:Unsupported does not support AccessFs::Execute.
1488        let ruleset = Ruleset::from(ABI::Unsupported);
1489        assert_eq!(ruleset.compat.state, CompatState::Init);
1490
1491        let ruleset = ruleset.set_compatibility(level);
1492        assert_eq!(ruleset.compat.state, CompatState::Init);
1493
1494        let ruleset = ruleset.handle_access(AccessFs::Execute).unwrap();
1495        assert_eq!(
1496            ruleset.compat.state,
1497            match level {
1498                CompatLevel::BestEffort => CompatState::No,
1499                CompatLevel::SoftRequirement => CompatState::Dummy,
1500                _ => unreachable!(),
1501            }
1502        );
1503
1504        let ruleset_created = ruleset.create().unwrap();
1505        // Because the compatibility state was either No or Dummy, calling create() updates it to
1506        // Dummy.
1507        assert_eq!(ruleset_created.compat.state, CompatState::Dummy);
1508
1509        let ruleset_created = ruleset_created
1510            .add_rule(PathBeneath::new(
1511                PathFd::new("/usr").unwrap(),
1512                AccessFs::Execute,
1513            ))
1514            .unwrap();
1515        assert_eq!(ruleset_created.compat.state, CompatState::Dummy);
1516    }
1517}
1518
1519#[test]
1520fn ruleset_compat_partial() {
1521    // CompatLevel::BestEffort
1522    let ruleset = Ruleset::from(ABI::V1);
1523    assert_eq!(ruleset.compat.state, CompatState::Init);
1524
1525    // ABI::V1 does not support AccessFs::Refer.
1526    let ruleset = ruleset.handle_access(AccessFs::Refer).unwrap();
1527    assert_eq!(ruleset.compat.state, CompatState::No);
1528
1529    let ruleset = ruleset.handle_access(AccessFs::Execute).unwrap();
1530    assert_eq!(ruleset.compat.state, CompatState::Partial);
1531
1532    // Requesting to handle another unsupported handled access does not change anything.
1533    let ruleset = ruleset.handle_access(AccessFs::Refer).unwrap();
1534    assert_eq!(ruleset.compat.state, CompatState::Partial);
1535}
1536
1537#[test]
1538fn ruleset_unsupported() {
1539    assert_eq!(
1540        Ruleset::from(ABI::Unsupported)
1541            // BestEffort for Ruleset.
1542            .handle_access(AccessFs::Execute)
1543            .unwrap()
1544            .create()
1545            .unwrap()
1546            .restrict_self()
1547            .unwrap(),
1548        RestrictionStatus {
1549            ruleset: RulesetStatus::NotEnforced,
1550            landlock: LandlockStatus::NotImplemented,
1551            // With BestEffort, no_new_privs is still enabled.
1552            no_new_privs: true,
1553            log_same_exec: true,
1554            log_new_exec: false,
1555            log_subdomains: true,
1556            all_threads: false,
1557        }
1558    );
1559
1560    assert_eq!(
1561        Ruleset::from(ABI::Unsupported)
1562            // SoftRequirement for Ruleset.
1563            .set_compatibility(CompatLevel::SoftRequirement)
1564            .handle_access(AccessFs::Execute)
1565            .unwrap()
1566            .create()
1567            .unwrap()
1568            .restrict_self()
1569            .unwrap(),
1570        RestrictionStatus {
1571            ruleset: RulesetStatus::NotEnforced,
1572            landlock: LandlockStatus::NotImplemented,
1573            // With SoftRequirement, no_new_privs is still enabled.
1574            no_new_privs: true,
1575            log_same_exec: true,
1576            log_new_exec: false,
1577            log_subdomains: true,
1578            all_threads: false,
1579        }
1580    );
1581
1582    // Incompatible handled access because of the compatibility level.
1583    assert!(matches!(
1584        Ruleset::from(ABI::Unsupported)
1585            // HardRequirement for Ruleset.
1586            .set_compatibility(CompatLevel::HardRequirement)
1587            .handle_access(AccessFs::Execute)
1588            .unwrap_err(),
1589        RulesetError::HandleAccesses(HandleAccessesError::Fs(HandleAccessError::Compat(
1590            CompatError::Access(AccessError::Incompatible { .. })
1591        )))
1592    ));
1593
1594    // Incompatible scope because of the compatibility level.
1595    assert!(matches!(
1596        Ruleset::from(ABI::Unsupported)
1597            // HardRequirement for Ruleset.
1598            .set_compatibility(CompatLevel::HardRequirement)
1599            .scope(Scope::Signal)
1600            .unwrap_err(),
1601        RulesetError::Scope(ScopeError::Compat(CompatError::Access(
1602            AccessError::Incompatible { .. }
1603        )))
1604    ));
1605
1606    assert_eq!(
1607        Ruleset::from(ABI::Unsupported)
1608            .handle_access(AccessFs::Execute)
1609            .unwrap()
1610            .create()
1611            .unwrap()
1612            // SoftRequirement for RulesetCreated without any rule.
1613            .set_compatibility(CompatLevel::SoftRequirement)
1614            .restrict_self()
1615            .unwrap(),
1616        RestrictionStatus {
1617            ruleset: RulesetStatus::NotEnforced,
1618            landlock: LandlockStatus::NotImplemented,
1619            // With SoftRequirement, no_new_privs is untouched if there is no error (e.g. no rule).
1620            no_new_privs: true,
1621            log_same_exec: true,
1622            log_new_exec: false,
1623            log_subdomains: true,
1624            all_threads: false,
1625        }
1626    );
1627
1628    // Don't explicitly call create() on a CI that doesn't support Landlock.
1629    if compat::can_emulate(ABI::V1, ABI::V1, Some(ABI::V2)) {
1630        assert_eq!(
1631            Ruleset::from(ABI::V1)
1632                .handle_access(make_bitflags!(AccessFs::{Execute | Refer}))
1633                .unwrap()
1634                .create()
1635                .unwrap()
1636                // SoftRequirement for RulesetCreated with a rule.
1637                .set_compatibility(CompatLevel::SoftRequirement)
1638                .add_rule(PathBeneath::new(PathFd::new("/").unwrap(), AccessFs::Refer))
1639                .unwrap()
1640                .restrict_self()
1641                .unwrap(),
1642            RestrictionStatus {
1643                ruleset: RulesetStatus::NotEnforced,
1644                landlock: LandlockStatus::Available {
1645                    effective_abi: ABI::V1,
1646                    kernel_abi: None,
1647                },
1648                // With SoftRequirement, no_new_privs is still enabled, even if there is an error
1649                // (e.g. unsupported access right).
1650                no_new_privs: true,
1651                log_same_exec: true,
1652                log_new_exec: false,
1653                log_subdomains: true,
1654                all_threads: false,
1655            }
1656        );
1657    }
1658
1659    assert_eq!(
1660        Ruleset::from(ABI::Unsupported)
1661            .handle_access(AccessFs::Execute)
1662            .unwrap()
1663            .create()
1664            .unwrap()
1665            .no_new_privs(false)
1666            .restrict_self()
1667            .unwrap(),
1668        RestrictionStatus {
1669            ruleset: RulesetStatus::NotEnforced,
1670            landlock: LandlockStatus::NotImplemented,
1671            no_new_privs: false,
1672            log_same_exec: true,
1673            log_new_exec: false,
1674            log_subdomains: true,
1675            all_threads: false,
1676        }
1677    );
1678
1679    // Checks empty handled access with moot ruleset.
1680    assert!(matches!(
1681        Ruleset::from(ABI::Unsupported)
1682            // Empty access-rights
1683            .handle_access(AccessFs::from_all(ABI::Unsupported))
1684            .unwrap_err(),
1685        RulesetError::HandleAccesses(HandleAccessesError::Fs(HandleAccessError::Compat(
1686            CompatError::Access(AccessError::Empty)
1687        )))
1688    ));
1689
1690    assert!(matches!(
1691        Ruleset::from(ABI::Unsupported)
1692            // No handle_access() nor scope() call.
1693            .create()
1694            .unwrap_err(),
1695        RulesetError::CreateRuleset(CreateRulesetError::MissingHandledAccess)
1696    ));
1697
1698    // Checks empty handled access with minimal ruleset.
1699    assert!(matches!(
1700        Ruleset::from(ABI::V1)
1701            // Empty access-rights
1702            .handle_access(AccessFs::from_all(ABI::Unsupported))
1703            .unwrap_err(),
1704        RulesetError::HandleAccesses(HandleAccessesError::Fs(HandleAccessError::Compat(
1705            CompatError::Access(AccessError::Empty)
1706        )))
1707    ));
1708
1709    // Checks empty scope with moot ruleset.
1710    assert!(matches!(
1711        Ruleset::from(ABI::Unsupported)
1712            .scope(Scope::from_all(ABI::Unsupported))
1713            .unwrap_err(),
1714        RulesetError::Scope(ScopeError::Compat(CompatError::Access(AccessError::Empty)))
1715    ));
1716
1717    // Checks empty scope with minimal ruleset.
1718    assert!(matches!(
1719        Ruleset::from(ABI::V1)
1720            .scope(Scope::from_all(ABI::Unsupported))
1721            .unwrap_err(),
1722        RulesetError::Scope(ScopeError::Compat(CompatError::Access(AccessError::Empty)))
1723    ));
1724
1725    // Scope with SoftRequirement on unsupported ABI: silently dropped, state becomes Dummy.
1726    let ruleset = Ruleset::from(ABI::V1)
1727        .handle_access(AccessFs::Execute)
1728        .unwrap()
1729        .set_compatibility(CompatLevel::SoftRequirement)
1730        .scope(Scope::Signal)
1731        .unwrap();
1732    assert_eq!(ruleset.scoped.access, BitFlags::from(Scope::Signal));
1733    assert_eq!(
1734        ruleset.scoped.resolve(ruleset.compat.abi()).access,
1735        BitFlags::<Scope>::EMPTY
1736    );
1737
1738    // Log flags with BestEffort on unsupported ABI are silently ignored.
1739    assert_eq!(
1740        Ruleset::from(ABI::Unsupported)
1741            .handle_access(AccessFs::Execute)
1742            .unwrap()
1743            .create()
1744            .unwrap()
1745            .log_same_exec(false)
1746            .unwrap()
1747            .restrict_self()
1748            .unwrap(),
1749        RestrictionStatus {
1750            ruleset: RulesetStatus::NotEnforced,
1751            landlock: LandlockStatus::NotImplemented,
1752            no_new_privs: true,
1753            log_same_exec: true,
1754            log_new_exec: false,
1755            log_subdomains: true,
1756            all_threads: false,
1757        }
1758    );
1759
1760    // Log flags with HardRequirement on unsupported ABI return an error.
1761    assert!(matches!(
1762        Ruleset::from(ABI::Unsupported)
1763            .handle_access(AccessFs::Execute)
1764            .unwrap()
1765            .create()
1766            .unwrap()
1767            .set_compatibility(CompatLevel::HardRequirement)
1768            .log_new_exec(true)
1769            .unwrap_err(),
1770        RulesetError::RestrictSelfFlags(SyscallFlagError::NotSupported {
1771            flag: RestrictSelfFlag::LogNewExec,
1772            set: true,
1773        })
1774    ));
1775
1776    // Tests inconsistency between the ruleset handled access-rights and the rule access-rights.
1777    for handled_access in &[
1778        make_bitflags!(AccessFs::{Execute | WriteFile}),
1779        AccessFs::Execute.into(),
1780    ] {
1781        let ruleset = Ruleset::from(ABI::V1)
1782            .handle_access(*handled_access)
1783            .unwrap();
1784        // Fakes a call to create() to test without involving the kernel (i.e. no
1785        // landlock_ruleset_create() call).
1786        let ruleset_created = RulesetCreated::new(ruleset, None);
1787        assert!(matches!(
1788            ruleset_created
1789                .add_rule(PathBeneath::new(
1790                    PathFd::new("/").unwrap(),
1791                    AccessFs::ReadFile
1792                ))
1793                .unwrap_err(),
1794            RulesetError::AddRules(AddRulesError::Fs(AddRuleError::UnhandledAccess { .. }))
1795        ));
1796    }
1797}
1798
1799#[test]
1800fn ignore_abi_v2_with_abi_v1() {
1801    // We don't need kernel/CI support for Landlock because no related syscalls should actually be
1802    // performed.
1803    assert_eq!(
1804        Ruleset::from(ABI::V1)
1805            .set_compatibility(CompatLevel::HardRequirement)
1806            .handle_access(AccessFs::from_all(ABI::V1))
1807            .unwrap()
1808            .set_compatibility(CompatLevel::SoftRequirement)
1809            // Because Ruleset only supports V1, Refer will be ignored.
1810            .handle_access(AccessFs::Refer)
1811            .unwrap()
1812            .create()
1813            .unwrap()
1814            .add_rule(PathBeneath::new(
1815                PathFd::new("/tmp").unwrap(),
1816                AccessFs::from_all(ABI::V2)
1817            ))
1818            .unwrap()
1819            .add_rule(PathBeneath::new(
1820                PathFd::new("/usr").unwrap(),
1821                make_bitflags!(AccessFs::{ReadFile | ReadDir})
1822            ))
1823            .unwrap()
1824            .restrict_self()
1825            .unwrap(),
1826        RestrictionStatus {
1827            ruleset: RulesetStatus::NotEnforced,
1828            landlock: LandlockStatus::Available {
1829                effective_abi: ABI::V1,
1830                kernel_abi: None,
1831            },
1832            no_new_privs: true,
1833            log_same_exec: true,
1834            log_new_exec: false,
1835            log_subdomains: true,
1836            all_threads: false,
1837        }
1838    );
1839}
1840
1841#[test]
1842fn unsupported_handled_access() {
1843    assert!(matches!(
1844        Ruleset::from(ABI::V3)
1845            .handle_access(AccessNet::from_all(ABI::V3))
1846            .unwrap_err(),
1847        RulesetError::HandleAccesses(HandleAccessesError::Net(HandleAccessError::Compat(
1848            CompatError::Access(AccessError::Empty)
1849        )))
1850    ));
1851}
1852
1853#[test]
1854fn unsupported_handled_access_errno() {
1855    assert_eq!(
1856        Errno::from(
1857            Ruleset::from(ABI::V3)
1858                .handle_access(AccessNet::from_all(ABI::V3))
1859                .unwrap_err()
1860        ),
1861        Errno::new(libc::EINVAL)
1862    );
1863}