landlock

Function path_beneath_rules

Source
pub fn path_beneath_rules<I, P, A>(
    paths: I,
    access: A,
) -> impl Iterator<Item = Result<PathBeneath<PathFd>, RulesetError>>
where I: IntoIterator<Item = P>, P: AsRef<Path>, A: Into<BitFlags<AccessFs>>,
Expand description

Helper to quickly create an iterator of PathBeneath rules.

§Note

Landlock rules operate on file descriptors, not paths. This is a helper to create rules based on paths. It silently ignores paths that cannot be opened, and automatically adjusts access rights according to file types when possible.

§Example

use landlock::{
    ABI, Access, AccessFs, Ruleset, RulesetAttr, RulesetCreatedAttr, RulesetStatus, RulesetError,
    path_beneath_rules,
};

fn restrict_thread() -> Result<(), RulesetError> {
    let abi = ABI::V1;
    let status = Ruleset::default()
        .handle_access(AccessFs::from_all(abi))?
        .create()?
        // Read-only access to /usr, /etc and /dev.
        .add_rules(path_beneath_rules(&["/usr", "/etc", "/dev"], AccessFs::from_read(abi)))?
        // Read-write access to /home and /tmp.
        .add_rules(path_beneath_rules(&["/home", "/tmp"], AccessFs::from_all(abi)))?
        .restrict_self()?;
    match status.ruleset {
        // The FullyEnforced case must be tested by the developer.
        RulesetStatus::FullyEnforced => println!("Fully sandboxed."),
        RulesetStatus::PartiallyEnforced => println!("Partially sandboxed."),
        // Users should be warned that they are not protected.
        RulesetStatus::NotEnforced => println!("Not sandboxed! Please update your kernel."),
    }
    Ok(())
}