Skip to main content

landlock/
fs.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2
3use crate::compat::{private::OptionCompatLevelMut, try_compat_binary};
4use crate::ruleset::QuietRuleCompatibility;
5use crate::{
6    uapi, Access, AddRuleError, AddRulesError, CompatError, CompatLevel, CompatResult, CompatState,
7    Compatible, HandleAccessError, HandleAccessesError, HandledAccess, PathBeneathError,
8    PathFdError, PrivateHandledAccess, PrivateRule, Rule, Ruleset, RulesetCreated, RulesetError,
9    TailoredCompatLevel, TryCompat, ABI,
10};
11use enumflags2::{bitflags, make_bitflags, BitFlags};
12use std::ffi::CString;
13use std::io::{Error, ErrorKind};
14use std::mem::zeroed;
15use std::os::unix::ffi::OsStrExt;
16use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, OwnedFd};
17use std::path::Path;
18
19#[cfg(test)]
20use crate::{RulesetAttr, RulesetCreatedAttr};
21#[cfg(test)]
22use strum::IntoEnumIterator;
23
24/// File system access right.
25///
26/// Each variant of `AccessFs` is an [access right](https://www.kernel.org/doc/html/latest/userspace-api/landlock.html#access-rights)
27/// for the file system.
28/// A set of access rights can be created with [`BitFlags<AccessFs>`](BitFlags).
29///
30/// # Example
31///
32/// ```
33/// use landlock::{ABI, Access, AccessFs, BitFlags, make_bitflags};
34///
35/// let exec = AccessFs::Execute;
36///
37/// let exec_set: BitFlags<AccessFs> = exec.into();
38///
39/// let file_content = make_bitflags!(AccessFs::{Execute | WriteFile | ReadFile});
40///
41/// let fs_v1 = AccessFs::from_all(ABI::V1);
42///
43/// let without_exec = fs_v1 & !AccessFs::Execute;
44///
45/// assert_eq!(fs_v1 | AccessFs::Refer, AccessFs::from_all(ABI::V2));
46/// ```
47///
48/// # Warning
49///
50/// To avoid unknown restrictions **don't use `BitFlags::<AccessFs>::all()` nor `BitFlags::ALL`**,
51/// but use a version you tested and vetted instead,
52/// for instance [`AccessFs::from_all(ABI::V1)`](Access::from_all).
53/// Direct use of **the [`BitFlags`] API is deprecated**.
54/// See [`ABI`] for the rationale and help to test it.
55#[bitflags]
56#[repr(u64)]
57#[derive(Copy, Clone, Debug, PartialEq, Eq)]
58#[non_exhaustive]
59pub enum AccessFs {
60    /// Execute a file.
61    Execute = uapi::LANDLOCK_ACCESS_FS_EXECUTE as u64,
62    /// Open a file with write access.
63    ///
64    /// # Note
65    ///
66    /// Certain operations (such as [`std::fs::write`]) may also require [`AccessFs::Truncate`] since [`ABI::V3`].
67    WriteFile = uapi::LANDLOCK_ACCESS_FS_WRITE_FILE as u64,
68    /// Open a file with read access.
69    ReadFile = uapi::LANDLOCK_ACCESS_FS_READ_FILE as u64,
70    /// Open a directory or list its content.
71    ReadDir = uapi::LANDLOCK_ACCESS_FS_READ_DIR as u64,
72    /// Remove an empty directory or rename one.
73    RemoveDir = uapi::LANDLOCK_ACCESS_FS_REMOVE_DIR as u64,
74    /// Unlink (or rename) a file.
75    RemoveFile = uapi::LANDLOCK_ACCESS_FS_REMOVE_FILE as u64,
76    /// Create (or rename or link) a character device.
77    MakeChar = uapi::LANDLOCK_ACCESS_FS_MAKE_CHAR as u64,
78    /// Create (or rename) a directory.
79    MakeDir = uapi::LANDLOCK_ACCESS_FS_MAKE_DIR as u64,
80    /// Create (or rename or link) a regular file.
81    MakeReg = uapi::LANDLOCK_ACCESS_FS_MAKE_REG as u64,
82    /// Create (or rename or link) a UNIX domain socket.
83    MakeSock = uapi::LANDLOCK_ACCESS_FS_MAKE_SOCK as u64,
84    /// Create (or rename or link) a named pipe.
85    MakeFifo = uapi::LANDLOCK_ACCESS_FS_MAKE_FIFO as u64,
86    /// Create (or rename or link) a block device.
87    MakeBlock = uapi::LANDLOCK_ACCESS_FS_MAKE_BLOCK as u64,
88    /// Create (or rename or link) a symbolic link.
89    MakeSym = uapi::LANDLOCK_ACCESS_FS_MAKE_SYM as u64,
90    /// Link or rename a file from or to a different directory.
91    Refer = uapi::LANDLOCK_ACCESS_FS_REFER as u64,
92    /// Truncate a file with `truncate(2)`, `ftruncate(2)`, `creat(2)`, or `open(2)` with `O_TRUNC`.
93    Truncate = uapi::LANDLOCK_ACCESS_FS_TRUNCATE as u64,
94    /// Send IOCL commands to a device file.
95    IoctlDev = uapi::LANDLOCK_ACCESS_FS_IOCTL_DEV as u64,
96    /// Connect to a pathname UNIX domain socket with `connect(2)` or `sendmsg(2)`.
97    ResolveUnix = uapi::LANDLOCK_ACCESS_FS_RESOLVE_UNIX as u64,
98}
99
100impl Access for AccessFs {
101    /// Union of [`from_read()`](AccessFs::from_read) and [`from_write()`](AccessFs::from_write).
102    fn from_all(abi: ABI) -> BitFlags<Self> {
103        // An empty access-right would be an error if passed to the kernel, but because the kernel
104        // doesn't support Landlock, no Landlock syscall should be called.  try_compat() should
105        // also return RestrictionStatus::Unrestricted when called with unsupported/empty
106        // access-rights.
107        Self::from_read(abi) | Self::from_write(abi)
108    }
109}
110
111impl AccessFs {
112    // Roughly read (i.e. not all FS actions are handled).
113    /// Gets the access rights identified as read-only according to a specific ABI.
114    /// Exclusive with [`from_write()`](AccessFs::from_write).
115    pub fn from_read(abi: ABI) -> BitFlags<Self> {
116        match abi {
117            ABI::Unsupported => BitFlags::EMPTY,
118            ABI::V1
119            | ABI::V2
120            | ABI::V3
121            | ABI::V4
122            | ABI::V5
123            | ABI::V6
124            | ABI::V7
125            | ABI::V8
126            | ABI::V9
127            | ABI::V10 => {
128                make_bitflags!(AccessFs::{
129                    Execute
130                    | ReadFile
131                    | ReadDir
132                })
133            }
134        }
135    }
136
137    // Roughly write (i.e. not all FS actions are handled).
138    /// Gets the access rights identified as write-only according to a specific ABI.
139    /// Exclusive with [`from_read()`](AccessFs::from_read).
140    pub fn from_write(abi: ABI) -> BitFlags<Self> {
141        match abi {
142            ABI::Unsupported => BitFlags::EMPTY,
143            ABI::V1 => make_bitflags!(AccessFs::{
144                WriteFile
145                | RemoveDir
146                | RemoveFile
147                | MakeChar
148                | MakeDir
149                | MakeReg
150                | MakeSock
151                | MakeFifo
152                | MakeBlock
153                | MakeSym
154            }),
155            ABI::V2 => Self::from_write(ABI::V1) | AccessFs::Refer,
156            ABI::V3 | ABI::V4 => Self::from_write(ABI::V2) | AccessFs::Truncate,
157            ABI::V5 | ABI::V6 | ABI::V7 | ABI::V8 => Self::from_write(ABI::V4) | AccessFs::IoctlDev,
158            ABI::V9 | ABI::V10 => Self::from_write(ABI::V8) | AccessFs::ResolveUnix,
159        }
160    }
161
162    /// Gets the access rights legitimate for non-directory files.
163    pub fn from_file(abi: ABI) -> BitFlags<Self> {
164        Self::from_all(abi) & ACCESS_FILE
165    }
166}
167
168#[test]
169fn consistent_access_fs_rw() {
170    for abi in ABI::iter() {
171        let access_all = AccessFs::from_all(abi);
172        let access_read = AccessFs::from_read(abi);
173        let access_write = AccessFs::from_write(abi);
174        let access_file = AccessFs::from_file(abi);
175        assert_eq!(access_read, !access_write & access_all);
176        assert_eq!(access_read | access_write, access_all);
177        assert_eq!(access_file, access_all & ACCESS_FILE);
178    }
179}
180
181impl HandledAccess for AccessFs {}
182
183impl PrivateHandledAccess for AccessFs {
184    fn ruleset_handle_access(
185        ruleset: &mut Ruleset,
186        access: BitFlags<Self>,
187    ) -> Result<(), HandleAccessesError> {
188        ruleset
189            .fs
190            .request(access, &mut ruleset.compat)
191            .map_err(HandleAccessError::Compat)?;
192        Ok(())
193    }
194
195    fn ruleset_quiet_access(
196        ruleset: &mut Ruleset,
197        access: BitFlags<Self>,
198    ) -> Result<(), HandleAccessesError> {
199        ruleset
200            .fs
201            .request_quiet(access, &mut ruleset.compat)
202            .map_err(HandleAccessError::Compat)?;
203        Ok(())
204    }
205
206    fn ruleset_has_effective_quiet_access(ruleset: &RulesetCreated, abi: ABI) -> bool {
207        !ruleset.fs.resolve(abi).quiet.is_empty()
208    }
209
210    fn into_add_rules_error(error: AddRuleError<Self>) -> AddRulesError {
211        AddRulesError::Fs(error)
212    }
213
214    fn into_handle_accesses_error(error: HandleAccessError<Self>) -> HandleAccessesError {
215        HandleAccessesError::Fs(error)
216    }
217}
218
219// TODO: Make ACCESS_FILE a property of AccessFs.
220// TODO: Add tests for ACCESS_FILE.
221const ACCESS_FILE: BitFlags<AccessFs> = make_bitflags!(AccessFs::{
222    ReadFile | WriteFile | Execute | Truncate | IoctlDev | ResolveUnix
223});
224
225// XXX: What should we do when a stat call failed?
226fn is_file<F>(fd: F) -> Result<bool, Error>
227where
228    F: AsFd,
229{
230    unsafe {
231        let mut stat = zeroed();
232        match libc::fstat(fd.as_fd().as_raw_fd(), &mut stat) {
233            0 => Ok((stat.st_mode & libc::S_IFMT) != libc::S_IFDIR),
234            _ => Err(Error::last_os_error()),
235        }
236    }
237}
238
239/// Landlock rule for a file hierarchy.
240///
241/// # Example
242///
243/// ```
244/// use landlock::{AccessFs, PathBeneath, PathFd, PathFdError};
245///
246/// fn home_dir() -> Result<PathBeneath<PathFd>, PathFdError> {
247///     Ok(PathBeneath::new(PathFd::new("/home")?, AccessFs::ReadDir))
248/// }
249/// ```
250#[derive(Debug)]
251pub struct PathBeneath<F> {
252    attr: uapi::landlock_path_beneath_attr,
253    // Ties the lifetime of a file descriptor to this object.
254    parent_fd: F,
255    allowed_access: BitFlags<AccessFs>,
256    compat_level: Option<CompatLevel>,
257    quiet: bool,
258    quiet_compatibility: QuietRuleCompatibility,
259}
260
261impl<F> PathBeneath<F>
262where
263    F: AsFd,
264{
265    /// Creates a new `PathBeneath` rule identifying the `parent` directory of a file hierarchy,
266    /// or just a file, and allows `access` on it.
267    /// The `parent` file descriptor will be automatically closed with the returned `PathBeneath`.
268    pub fn new<A>(parent: F, access: A) -> Self
269    where
270        A: Into<BitFlags<AccessFs>>,
271    {
272        PathBeneath {
273            // Invalid access rights until as_ptr() is called.
274            attr: unsafe { zeroed() },
275            parent_fd: parent,
276            allowed_access: access.into(),
277            compat_level: None,
278            quiet: false,
279            quiet_compatibility: QuietRuleCompatibility::Unsupported,
280        }
281    }
282}
283
284impl<F> TryCompat<AccessFs> for PathBeneath<F>
285where
286    F: AsFd,
287{
288    fn try_compat_children<L>(
289        mut self,
290        abi: ABI,
291        parent_level: L,
292        compat_state: &mut CompatState,
293    ) -> Result<Option<Self>, CompatError<AccessFs>>
294    where
295        L: Into<CompatLevel>,
296    {
297        let level = self.tailored_compat_level(parent_level);
298        let requested_quiet = self.quiet;
299        if self.quiet {
300            let (supported, effective) = match self.quiet_compatibility {
301                QuietRuleCompatibility::Unsupported => (false, false),
302                QuietRuleCompatibility::SupportedIneffective => (true, false),
303                QuietRuleCompatibility::SupportedEffective => (true, true),
304            };
305            self.quiet = try_compat_binary(supported, level, compat_state, || {
306                CompatError::<AccessFs>::QuietNotSupported
307            })?;
308            // Quiet may be supported but have no effect after every quiet
309            // access in this rule category has degraded away.  The ruleset
310            // compatibility state already records that degradation.
311            if self.quiet && !effective {
312                self.quiet = false;
313            }
314        }
315        // Empty allowed access is meaningful only while the rule remains quiet.
316        if requested_quiet && self.allowed_access.is_empty() {
317            return Ok(self.quiet.then_some(self));
318        }
319        // Checks with our own compatibility level, if any.
320        self.allowed_access = match self.allowed_access.try_compat(abi, level, compat_state)? {
321            Some(a) => a,
322            None if self.quiet => BitFlags::EMPTY,
323            None => return Ok(None),
324        };
325        Ok(Some(self))
326    }
327
328    fn try_compat_inner(
329        &mut self,
330        _abi: ABI,
331    ) -> Result<CompatResult<AccessFs>, CompatError<AccessFs>> {
332        // Gets subset of valid accesses according the FD type.
333        let valid_access =
334            if is_file(&self.parent_fd).map_err(|e| PathBeneathError::StatCall { source: e })? {
335                self.allowed_access & ACCESS_FILE
336            } else {
337                self.allowed_access
338            };
339
340        if self.allowed_access != valid_access {
341            let error = PathBeneathError::DirectoryAccess {
342                access: self.allowed_access,
343                incompatible: self.allowed_access ^ valid_access,
344            }
345            .into();
346            self.allowed_access = valid_access;
347            // Linux would return EINVAL.
348            Ok(CompatResult::Partial(error))
349        } else {
350            Ok(CompatResult::Full)
351        }
352    }
353}
354
355#[test]
356fn path_beneath_try_compat_children() {
357    use crate::*;
358
359    // AccessFs::Refer is not handled by ABI::V1 and only for directories.
360    let access_file = AccessFs::ReadFile | AccessFs::Refer;
361
362    // Test error ordering with ABI::V1
363    let mut ruleset = Ruleset::from(ABI::V1).handle_access(access_file).unwrap();
364    // Do not actually perform any syscall.
365    ruleset.compat.state = CompatState::Dummy;
366    assert!(matches!(
367        RulesetCreated::new(ruleset, None)
368            .set_compatibility(CompatLevel::HardRequirement)
369            .add_rule(PathBeneath::new(PathFd::new("/dev/null").unwrap(), access_file))
370            .unwrap_err(),
371        RulesetError::AddRules(AddRulesError::Fs(AddRuleError::Compat(
372            CompatError::PathBeneath(PathBeneathError::DirectoryAccess { access, incompatible })
373        ))) if access == access_file && incompatible == AccessFs::Refer
374    ));
375
376    // Test error ordering with ABI::V2
377    let mut ruleset = Ruleset::from(ABI::V2).handle_access(access_file).unwrap();
378    // Do not actually perform any syscall.
379    ruleset.compat.state = CompatState::Dummy;
380    assert!(matches!(
381        RulesetCreated::new(ruleset, None)
382            .set_compatibility(CompatLevel::HardRequirement)
383            .add_rule(PathBeneath::new(PathFd::new("/dev/null").unwrap(), access_file))
384            .unwrap_err(),
385        RulesetError::AddRules(AddRulesError::Fs(AddRuleError::Compat(
386            CompatError::PathBeneath(PathBeneathError::DirectoryAccess { access, incompatible })
387        ))) if access == access_file && incompatible == AccessFs::Refer
388    ));
389}
390
391#[test]
392fn path_beneath_try_compat() {
393    use crate::*;
394
395    let abi = ABI::V1;
396
397    for file in &["/etc/passwd", "/dev/null"] {
398        let mut compat_state = CompatState::Init;
399        let ro_access = AccessFs::ReadDir | AccessFs::ReadFile;
400        assert!(matches!(
401            PathBeneath::new(PathFd::new(file).unwrap(), ro_access)
402                .try_compat(abi, CompatLevel::HardRequirement, &mut compat_state)
403                .unwrap_err(),
404            CompatError::PathBeneath(PathBeneathError::DirectoryAccess { access, incompatible })
405                if access == ro_access && incompatible == AccessFs::ReadDir
406        ));
407
408        let mut compat_state = CompatState::Init;
409        assert!(matches!(
410            PathBeneath::new(PathFd::new(file).unwrap(), BitFlags::EMPTY)
411                .try_compat(abi, CompatLevel::BestEffort, &mut compat_state)
412                .unwrap_err(),
413            CompatError::Access(AccessError::Empty)
414        ));
415    }
416
417    let full_access = AccessFs::from_all(ABI::V1);
418    for compat_level in &[
419        CompatLevel::BestEffort,
420        CompatLevel::SoftRequirement,
421        CompatLevel::HardRequirement,
422    ] {
423        let mut compat_state = CompatState::Init;
424        let mut path_beneath = PathBeneath::new(PathFd::new("/").unwrap(), full_access)
425            .try_compat(abi, *compat_level, &mut compat_state)
426            .unwrap()
427            .unwrap();
428        assert_eq!(compat_state, CompatState::Full);
429
430        // Without synchronization.
431        let raw_access = path_beneath.attr.allowed_access;
432        assert_eq!(raw_access, 0);
433
434        // Synchronize the inner attribute buffer.
435        let _ = path_beneath.as_ptr();
436        let raw_access = path_beneath.attr.allowed_access;
437        assert_eq!(raw_access, full_access.bits());
438    }
439}
440
441impl<F> OptionCompatLevelMut for PathBeneath<F> {
442    fn as_option_compat_level_mut(&mut self) -> &mut Option<CompatLevel> {
443        &mut self.compat_level
444    }
445}
446
447impl<F> OptionCompatLevelMut for &mut PathBeneath<F> {
448    fn as_option_compat_level_mut(&mut self) -> &mut Option<CompatLevel> {
449        &mut self.compat_level
450    }
451}
452
453impl<F> Compatible for PathBeneath<F> {}
454
455impl<F> Compatible for &mut PathBeneath<F> {}
456
457#[test]
458fn path_beneath_compatibility() {
459    let mut path = PathBeneath::new(PathFd::new("/").unwrap(), AccessFs::from_all(ABI::V1));
460    let path_ref = &mut path;
461
462    let level = path_ref.as_option_compat_level_mut();
463    assert_eq!(level, &None);
464    assert_eq!(
465        <Option<CompatLevel> as Into<CompatLevel>>::into(*level),
466        CompatLevel::BestEffort
467    );
468
469    path_ref.set_compatibility(CompatLevel::SoftRequirement);
470    assert_eq!(
471        path_ref.as_option_compat_level_mut(),
472        &Some(CompatLevel::SoftRequirement)
473    );
474
475    path.set_compatibility(CompatLevel::HardRequirement);
476}
477
478// It is useful for documentation generation to explicitely implement Rule for every types, instead
479// of doing it generically.
480impl<F> Rule<AccessFs> for PathBeneath<F> where F: AsFd {}
481
482impl<F> PrivateRule<AccessFs> for PathBeneath<F>
483where
484    F: AsFd,
485{
486    const TYPE_ID: uapi::landlock_rule_type = uapi::landlock_rule_type_LANDLOCK_RULE_PATH_BENEATH;
487
488    fn as_ptr(&mut self) -> *const libc::c_void {
489        self.attr.parent_fd = self.parent_fd.as_fd().as_raw_fd();
490        self.attr.allowed_access = self.allowed_access.bits();
491        &self.attr as *const _ as _
492    }
493
494    fn check_consistency(&self, ruleset: &RulesetCreated) -> Result<(), AddRulesError> {
495        // Checks that this rule doesn't contain a superset of the access-rights handled by the
496        // ruleset.  This check is about requested but not ABI-resolved access rights.
497        // Indeed, we want to get a deterministic behavior, i.e. not based on the running kernel
498        // (which is handled by Ruleset and RulesetCreated).
499        if !ruleset.fs.access.contains(self.allowed_access) {
500            return Err(AddRuleError::UnhandledAccess {
501                access: self.allowed_access,
502                incompatible: self.allowed_access & !ruleset.fs.access,
503            }
504            .into());
505        }
506        if self.quiet && ruleset.fs.quiet.is_empty() {
507            return Err(AddRuleError::<AccessFs>::MissingQuietAccess.into());
508        }
509        Ok(())
510    }
511
512    fn set_quiet(&mut self, quiet: bool) {
513        self.quiet = quiet;
514    }
515
516    fn set_quiet_compatibility(&mut self, compatibility: QuietRuleCompatibility) {
517        self.quiet_compatibility = compatibility;
518    }
519
520    fn add_rule_flags(&self) -> u32 {
521        if self.quiet {
522            uapi::LANDLOCK_ADD_RULE_QUIET
523        } else {
524            0
525        }
526    }
527}
528
529#[test]
530fn quiet_path_beneath_compatibility() {
531    use crate::*;
532
533    let mut state = CompatState::Init;
534    let mut rule =
535        PathBeneath::new(PathFd::new("/").unwrap(), BitFlags::<AccessFs>::EMPTY).quiet(true);
536    rule.set_quiet_compatibility(QuietRuleCompatibility::SupportedEffective);
537    let rule = rule
538        .try_compat(ABI::V10, CompatLevel::BestEffort, &mut state)
539        .unwrap()
540        .unwrap();
541    assert_eq!(rule.add_rule_flags(), uapi::LANDLOCK_ADD_RULE_QUIET);
542    assert_eq!(state, CompatState::Full);
543
544    // Models a future access right unsupported by a kernel that supports quiet rules.
545    let mut state = CompatState::Init;
546    let mut rule = PathBeneath::new(PathFd::new("/").unwrap(), AccessFs::ResolveUnix).quiet(true);
547    rule.set_quiet_compatibility(QuietRuleCompatibility::SupportedEffective);
548    let rule = rule
549        .try_compat(ABI::V8, CompatLevel::BestEffort, &mut state)
550        .unwrap()
551        .unwrap();
552    assert!(rule.allowed_access.is_empty());
553    assert_eq!(rule.add_rule_flags(), uapi::LANDLOCK_ADD_RULE_QUIET);
554    assert_eq!(state, CompatState::Partial);
555
556    // Quiet support is distinct from whether this ruleset has an effective
557    // quiet mask for the rule category.
558    let mut state = CompatState::Partial;
559    let mut rule =
560        PathBeneath::new(PathFd::new("/").unwrap(), BitFlags::<AccessFs>::EMPTY).quiet(true);
561    rule.set_quiet_compatibility(QuietRuleCompatibility::SupportedIneffective);
562    assert!(rule
563        .try_compat(ABI::V10, CompatLevel::HardRequirement, &mut state)
564        .unwrap()
565        .is_none());
566    assert_eq!(state, CompatState::Partial);
567
568    let mut state = CompatState::Partial;
569    let mut rule = PathBeneath::new(PathFd::new("/").unwrap(), AccessFs::ReadFile).quiet(true);
570    rule.set_quiet_compatibility(QuietRuleCompatibility::SupportedIneffective);
571    let rule = rule
572        .try_compat(ABI::V10, CompatLevel::HardRequirement, &mut state)
573        .unwrap()
574        .unwrap();
575    assert_eq!(rule.add_rule_flags(), 0);
576    assert_eq!(state, CompatState::Partial);
577
578    let mut state = CompatState::Dummy;
579    let mut rule =
580        PathBeneath::new(PathFd::new("/").unwrap(), BitFlags::<AccessFs>::EMPTY).quiet(true);
581    rule.set_quiet_compatibility(QuietRuleCompatibility::SupportedIneffective);
582    assert!(rule
583        .try_compat(ABI::V10, CompatLevel::SoftRequirement, &mut state)
584        .unwrap()
585        .is_none());
586    assert_eq!(state, CompatState::Dummy);
587
588    let mut state = CompatState::Init;
589    let mut rule =
590        PathBeneath::new(PathFd::new("/").unwrap(), BitFlags::<AccessFs>::EMPTY).quiet(true);
591    rule.set_quiet_compatibility(QuietRuleCompatibility::Unsupported);
592    assert!(rule
593        .try_compat(ABI::V9, CompatLevel::BestEffort, &mut state)
594        .unwrap()
595        .is_none());
596    assert_eq!(state, CompatState::Partial);
597
598    let mut state = CompatState::Init;
599    let mut rule = PathBeneath::new(PathFd::new("/").unwrap(), AccessFs::ReadFile).quiet(true);
600    rule.set_quiet_compatibility(QuietRuleCompatibility::Unsupported);
601    let rule = rule
602        .try_compat(ABI::V9, CompatLevel::BestEffort, &mut state)
603        .unwrap()
604        .unwrap();
605    assert_eq!(rule.add_rule_flags(), 0);
606    assert_eq!(state, CompatState::Partial);
607
608    let mut state = CompatState::Init;
609    let mut rule =
610        PathBeneath::new(PathFd::new("/").unwrap(), BitFlags::<AccessFs>::EMPTY).quiet(true);
611    rule.set_quiet_compatibility(QuietRuleCompatibility::Unsupported);
612    assert!(matches!(
613        rule.try_compat(ABI::V9, CompatLevel::HardRequirement, &mut state),
614        Err(CompatError::QuietNotSupported)
615    ));
616    assert_eq!(state, CompatState::Full);
617}
618
619#[test]
620fn path_beneath_check_consistency() {
621    use crate::*;
622
623    let ro_access = AccessFs::ReadDir | AccessFs::ReadFile;
624    let rx_access = AccessFs::Execute | AccessFs::ReadFile;
625    assert!(matches!(
626        Ruleset::from(ABI::Unsupported)
627            .handle_access(ro_access)
628            .unwrap()
629            .create()
630            .unwrap()
631            .add_rule(PathBeneath::new(PathFd::new("/").unwrap(), rx_access))
632            .unwrap_err(),
633        RulesetError::AddRules(AddRulesError::Fs(AddRuleError::UnhandledAccess { access, incompatible }))
634            if access == rx_access && incompatible == AccessFs::Execute
635    ));
636}
637
638/// Simple helper to open a file or a directory with the `O_PATH` flag.
639///
640/// This is the recommended way to identify a path
641/// and manage the lifetime of the underlying opened file descriptor.
642/// Indeed, using other [`AsFd`] implementations such as [`File`] brings more complexity
643/// and may lead to unexpected errors (e.g., denied access).
644///
645/// [`File`]: std::fs::File
646///
647/// # Example
648///
649/// ```
650/// use landlock::{AccessFs, PathBeneath, PathFd, PathFdError};
651///
652/// fn allowed_root_dir(access: AccessFs) -> Result<PathBeneath<PathFd>, PathFdError> {
653///     let fd = PathFd::new("/")?;
654///     Ok(PathBeneath::new(fd, access))
655/// }
656/// ```
657#[derive(Debug)]
658pub struct PathFd {
659    fd: OwnedFd,
660}
661
662impl PathFd {
663    pub fn new<T>(path: T) -> Result<Self, PathFdError>
664    where
665        T: AsRef<Path>,
666    {
667        let open = || -> Result<OwnedFd, Error> {
668            let path = CString::new(path.as_ref().as_os_str().as_bytes())?;
669            // std masks O_ACCMODE out of custom_flags, and musl includes O_PATH in O_ACCMODE.
670            // Linux kernels before 2.6.39 ignore O_PATH.
671            // This retry mirrors Rust's cvt_r() implementation:
672            // https://github.com/rust-lang/rust/blob/1.77.2/library/std/src/sys/pal/unix/mod.rs#L318-L329
673            let fd = loop {
674                // SAFETY: path is NUL-terminated, and these flags do not require a mode argument.
675                let fd = unsafe { libc::open(path.as_ptr(), libc::O_PATH | libc::O_CLOEXEC) };
676                if fd >= 0 {
677                    break fd;
678                }
679                let error = Error::last_os_error();
680                if error.kind() != ErrorKind::Interrupted {
681                    return Err(error);
682                }
683            };
684            // SAFETY: fd is valid, newly opened, and uniquely owned.
685            Ok(unsafe { OwnedFd::from_raw_fd(fd) })
686        };
687        Ok(PathFd {
688            fd: open().map_err(|e| PathFdError::OpenCall {
689                source: e,
690                path: path.as_ref().into(),
691            })?,
692        })
693    }
694}
695
696impl AsFd for PathFd {
697    fn as_fd(&self) -> BorrowedFd<'_> {
698        self.fd.as_fd()
699    }
700}
701
702#[test]
703fn path_fd() {
704    use std::fs::File;
705    use std::io::Read;
706
707    PathBeneath::new(PathFd::new("/").unwrap(), AccessFs::Execute);
708    PathBeneath::new(File::open("/").unwrap(), AccessFs::Execute);
709
710    let mut buffer = [0; 1];
711    // Checks that PathFd really returns an FD opened with O_PATH (Bad file descriptor error).
712    let error = File::from(PathFd::new("/etc/passwd").unwrap().fd)
713        .read(&mut buffer)
714        .unwrap_err();
715    assert_eq!(error.raw_os_error(), Some(libc::EBADF));
716}
717
718/// Helper to quickly create an iterator of PathBeneath rules.
719///
720/// # Note
721///
722/// From the kernel's perspective, Landlock rules operate on file descriptors, not paths.
723/// This is a helper to create rules based on paths. Here, `path_beneath_rules()` silently ignores
724/// paths that cannot be opened, hence making the obtainment of a file descriptor impossible. When
725/// possible and for a given path, `path_beneath_rules()` automatically adjusts [access rights](`AccessFs`),
726/// depending on whether a directory or a file is present at that said path.
727///
728/// This behavior is the result of [`CompatLevel::BestEffort`], which is the default compatibility level of
729/// all created rulesets. Thus, it applies to the example below. However, if [`CompatLevel::HardRequirement`]
730/// is set using [`Compatible::set_compatibility`], attempting to create an incompatible rule at runtime will cause
731/// this crate to raise an error instead.
732///
733/// # Example
734///
735/// ```
736/// use landlock::{
737///     ABI, Access, AccessFs, Ruleset, RulesetAttr, RulesetCreatedAttr, RulesetStatus, RulesetError,
738///     path_beneath_rules,
739/// };
740///
741/// fn restrict_thread() -> Result<(), RulesetError> {
742///     let abi = ABI::V1;
743///     let status = Ruleset::default()
744///         .handle_access(AccessFs::from_all(abi))?
745///         .create()?
746///         // Read-only access to /usr, /etc and /dev.
747///         .add_rules(path_beneath_rules(&["/usr", "/etc", "/dev"], AccessFs::from_read(abi)))?
748///         // Read-write access to /home and /tmp.
749///         .add_rules(path_beneath_rules(&["/home", "/tmp"], AccessFs::from_all(abi)))?
750///         .restrict_self()?;
751///     match status.ruleset {
752///         // The FullyEnforced case must be tested by the developer.
753///         RulesetStatus::FullyEnforced => println!("Fully sandboxed."),
754///         RulesetStatus::PartiallyEnforced => println!("Partially sandboxed."),
755///         // Users should be warned that they are not protected.
756///         RulesetStatus::NotEnforced => println!("Not sandboxed! Please update your kernel."),
757///     }
758///     Ok(())
759/// }
760/// ```
761pub fn path_beneath_rules<I, P, A>(
762    paths: I,
763    access: A,
764) -> impl Iterator<Item = Result<PathBeneath<PathFd>, RulesetError>>
765where
766    I: IntoIterator<Item = P>,
767    P: AsRef<Path>,
768    A: Into<BitFlags<AccessFs>>,
769{
770    let access = access.into();
771    paths.into_iter().filter_map(move |p| match PathFd::new(p) {
772        Ok(f) => {
773            let valid_access = match is_file(&f) {
774                Ok(true) => access & ACCESS_FILE,
775                // If the stat call failed, let's blindly rely on the requested access rights.
776                Err(_) | Ok(false) => access,
777            };
778            Some(Ok(PathBeneath::new(f, valid_access)))
779        }
780        Err(_) => None,
781    })
782}
783
784#[test]
785fn path_beneath_rules_iter() {
786    let _ = Ruleset::default()
787        .handle_access(AccessFs::from_all(ABI::V1))
788        .unwrap()
789        .create()
790        .unwrap()
791        .add_rules(path_beneath_rules(
792            &["/usr", "/opt", "/does-not-exist", "/root"],
793            AccessFs::Execute,
794        ))
795        .unwrap();
796}