Skip to main content

landlock/
errors.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2
3use crate::{
4    Access, AccessFs, AccessNet, BitFlags, HandledAccess, PrivateHandledAccess, RestrictSelfFlag,
5    Scope, SyscallFlag,
6};
7use libc::c_int;
8use std::io;
9use std::path::PathBuf;
10use thiserror::Error;
11
12/// Maps to all errors that can be returned by a ruleset action.
13#[derive(Debug, Error)]
14#[non_exhaustive]
15pub enum RulesetError {
16    #[error(transparent)]
17    HandleAccesses(#[from] HandleAccessesError),
18    #[error(transparent)]
19    CreateRuleset(#[from] CreateRulesetError),
20    #[error(transparent)]
21    AddRules(#[from] AddRulesError),
22    #[error(transparent)]
23    RestrictSelf(#[from] RestrictSelfError),
24    #[error(transparent)]
25    Scope(#[from] ScopeError),
26    /// Error configuring flags passed to `landlock_restrict_self(2)`.
27    /// Distinct from [`Self::RestrictSelf`], which wraps errors from
28    /// the syscall itself (e.g., EINVAL on an unsupported kernel).
29    #[error(transparent)]
30    RestrictSelfFlags(#[from] SyscallFlagError<RestrictSelfFlag>),
31}
32
33#[test]
34fn ruleset_error_breaking_change() {
35    use crate::*;
36
37    // Generics are part of the API and modifying them can lead to a breaking change.
38    let _: RulesetError = RulesetError::HandleAccesses(HandleAccessesError::Fs(
39        HandleAccessError::Compat(CompatError::Access(AccessError::Empty)),
40    ));
41}
42
43/// Identifies errors when updating the ruleset's handled access-rights.
44#[derive(Debug, Error)]
45#[non_exhaustive]
46pub enum HandleAccessError<T>
47where
48    T: HandledAccess,
49{
50    #[error(transparent)]
51    Compat(#[from] CompatError<T>),
52}
53
54/// Identifies errors when updating the ruleset's scopes.
55#[derive(Debug, Error)]
56#[non_exhaustive]
57pub enum ScopeError {
58    #[error(transparent)]
59    Compat(#[from] CompatError<Scope>),
60}
61
62/// Identifies errors when configuring a syscall flag.
63///
64/// Generic over the flag type to support different syscall flag categories.
65/// Each flag type implements [`SyscallFlag`].
66#[derive(Debug, Error)]
67#[non_exhaustive]
68pub enum SyscallFlagError<F: SyscallFlag> {
69    /// The requested flag configuration is not supported by the running kernel.
70    #[error("unsupported syscall flag: {flag:?} set to {set}")]
71    #[non_exhaustive]
72    NotSupported { flag: F, set: bool },
73}
74
75#[derive(Debug, Error)]
76#[non_exhaustive]
77pub enum HandleAccessesError {
78    #[error(transparent)]
79    Fs(HandleAccessError<AccessFs>),
80    #[error(transparent)]
81    Net(HandleAccessError<AccessNet>),
82}
83
84// Generically implement for all the handled access implementations rather than for the cases
85// listed in HandleAccessesError (with #[from]).
86impl<A> From<HandleAccessError<A>> for HandleAccessesError
87where
88    A: PrivateHandledAccess,
89{
90    fn from(error: HandleAccessError<A>) -> Self {
91        A::into_handle_accesses_error(error)
92    }
93}
94
95/// Identifies errors when creating a ruleset.
96#[derive(Debug, Error)]
97#[non_exhaustive]
98pub enum CreateRulesetError {
99    /// The `landlock_create_ruleset()` system call failed.
100    #[error("failed to create a ruleset: {source}")]
101    #[non_exhaustive]
102    CreateRulesetCall { source: io::Error },
103    /// Missing call to [`RulesetAttr::handle_access()`](crate::RulesetAttr::handle_access)
104    /// or [`RulesetAttr::scope()`](crate::RulesetAttr::scope).
105    #[error("missing access")]
106    MissingHandledAccess,
107    /// Filesystem accesses selected for quieting are not all handled by the ruleset.
108    #[error("quiet filesystem access-rights not handled by the ruleset: {incompatible:?}")]
109    #[non_exhaustive]
110    UnhandledQuietAccessFs {
111        access: BitFlags<AccessFs>,
112        incompatible: BitFlags<AccessFs>,
113    },
114    /// Network accesses selected for quieting are not all handled by the ruleset.
115    #[error("quiet network access-rights not handled by the ruleset: {incompatible:?}")]
116    #[non_exhaustive]
117    UnhandledQuietAccessNet {
118        access: BitFlags<AccessNet>,
119        incompatible: BitFlags<AccessNet>,
120    },
121    /// Scopes selected for quieting are not all configured by the ruleset.
122    #[error("quiet scopes not configured by the ruleset: {incompatible:?}")]
123    #[non_exhaustive]
124    UnhandledQuietScope {
125        access: BitFlags<Scope>,
126        incompatible: BitFlags<Scope>,
127    },
128}
129
130/// Identifies errors when adding a rule to a ruleset.
131#[derive(Debug, Error)]
132#[non_exhaustive]
133pub enum AddRuleError<T>
134where
135    T: HandledAccess,
136{
137    /// The `landlock_add_rule()` system call failed.
138    #[error("failed to add a rule: {source}")]
139    #[non_exhaustive]
140    AddRuleCall { source: io::Error },
141    /// The rule's access-rights are not all handled by the (requested) ruleset access-rights.
142    #[error("access-rights not handled by the ruleset: {incompatible:?}")]
143    UnhandledAccess {
144        access: BitFlags<T>,
145        incompatible: BitFlags<T>,
146    },
147    /// The rule is marked quiet, but its ruleset has no quiet access mask for this rule category.
148    #[error("missing quiet access mask for rule category")]
149    MissingQuietAccess,
150    #[error(transparent)]
151    Compat(#[from] CompatError<T>),
152}
153
154// Generically implement for all the handled access implementations rather than for the cases listed
155// in AddRulesError (with #[from]).
156impl<A> From<AddRuleError<A>> for AddRulesError
157where
158    A: PrivateHandledAccess,
159{
160    fn from(error: AddRuleError<A>) -> Self {
161        A::into_add_rules_error(error)
162    }
163}
164
165/// Identifies errors when adding rules to a ruleset thanks to an iterator returning
166/// Result<Rule, E> items.
167#[derive(Debug, Error)]
168#[non_exhaustive]
169pub enum AddRulesError {
170    #[error(transparent)]
171    Fs(AddRuleError<AccessFs>),
172    #[error(transparent)]
173    Net(AddRuleError<AccessNet>),
174}
175
176#[derive(Debug, Error)]
177#[non_exhaustive]
178pub enum CompatError<T>
179where
180    T: Access,
181{
182    #[error(transparent)]
183    PathBeneath(#[from] PathBeneathError),
184    #[error(transparent)]
185    Access(#[from] AccessError<T>),
186    /// Quiet access masks or quiet rules are not supported by the running kernel.
187    #[error("quiet access is not supported by the kernel")]
188    QuietNotSupported,
189}
190
191#[derive(Debug, Error)]
192#[non_exhaustive]
193pub enum PathBeneathError {
194    /// To check that access-rights are consistent with a file descriptor, a call to
195    /// [`RulesetCreatedAttr::add_rule()`](crate::RulesetCreatedAttr::add_rule)
196    /// looks at the file type with an `fstat()` system call.
197    #[error("failed to check file descriptor type: {source}")]
198    #[non_exhaustive]
199    StatCall { source: io::Error },
200    /// This error is returned by
201    /// [`RulesetCreatedAttr::add_rule()`](crate::RulesetCreatedAttr::add_rule)
202    /// if the related PathBeneath object is not set to best-effort,
203    /// and if its allowed access-rights contain directory-only ones
204    /// whereas the file descriptor doesn't point to a directory.
205    #[error("incompatible directory-only access-rights: {incompatible:?}")]
206    DirectoryAccess {
207        access: BitFlags<AccessFs>,
208        incompatible: BitFlags<AccessFs>,
209    },
210}
211
212#[derive(Debug, Error)]
213// Exhaustive enum
214pub enum AccessError<T>
215where
216    T: Access,
217{
218    /// The access-rights set is empty, which doesn't make sense and would be rejected by the
219    /// kernel.
220    #[error("empty access-right")]
221    Empty,
222    /// The access-rights set was forged with the unsafe `BitFlags::from_bits_unchecked()` and it
223    /// contains unknown bits.
224    #[error("unknown access-rights (at build time): {unknown:?}")]
225    Unknown {
226        access: BitFlags<T>,
227        unknown: BitFlags<T>,
228    },
229    /// The best-effort approach was (deliberately) disabled and the requested access-rights are
230    /// fully incompatible with the running kernel.
231    #[error("fully incompatible access-rights: {access:?}")]
232    Incompatible { access: BitFlags<T> },
233    /// The best-effort approach was (deliberately) disabled and the requested access-rights are
234    /// partially incompatible with the running kernel.
235    #[error("partially incompatible access-rights: {incompatible:?}")]
236    PartiallyCompatible {
237        access: BitFlags<T>,
238        incompatible: BitFlags<T>,
239    },
240}
241
242#[derive(Debug, Error)]
243#[non_exhaustive]
244pub enum RestrictSelfError {
245    /// The `prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)` system call failed.
246    #[error("failed to set no_new_privs: {source}")]
247    #[non_exhaustive]
248    SetNoNewPrivsCall { source: io::Error },
249    /// The `landlock_restrict_self() `system call failed.
250    #[error("failed to restrict the calling thread: {source}")]
251    #[non_exhaustive]
252    RestrictSelfCall { source: io::Error },
253}
254
255#[derive(Debug, Error)]
256#[non_exhaustive]
257pub enum PathFdError {
258    /// The `open()` system call failed.
259    #[error("failed to open \"{path}\": {source}")]
260    #[non_exhaustive]
261    OpenCall { source: io::Error, path: PathBuf },
262}
263
264#[cfg(test)]
265#[derive(Debug, Error)]
266pub(crate) enum TestRulesetError {
267    #[error(transparent)]
268    Ruleset(#[from] RulesetError),
269    #[error(transparent)]
270    PathFd(#[from] PathFdError),
271    #[error(transparent)]
272    File(#[from] std::io::Error),
273}
274
275/// Get the underlying errno value.
276///
277/// This helper is useful for FFI to easily translate a Landlock error into an
278/// errno value.
279#[derive(Debug, PartialEq, Eq)]
280pub struct Errno(c_int);
281
282impl Errno {
283    pub fn new(value: c_int) -> Self {
284        Self(value)
285    }
286}
287
288impl<T> From<T> for Errno
289where
290    T: std::error::Error,
291{
292    fn from(error: T) -> Self {
293        let default = libc::EINVAL;
294        if let Some(e) = error.source() {
295            if let Some(e) = e.downcast_ref::<std::io::Error>() {
296                return Errno(e.raw_os_error().unwrap_or(default));
297            }
298        }
299        Errno(default)
300    }
301}
302
303impl std::ops::Deref for Errno {
304    type Target = c_int;
305
306    fn deref(&self) -> &Self::Target {
307        &self.0
308    }
309}
310
311#[cfg(test)]
312fn _test_ruleset_errno(expected_errno: c_int) {
313    use std::io::Error;
314
315    let handle_access_err = RulesetError::HandleAccesses(HandleAccessesError::Fs(
316        HandleAccessError::Compat(CompatError::Access(AccessError::Empty)),
317    ));
318    assert_eq!(*Errno::from(handle_access_err), libc::EINVAL);
319
320    let create_ruleset_err = RulesetError::CreateRuleset(CreateRulesetError::CreateRulesetCall {
321        source: Error::from_raw_os_error(expected_errno),
322    });
323    assert_eq!(*Errno::from(create_ruleset_err), expected_errno);
324
325    let add_rules_fs_err = RulesetError::AddRules(AddRulesError::Fs(AddRuleError::AddRuleCall {
326        source: Error::from_raw_os_error(expected_errno),
327    }));
328    assert_eq!(*Errno::from(add_rules_fs_err), expected_errno);
329
330    let add_rules_net_err = RulesetError::AddRules(AddRulesError::Net(AddRuleError::AddRuleCall {
331        source: Error::from_raw_os_error(expected_errno),
332    }));
333    assert_eq!(*Errno::from(add_rules_net_err), expected_errno);
334
335    let add_rules_other_err =
336        RulesetError::AddRules(AddRulesError::Fs(AddRuleError::UnhandledAccess {
337            access: AccessFs::Execute.into(),
338            incompatible: BitFlags::<AccessFs>::EMPTY,
339        }));
340    assert_eq!(*Errno::from(add_rules_other_err), libc::EINVAL);
341
342    let restrict_self_err = RulesetError::RestrictSelf(RestrictSelfError::RestrictSelfCall {
343        source: Error::from_raw_os_error(expected_errno),
344    });
345    assert_eq!(*Errno::from(restrict_self_err), expected_errno);
346
347    let set_no_new_privs_err = RulesetError::RestrictSelf(RestrictSelfError::SetNoNewPrivsCall {
348        source: Error::from_raw_os_error(expected_errno),
349    });
350    assert_eq!(*Errno::from(set_no_new_privs_err), expected_errno);
351
352    let create_ruleset_missing_err =
353        RulesetError::CreateRuleset(CreateRulesetError::MissingHandledAccess);
354    assert_eq!(*Errno::from(create_ruleset_missing_err), libc::EINVAL);
355
356    let create_ruleset_quiet_fs_err =
357        RulesetError::CreateRuleset(CreateRulesetError::UnhandledQuietAccessFs {
358            access: AccessFs::Execute.into(),
359            incompatible: AccessFs::Execute.into(),
360        });
361    assert_eq!(*Errno::from(create_ruleset_quiet_fs_err), libc::EINVAL);
362
363    let create_ruleset_quiet_net_err =
364        RulesetError::CreateRuleset(CreateRulesetError::UnhandledQuietAccessNet {
365            access: AccessNet::BindTcp.into(),
366            incompatible: AccessNet::BindTcp.into(),
367        });
368    assert_eq!(*Errno::from(create_ruleset_quiet_net_err), libc::EINVAL);
369
370    let create_ruleset_quiet_scope_err =
371        RulesetError::CreateRuleset(CreateRulesetError::UnhandledQuietScope {
372            access: Scope::Signal.into(),
373            incompatible: Scope::Signal.into(),
374        });
375    assert_eq!(*Errno::from(create_ruleset_quiet_scope_err), libc::EINVAL);
376
377    let add_rules_quiet_err =
378        RulesetError::AddRules(AddRulesError::Fs(AddRuleError::MissingQuietAccess));
379    assert_eq!(*Errno::from(add_rules_quiet_err), libc::EINVAL);
380
381    let quiet_compat_err = RulesetError::HandleAccesses(HandleAccessesError::Fs(
382        HandleAccessError::Compat(CompatError::<AccessFs>::QuietNotSupported),
383    ));
384    assert_eq!(*Errno::from(quiet_compat_err), libc::EINVAL);
385
386    let restrict_self_flags_err = RulesetError::RestrictSelfFlags(SyscallFlagError::NotSupported {
387        flag: RestrictSelfFlag::LogSameExec,
388        set: false,
389    });
390    assert_eq!(*Errno::from(restrict_self_flags_err), libc::EINVAL);
391}
392
393#[test]
394fn test_ruleset_errno() {
395    _test_ruleset_errno(libc::EACCES);
396    _test_ruleset_errno(libc::EIO);
397}