landlock/compat.rs
1// SPDX-License-Identifier: Apache-2.0 OR MIT
2
3use crate::{uapi, Access, CompatError};
4use std::fmt::{self, Display, Formatter};
5use std::io::Error;
6
7#[cfg(test)]
8use std::convert::TryInto;
9#[cfg(test)]
10use strum::{EnumCount, IntoEnumIterator};
11#[cfg(test)]
12use strum_macros::{EnumCount as EnumCountMacro, EnumIter};
13
14/// Version of the Landlock [ABI](https://en.wikipedia.org/wiki/Application_binary_interface).
15///
16/// `ABI` enables getting the features supported by a specific Landlock ABI
17/// (without relying on the kernel version which may not be accessible or patched).
18/// For example, [`AccessFs::from_all(ABI::V1)`](Access::from_all)
19/// gets all the file system access rights defined by the first version.
20///
21/// Without `ABI`, it would be hazardous to rely on the the full set of access flags
22/// (e.g., `BitFlags::<AccessFs>::all()` or `BitFlags::ALL`),
23/// a moving target that would change the semantics of your Landlock rule
24/// when migrating to a newer version of this crate.
25/// Indeed, a simple `cargo update` or `cargo install` run by any developer
26/// can result in a new version of this crate (fixing bugs or bringing non-breaking changes).
27/// This crate cannot give any guarantee concerning the new restrictions resulting from
28/// these unknown bits (i.e. access rights) that would not be controlled by your application but by
29/// a future version of this crate instead.
30/// Because we cannot know what the effect on your application of an unknown restriction would be
31/// when handling an untested Landlock access right (i.e. denied-by-default access),
32/// it could trigger bugs in your application.
33///
34/// This crate provides a set of tools to sandbox as much as possible
35/// while guaranteeing a consistent behavior thanks to the [`Compatible`] methods.
36/// You should also test with different relevant kernel versions,
37/// see [landlock-test-tools](https://github.com/landlock-lsm/landlock-test-tools) and
38/// [CI integration](https://github.com/landlock-lsm/rust-landlock/pull/41).
39///
40/// This way, we can have the guarantee that the use of a set of tested Landlock ABI works as
41/// expected because features brought by newer Landlock ABI will never be enabled by default
42/// (cf. [Linux kernel compatibility contract](https://docs.kernel.org/userspace-api/landlock.html#compatibility)).
43///
44/// In a nutshell, test the access rights you request on a kernel that support them and
45/// on a kernel that doesn't support them.
46///
47/// Derived `Debug` formats are [not stable](https://doc.rust-lang.org/stable/std/fmt/trait.Debug.html#stability).
48#[cfg_attr(test, derive(EnumIter, EnumCountMacro))]
49#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
50#[non_exhaustive]
51pub enum ABI {
52 /// Kernel not supporting Landlock, either because it is not built with Landlock
53 /// or Landlock is not enabled at boot.
54 Unsupported = 0,
55 /// First Landlock ABI, introduced with
56 /// [Linux 5.13](https://git.kernel.org/stable/c/17ae69aba89dbfa2139b7f8024b757ab3cc42f59).
57 V1 = 1,
58 /// Second Landlock ABI, introduced with
59 /// [Linux 5.19](https://git.kernel.org/stable/c/cb44e4f061e16be65b8a16505e121490c66d30d0).
60 V2 = 2,
61 /// Third Landlock ABI, introduced with
62 /// [Linux 6.2](https://git.kernel.org/stable/c/299e2b1967578b1442128ba8b3e86ed3427d3651).
63 V3 = 3,
64 /// Fourth Landlock ABI, introduced with
65 /// [Linux 6.7](https://git.kernel.org/stable/c/136cc1e1f5be75f57f1e0404b94ee1c8792cb07d).
66 V4 = 4,
67 /// Fifth Landlock ABI, introduced with
68 /// [Linux 6.10](https://git.kernel.org/stable/c/2fc0e7892c10734c1b7c613ef04836d57d4676d5).
69 V5 = 5,
70 /// Sixth Landlock ABI, introduced with
71 /// [Linux 6.12](https://git.kernel.org/stable/c/e1b061b444fb01c237838f0d8238653afe6a8094).
72 V6 = 6,
73 /// Seventh Landlock ABI, introduced with
74 /// [Linux 6.15](https://git.kernel.org/stable/c/72885116069abdd05c245707c3989fc605632970).
75 V7 = 7,
76 /// Eighth Landlock ABI, introduced with [Linux
77 /// 7.0](https://git.kernel.org/stable/c/c22e26bd0906e9c8325462993f01adb16b8ea2c0).
78 V8 = 8,
79 /// Ninth Landlock ABI, introduced with
80 /// [Linux 7.1](https://git.kernel.org/stable/c/b8f82cb0d84d00c04cdbdce42f67df71b8507e8b).
81 V9 = 9,
82}
83
84// ABI should not be dynamically created (in other crates) according to the running kernel
85// to avoid inconsistent behaviors and non-determinism. Creating ABIs based on runtime detection
86// can lead to unreliable sandboxing where rules might differ between executions.
87impl ABI {
88 #[cfg(test)]
89 fn is_known(value: i32) -> bool {
90 value > 0 && value < ABI::COUNT as i32
91 }
92}
93
94/// Converting from an integer to an ABI should only be used for testing.
95/// Indeed, manually setting the ABI can lead to inconsistent and unexpected behaviors.
96/// Instead, just use the appropriate access rights, this library will handle the rest.
97impl From<i32> for ABI {
98 fn from(value: i32) -> ABI {
99 match value {
100 n if n <= 0 => ABI::Unsupported,
101 1 => ABI::V1,
102 2 => ABI::V2,
103 3 => ABI::V3,
104 4 => ABI::V4,
105 5 => ABI::V5,
106 6 => ABI::V6,
107 7 => ABI::V7,
108 8 => ABI::V8,
109 // Returns the greatest known ABI.
110 _ => ABI::V9,
111 }
112 }
113}
114
115#[test]
116fn abi_from() {
117 // EOPNOTSUPP (-95), ENOSYS (-38)
118 for n in [-95, -38, -1, 0] {
119 assert_eq!(ABI::from(n), ABI::Unsupported);
120 }
121
122 let mut last_i = 1;
123 let mut last_abi = ABI::Unsupported;
124 for (i, abi) in ABI::iter().enumerate() {
125 last_i = i.try_into().unwrap();
126 last_abi = abi;
127 assert_eq!(ABI::from(last_i), last_abi);
128 }
129
130 assert_eq!(ABI::from(last_i + 1), last_abi);
131 assert_eq!(ABI::from(999), last_abi);
132}
133
134#[test]
135fn known_abi() {
136 assert!(!ABI::is_known(-1));
137 assert!(!ABI::is_known(0));
138 assert!(!ABI::is_known(999));
139
140 let mut last_i = -1;
141 for (i, _) in ABI::iter().enumerate().skip(1) {
142 last_i = i as i32;
143 assert!(ABI::is_known(last_i));
144 }
145 assert!(!ABI::is_known(last_i + 1));
146}
147
148impl Display for ABI {
149 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
150 match self {
151 ABI::Unsupported => write!(f, "unsupported"),
152 v => (*v as u32).fmt(f),
153 }
154 }
155}
156
157/// Status of Landlock support for the running system.
158///
159/// This enum is used to represent the status of the Landlock support for the system where the code
160/// is executed. It can indicate whether Landlock is available or not.
161///
162/// # Warning
163///
164/// Sandboxed programs should only use this data to log or provide information to users,
165/// not to change their behavior according to this status. Indeed, the `Ruleset` and the other
166/// types are designed to handle the compatibility in a simple and safe way.
167#[derive(Copy, Clone, Debug, PartialEq, Eq)]
168pub enum LandlockStatus {
169 /// Landlock is supported but not enabled (`EOPNOTSUPP`).
170 NotEnabled,
171 /// Landlock is not implemented (i.e. not built into the running kernel: `ENOSYS`).
172 NotImplemented,
173 /// Landlock is available and working on the running system.
174 ///
175 /// This indicates that the kernel supports Landlock and it's properly enabled.
176 /// The crate uses the `effective_abi` for all operations, which represents
177 /// the highest ABI version that both the kernel and this crate understand.
178 Available {
179 /// The effective ABI version that this crate will use for Landlock operations.
180 /// This is the intersection of what the kernel supports and what this crate knows about.
181 effective_abi: ABI,
182 /// The actual kernel ABI version when it's newer than any ABI supported by this crate.
183 ///
184 /// If `Some(version)`, it means the running kernel supports Landlock ABI `version`
185 /// which is higher than the latest ABI known by this crate.
186 ///
187 /// This field is purely informational and is never used for Landlock operations.
188 /// The crate always and only uses `effective_abi` for all functionality.
189 kernel_abi: Option<i32>,
190 },
191}
192
193impl LandlockStatus {
194 // Must remain private to avoid inconsistent behavior using such unknown-at-build-time ABI
195 // e.g., AccessFs::from_all(ABI::new_current())
196 //
197 // This should not be Default::default() because the returned value would may not be the same
198 // for all users.
199 fn current() -> Self {
200 // Landlock ABI version starts at 1 but errno is only set for negative values.
201 let v = unsafe {
202 uapi::landlock_create_ruleset(
203 std::ptr::null(),
204 0,
205 uapi::LANDLOCK_CREATE_RULESET_VERSION,
206 )
207 };
208 if v < 0 {
209 // The only possible error values should be EOPNOTSUPP and ENOSYS.
210 match Error::last_os_error().raw_os_error() {
211 Some(libc::EOPNOTSUPP) => Self::NotEnabled,
212 _ => Self::NotImplemented,
213 }
214 } else {
215 let abi = ABI::from(v);
216 Self::Available {
217 effective_abi: abi,
218 kernel_abi: (v != abi as i32).then_some(v),
219 }
220 }
221 }
222}
223
224// Test against the running kernel.
225#[test]
226fn test_current_landlock_status() {
227 let status = LandlockStatus::current();
228 if *TEST_ABI == ABI::Unsupported {
229 assert_eq!(status, LandlockStatus::NotImplemented);
230 } else {
231 assert!(
232 matches!(status, LandlockStatus::Available { effective_abi, .. } if effective_abi == *TEST_ABI)
233 );
234 if std::env::var(TEST_ABI_ENV_NAME).is_ok() {
235 // We cannot reliably check for unknown kernel.
236 assert!(matches!(
237 status,
238 LandlockStatus::Available {
239 kernel_abi: None,
240 ..
241 }
242 ));
243 }
244 }
245}
246
247impl From<LandlockStatus> for ABI {
248 fn from(status: LandlockStatus) -> Self {
249 match status {
250 // The only possible error values should be EOPNOTSUPP and ENOSYS,
251 // but let's convert all kind of errors as unsupported.
252 LandlockStatus::NotEnabled | LandlockStatus::NotImplemented => ABI::Unsupported,
253 LandlockStatus::Available { effective_abi, .. } => effective_abi,
254 }
255 }
256}
257
258// This is only useful to tests and should not be exposed publicly because
259// the mapping can only be partial.
260#[cfg(test)]
261impl From<ABI> for LandlockStatus {
262 fn from(abi: ABI) -> Self {
263 match abi {
264 // Convert to ENOSYS because of check_ruleset_support() and ruleset_unsupported() tests.
265 ABI::Unsupported => Self::NotImplemented,
266 _ => Self::Available {
267 effective_abi: abi,
268 kernel_abi: None,
269 },
270 }
271 }
272}
273
274#[cfg(test)]
275pub(crate) static TEST_ABI_ENV_NAME: &str = "LANDLOCK_CRATE_TEST_ABI";
276
277#[cfg(test)]
278lazy_static! {
279 pub(crate) static ref TEST_ABI: ABI = match std::env::var("LANDLOCK_CRATE_TEST_ABI") {
280 Ok(s) => {
281 let n = s.parse::<i32>().unwrap();
282 if ABI::is_known(n) || n == 0 {
283 ABI::from(n)
284 } else {
285 panic!("Unknown ABI: {n}");
286 }
287 }
288 Err(std::env::VarError::NotPresent) => LandlockStatus::current().into(),
289 Err(e) => panic!("Failed to read LANDLOCK_CRATE_TEST_ABI: {e}"),
290 };
291}
292
293#[cfg(test)]
294pub(crate) fn can_emulate(mock: ABI, partial_support: ABI, full_support: Option<ABI>) -> bool {
295 mock < partial_support
296 || mock <= *TEST_ABI
297 || if let Some(full) = full_support {
298 full <= *TEST_ABI
299 } else {
300 partial_support <= *TEST_ABI
301 }
302}
303
304#[cfg(test)]
305pub(crate) fn get_errno_from_landlock_status() -> Option<i32> {
306 match LandlockStatus::current() {
307 LandlockStatus::NotImplemented | LandlockStatus::NotEnabled => {
308 match Error::last_os_error().raw_os_error() {
309 // Returns ENOSYS when the kernel is not built with Landlock support,
310 // or EOPNOTSUPP when Landlock is supported but disabled at boot time.
311 ret @ Some(libc::ENOSYS | libc::EOPNOTSUPP) => ret,
312 // Other values can only come from bogus seccomp filters or debugging tampering.
313 ret => {
314 eprintln!("Current kernel should support this Landlock ABI according to $LANDLOCK_CRATE_TEST_ABI");
315 eprintln!("Unexpected result: {ret:?}");
316 unreachable!();
317 }
318 }
319 }
320 LandlockStatus::Available { .. } => None,
321 }
322}
323
324#[test]
325fn current_kernel_abi() {
326 // Ensures that the tested Landlock ABI is the latest known version supported by the running
327 // kernel. If this test failed, you need set the LANDLOCK_CRATE_TEST_ABI environment variable
328 // to the Landlock ABI version supported by your kernel. With a missing variable, the latest
329 // Landlock ABI version known by this crate is automatically set.
330 // From Linux 5.13 to 5.18, you need to run: LANDLOCK_CRATE_TEST_ABI=1 cargo test
331 let test_abi = *TEST_ABI;
332 let current_abi = LandlockStatus::current().into();
333 println!(
334 "Current kernel version: {}",
335 std::fs::read_to_string("/proc/version")
336 .unwrap_or_else(|_| "unknown".into())
337 .trim()
338 );
339 println!("Expected Landlock ABI {test_abi:?} whereas the current ABI is {current_abi:#?}");
340 assert_eq!(test_abi, current_abi);
341}
342
343// CompatState is not public outside this crate.
344/// Returned by ruleset builder.
345#[derive(Copy, Clone, Debug, PartialEq, Eq)]
346pub enum CompatState {
347 /// Initial undefined state.
348 Init,
349 /// All requested restrictions are enforced.
350 Full,
351 /// Some requested restrictions are enforced, following a best-effort approach.
352 Partial,
353 /// The running system doesn't support Landlock.
354 No,
355 /// Final unsupported state.
356 Dummy,
357}
358
359impl CompatState {
360 fn update(&mut self, other: Self) {
361 *self = match (*self, other) {
362 (CompatState::Init, other) => other,
363 (CompatState::Dummy, _) => CompatState::Dummy,
364 (_, CompatState::Dummy) => CompatState::Dummy,
365 (CompatState::No, CompatState::No) => CompatState::No,
366 (CompatState::Full, CompatState::Full) => CompatState::Full,
367 (_, _) => CompatState::Partial,
368 }
369 }
370}
371
372#[test]
373fn compat_state_update_1() {
374 let mut state = CompatState::Full;
375
376 state.update(CompatState::Full);
377 assert_eq!(state, CompatState::Full);
378
379 state.update(CompatState::No);
380 assert_eq!(state, CompatState::Partial);
381
382 state.update(CompatState::Full);
383 assert_eq!(state, CompatState::Partial);
384
385 state.update(CompatState::Full);
386 assert_eq!(state, CompatState::Partial);
387
388 state.update(CompatState::No);
389 assert_eq!(state, CompatState::Partial);
390
391 state.update(CompatState::Dummy);
392 assert_eq!(state, CompatState::Dummy);
393
394 state.update(CompatState::Full);
395 assert_eq!(state, CompatState::Dummy);
396}
397
398#[test]
399fn compat_state_update_2() {
400 let mut state = CompatState::Full;
401
402 state.update(CompatState::Full);
403 assert_eq!(state, CompatState::Full);
404
405 state.update(CompatState::No);
406 assert_eq!(state, CompatState::Partial);
407
408 state.update(CompatState::Full);
409 assert_eq!(state, CompatState::Partial);
410}
411
412#[test]
413fn try_compat_binary_states() {
414 // Supported: state -> Full.
415 let mut compat: Compatibility = ABI::Unsupported.into();
416 assert_eq!(compat.state, CompatState::Init);
417 assert_eq!(compat.try_compat_binary(true, || "err"), Ok(true));
418 assert_eq!(compat.state, CompatState::Full);
419
420 // Unsupported + BestEffort: state -> Partial (Full + No).
421 assert_eq!(compat.try_compat_binary(false, || "err"), Ok(false));
422 assert_eq!(compat.state, CompatState::Partial);
423
424 // Unsupported + SoftRequirement: state -> Dummy.
425 let mut compat: Compatibility = ABI::Unsupported.into();
426 compat.level = Some(CompatLevel::SoftRequirement);
427 assert_eq!(compat.try_compat_binary(false, || "err"), Ok(false));
428 assert_eq!(compat.state, CompatState::Dummy);
429
430 // Unsupported + HardRequirement: returns error.
431 let mut compat: Compatibility = ABI::Unsupported.into();
432 compat.level = Some(CompatLevel::HardRequirement);
433 assert_eq!(compat.try_compat_binary(false, || "err"), Err("err"));
434}
435
436#[cfg_attr(test, derive(PartialEq))]
437#[derive(Copy, Clone, Debug)]
438pub(crate) struct Compatibility {
439 status: LandlockStatus,
440 pub(crate) level: Option<CompatLevel>,
441 pub(crate) state: CompatState,
442}
443
444impl From<LandlockStatus> for Compatibility {
445 fn from(status: LandlockStatus) -> Self {
446 Compatibility {
447 status,
448 level: Default::default(),
449 state: CompatState::Init,
450 }
451 }
452}
453
454#[cfg(test)]
455impl From<ABI> for Compatibility {
456 fn from(abi: ABI) -> Self {
457 Self::from(LandlockStatus::from(abi))
458 }
459}
460
461impl Compatibility {
462 // Compatibility is a semi-opaque struct.
463 #[allow(clippy::new_without_default)]
464 pub(crate) fn new() -> Self {
465 LandlockStatus::current().into()
466 }
467
468 pub(crate) fn update(&mut self, state: CompatState) {
469 self.state.update(state);
470 }
471
472 pub(crate) fn abi(&self) -> ABI {
473 self.status.into()
474 }
475
476 pub(crate) fn status(&self) -> LandlockStatus {
477 self.status
478 }
479
480 /// Handles the compat dispatch for a binary supported/not-supported check.
481 ///
482 /// This is factored out from the No branch of
483 /// [`TryCompat::try_compat()`](crate::TryCompat::try_compat) for use by
484 /// [`SyscallFlagExt::try_compat()`](crate::flags::SyscallFlagExt::try_compat),
485 /// where a single flag is either fully supported or not (no Partial case).
486 ///
487 /// Returns `Ok(true)` if supported (caller should apply the flag),
488 /// `Ok(false)` if unsupported but acceptable
489 /// ([`BestEffort`](crate::CompatLevel::BestEffort) /
490 /// [`SoftRequirement`](crate::CompatLevel::SoftRequirement)), or `Err` if
491 /// unsupported with [`HardRequirement`](crate::CompatLevel::HardRequirement).
492 pub(crate) fn try_compat_binary<E, F>(
493 &mut self,
494 supported: bool,
495 make_error: F,
496 ) -> Result<bool, E>
497 where
498 F: FnOnce() -> E,
499 {
500 if supported {
501 self.state.update(CompatState::Full);
502 Ok(true)
503 } else {
504 match self.level.into() {
505 CompatLevel::BestEffort => {
506 self.state.update(CompatState::No);
507 Ok(false)
508 }
509 CompatLevel::SoftRequirement => {
510 self.state.update(CompatState::Dummy);
511 Ok(false)
512 }
513 CompatLevel::HardRequirement => Err(make_error()),
514 }
515 }
516 }
517}
518
519pub(crate) mod private {
520 use crate::CompatLevel;
521
522 pub trait OptionCompatLevelMut {
523 fn as_option_compat_level_mut(&mut self) -> &mut Option<CompatLevel>;
524 }
525}
526
527/// Properly handles runtime unsupported features.
528///
529/// This guarantees consistent behaviors across crate users
530/// and runtime kernels even if this crate get new features.
531/// It eases backward compatibility and enables future-proofness.
532///
533/// Landlock is a security feature designed to help improve security of a running system
534/// thanks to application developers.
535/// To protect users as much as possible,
536/// compatibility with the running system should then be handled in a best-effort way,
537/// contrary to common system features.
538/// In some circumstances
539/// (e.g. applications carefully designed to only be run with a specific set of kernel features),
540/// it may be required to error out if some of these features are not available
541/// and will then not be enforced.
542pub trait Compatible: Sized + private::OptionCompatLevelMut {
543 /// To enable a best-effort security approach,
544 /// Landlock features that are not supported by the running system
545 /// are silently ignored by default,
546 /// which is a sane choice for most use cases.
547 /// However, on some rare circumstances,
548 /// developers may want to have some guarantees that their applications
549 /// will not run if a certain level of sandboxing is not possible.
550 /// If we really want to error out when not all our requested requirements are met,
551 /// then we can configure it with `set_compatibility()`.
552 ///
553 /// The `Compatible` trait is implemented for all object builders
554 /// (e.g. [`Ruleset`](crate::Ruleset)).
555 /// Such builders have a set of methods to incrementally build an object.
556 /// These build methods rely on kernel features that may not be available at runtime.
557 /// The `set_compatibility()` method enables to control the effect of
558 /// the following build method calls starting after the `set_compatibility()` call.
559 /// Such effect can be:
560 /// * to silently ignore unsupported features
561 /// and continue building ([`CompatLevel::BestEffort`]);
562 /// * to silently ignore unsupported features
563 /// and ignore the whole build ([`CompatLevel::SoftRequirement`]);
564 /// * to return an error for any unsupported feature ([`CompatLevel::HardRequirement`]).
565 ///
566 /// Taking [`Ruleset`](crate::Ruleset) as an example,
567 /// the [`handle_access()`](crate::RulesetAttr::handle_access()) build method
568 /// returns a [`Result`] that can be [`Err(RulesetError)`](crate::RulesetError)
569 /// with a nested [`CompatError`].
570 /// Such error can only occur with a running Linux kernel not supporting the requested
571 /// Landlock accesses *and* if the current compatibility level is
572 /// [`CompatLevel::HardRequirement`].
573 /// However, such error is not possible with [`CompatLevel::BestEffort`]
574 /// nor [`CompatLevel::SoftRequirement`].
575 ///
576 /// The order of this call is important because
577 /// it defines the behavior of the following build method calls that return a [`Result`].
578 /// If `set_compatibility(CompatLevel::HardRequirement)` is called on an object,
579 /// then a [`CompatError`] may be returned for the next method calls,
580 /// until the next call to `set_compatibility()`.
581 /// This enables to change the behavior of a set of build method calls,
582 /// for instance to be sure that the sandbox will at least restrict some access rights.
583 ///
584 /// New objects inherit the compatibility configuration of their parents, if any.
585 /// For instance, [`Ruleset::create()`](crate::Ruleset::create()) returns
586 /// a [`RulesetCreated`](crate::RulesetCreated) object that inherits the
587 /// `Ruleset`'s compatibility configuration.
588 ///
589 /// # Example with `SoftRequirement`
590 ///
591 /// Let's say an application legitimately needs to rename files between directories.
592 /// Because of [previous Landlock limitations](https://docs.kernel.org/userspace-api/landlock.html#file-renaming-and-linking-abi-2),
593 /// this was forbidden with the [first version of Landlock](ABI::V1),
594 /// but it is now handled starting with the [second version](ABI::V2).
595 /// For this use case, we only want the application to be sandboxed
596 /// if we have the guarantee that it will not break a legitimate usage (i.e. rename files).
597 /// We then create a ruleset which will either support file renaming
598 /// (thanks to [`AccessFs::Refer`](crate::AccessFs::Refer)) or silently do nothing.
599 ///
600 /// ```
601 /// use landlock::*;
602 ///
603 /// fn ruleset_handling_renames() -> Result<RulesetCreated, RulesetError> {
604 /// Ok(Ruleset::default()
605 /// // This ruleset must either handle the AccessFs::Refer right,
606 /// // or it must silently ignore the whole sandboxing.
607 /// .set_compatibility(CompatLevel::SoftRequirement)
608 /// .handle_access(AccessFs::Refer)?
609 /// // However, this ruleset may also handle other (future) access rights
610 /// // if they are supported by the running kernel.
611 /// .set_compatibility(CompatLevel::BestEffort)
612 /// .handle_access(AccessFs::from_all(ABI::V9))?
613 /// .create()?)
614 /// }
615 /// ```
616 ///
617 /// # Example with `HardRequirement`
618 ///
619 /// Security-dedicated applications may want to ensure that
620 /// an untrusted software component is subject to a minimum of restrictions before launching it.
621 /// In this case, we want to create a ruleset which will at least support
622 /// all restrictions provided by the [first version of Landlock](ABI::V1),
623 /// and opportunistically handle restrictions supported by newer kernels.
624 ///
625 /// ```
626 /// use landlock::*;
627 ///
628 /// fn ruleset_fragile() -> Result<RulesetCreated, RulesetError> {
629 /// Ok(Ruleset::default()
630 /// // This ruleset must either handle at least all accesses defined by
631 /// // the first Landlock version (e.g. AccessFs::WriteFile),
632 /// // or the following handle_access() call must return a wrapped
633 /// // AccessError<AccessFs>::Incompatible error.
634 /// .set_compatibility(CompatLevel::HardRequirement)
635 /// .handle_access(AccessFs::from_all(ABI::V1))?
636 /// // However, this ruleset may also handle new access rights
637 /// // (e.g. AccessFs::Refer defined by the second version of Landlock)
638 /// // if they are supported by the running kernel,
639 /// // but without returning any error otherwise.
640 /// .set_compatibility(CompatLevel::BestEffort)
641 /// .handle_access(AccessFs::from_all(ABI::V9))?
642 /// .create()?)
643 /// }
644 /// ```
645 fn set_compatibility(mut self, level: CompatLevel) -> Self {
646 *self.as_option_compat_level_mut() = Some(level);
647 self
648 }
649
650 /// Cf. [`set_compatibility()`](Compatible::set_compatibility()):
651 ///
652 /// - `set_best_effort(true)` translates to `set_compatibility(CompatLevel::BestEffort)`.
653 ///
654 /// - `set_best_effort(false)` translates to `set_compatibility(CompatLevel::HardRequirement)`.
655 #[deprecated(note = "Use set_compatibility() instead")]
656 fn set_best_effort(self, best_effort: bool) -> Self
657 where
658 Self: Sized,
659 {
660 self.set_compatibility(match best_effort {
661 true => CompatLevel::BestEffort,
662 false => CompatLevel::HardRequirement,
663 })
664 }
665}
666
667#[test]
668#[allow(deprecated)]
669fn deprecated_set_best_effort() {
670 use crate::{CompatLevel, Compatible, Ruleset};
671
672 assert_eq!(
673 Ruleset::default().set_best_effort(true).compat,
674 Ruleset::default()
675 .set_compatibility(CompatLevel::BestEffort)
676 .compat
677 );
678 assert_eq!(
679 Ruleset::default().set_best_effort(false).compat,
680 Ruleset::default()
681 .set_compatibility(CompatLevel::HardRequirement)
682 .compat
683 );
684}
685
686/// See the [`Compatible`] documentation.
687#[cfg_attr(test, derive(EnumIter))]
688#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
689pub enum CompatLevel {
690 /// Takes into account the build requests if they are supported by the running system,
691 /// or silently ignores them otherwise.
692 /// Never returns a compatibility error.
693 #[default]
694 BestEffort,
695 /// Takes into account the build requests if they are supported by the running system,
696 /// or silently ignores the whole build object otherwise.
697 /// Never returns a compatibility error.
698 /// If not supported,
699 /// the call to [`RulesetCreated::restrict_self()`](crate::RulesetCreated::restrict_self())
700 /// will return a
701 /// [`RestrictionStatus { ruleset: RulesetStatus::NotEnforced, no_new_privs: false, }`](crate::RestrictionStatus).
702 SoftRequirement,
703 /// Takes into account the build requests if they are supported by the running system,
704 /// or returns a compatibility error otherwise ([`CompatError`]).
705 HardRequirement,
706}
707
708impl From<Option<CompatLevel>> for CompatLevel {
709 fn from(opt: Option<CompatLevel>) -> Self {
710 match opt {
711 None => CompatLevel::default(),
712 Some(ref level) => *level,
713 }
714 }
715}
716
717// TailoredCompatLevel could be replaced with AsMut<Option<CompatLevel>>, but only traits defined
718// in the current crate can be implemented for types defined outside of the crate. Furthermore it
719// provides a default implementation which is handy for types such as BitFlags.
720pub trait TailoredCompatLevel {
721 fn tailored_compat_level<L>(&mut self, parent_level: L) -> CompatLevel
722 where
723 L: Into<CompatLevel>,
724 {
725 parent_level.into()
726 }
727}
728
729impl<T> TailoredCompatLevel for T
730where
731 Self: Compatible,
732{
733 // Every Compatible trait implementation returns its own compatibility level, if set.
734 fn tailored_compat_level<L>(&mut self, parent_level: L) -> CompatLevel
735 where
736 L: Into<CompatLevel>,
737 {
738 // Using a mutable reference is not required but it makes the code simpler (no double AsRef
739 // implementations for each Compatible types), and more importantly it guarantees
740 // consistency with Compatible::set_compatibility().
741 match self.as_option_compat_level_mut() {
742 None => parent_level.into(),
743 // Returns the most constrained compatibility level.
744 Some(ref level) => parent_level.into().max(*level),
745 }
746 }
747}
748
749#[test]
750fn tailored_compat_level() {
751 use crate::{AccessFs, PathBeneath, PathFd};
752
753 fn new_path(level: CompatLevel) -> PathBeneath<PathFd> {
754 PathBeneath::new(PathFd::new("/").unwrap(), AccessFs::Execute).set_compatibility(level)
755 }
756
757 for parent_level in CompatLevel::iter() {
758 assert_eq!(
759 new_path(CompatLevel::BestEffort).tailored_compat_level(parent_level),
760 parent_level
761 );
762 assert_eq!(
763 new_path(CompatLevel::HardRequirement).tailored_compat_level(parent_level),
764 CompatLevel::HardRequirement
765 );
766 }
767
768 assert_eq!(
769 new_path(CompatLevel::SoftRequirement).tailored_compat_level(CompatLevel::SoftRequirement),
770 CompatLevel::SoftRequirement
771 );
772
773 for child_level in CompatLevel::iter() {
774 assert_eq!(
775 new_path(child_level).tailored_compat_level(CompatLevel::BestEffort),
776 child_level
777 );
778 assert_eq!(
779 new_path(child_level).tailored_compat_level(CompatLevel::HardRequirement),
780 CompatLevel::HardRequirement
781 );
782 }
783}
784
785// CompatResult is not public outside this crate.
786pub enum CompatResult<A>
787where
788 A: Access,
789{
790 // Fully matches the request.
791 Full,
792 // Partially matches the request.
793 Partial(CompatError<A>),
794 // Doesn't matches the request.
795 No(CompatError<A>),
796}
797
798// TryCompat is not public outside this crate.
799pub trait TryCompat<A>
800where
801 Self: Sized + TailoredCompatLevel,
802 A: Access,
803{
804 fn try_compat_inner(&mut self, abi: ABI) -> Result<CompatResult<A>, CompatError<A>>;
805
806 // Default implementation for objects without children.
807 //
808 // If returning something other than Ok(Some(self)), the implementation must use its own
809 // compatibility level, if any, with self.tailored_compat_level(default_compat_level), and pass
810 // it with the abi and compat_state to each child.try_compat(). See PathBeneath implementation
811 // and the self.allowed_access.try_compat() call.
812 //
813 // # Warning
814 //
815 // Errors must be prioritized over incompatibility (i.e. return Err(e) over Ok(None)) for all
816 // children.
817 fn try_compat_children<L>(
818 self,
819 _abi: ABI,
820 _parent_level: L,
821 _compat_state: &mut CompatState,
822 ) -> Result<Option<Self>, CompatError<A>>
823 where
824 L: Into<CompatLevel>,
825 {
826 Ok(Some(self))
827 }
828
829 // Update compat_state and return an error according to try_compat_*() error, or to the
830 // compatibility level, i.e. either route compatible object or error.
831 fn try_compat<L>(
832 mut self,
833 abi: ABI,
834 parent_level: L,
835 compat_state: &mut CompatState,
836 ) -> Result<Option<Self>, CompatError<A>>
837 where
838 L: Into<CompatLevel>,
839 {
840 let compat_level = self.tailored_compat_level(parent_level);
841 let some_inner = match self.try_compat_inner(abi) {
842 Ok(CompatResult::Full) => {
843 compat_state.update(CompatState::Full);
844 true
845 }
846 Ok(CompatResult::Partial(error)) => match compat_level {
847 CompatLevel::BestEffort => {
848 compat_state.update(CompatState::Partial);
849 true
850 }
851 CompatLevel::SoftRequirement => {
852 compat_state.update(CompatState::Dummy);
853 false
854 }
855 CompatLevel::HardRequirement => {
856 compat_state.update(CompatState::Dummy);
857 return Err(error);
858 }
859 },
860 Ok(CompatResult::No(error)) => match compat_level {
861 CompatLevel::BestEffort => {
862 compat_state.update(CompatState::No);
863 false
864 }
865 CompatLevel::SoftRequirement => {
866 compat_state.update(CompatState::Dummy);
867 false
868 }
869 CompatLevel::HardRequirement => {
870 compat_state.update(CompatState::Dummy);
871 return Err(error);
872 }
873 },
874 Err(error) => {
875 // Safeguard to help for test consistency.
876 compat_state.update(CompatState::Dummy);
877 return Err(error);
878 }
879 };
880
881 // At this point, any inner error have been returned, so we can proceed with
882 // try_compat_children()?.
883 match self.try_compat_children(abi, compat_level, compat_state)? {
884 Some(n) if some_inner => Ok(Some(n)),
885 _ => Ok(None),
886 }
887 }
888}