use anyhow::{Context, Result};
use landlock::{
ABI, Access, AccessFs, AccessNet, BitFlags, LandlockStatus, PathBeneath, PathFd, Ruleset,
RulesetAttr, RulesetCreatedAttr, RulesetStatus, Scope,
};
use std::path::Path;
use crate::{SandboxConfig, SandboxMode};
const ABI_FS: ABI = ABI::V4;
const ABI_SCOPE: ABI = ABI::V6;
const ACCOUNT_DATABASE_PATHS: [&str; 3] = ["/etc/passwd", "/etc/group", "/etc/nsswitch.conf"];
pub(super) struct LandlockResult {
pub fs_applied: bool,
pub net_applied: bool,
pub scope_applied: bool,
pub effective_abi: Option<u8>,
pub message: String,
}
fn abi_version(abi: ABI) -> u8 {
match abi {
ABI::Unsupported => 0,
ABI::V1 => 1,
ABI::V2 => 2,
ABI::V3 => 3,
ABI::V4 => 4,
ABI::V5 => 5,
ABI::V6 => 6,
ABI::V7 => 7,
_ => 0,
}
}
pub(super) fn is_available() -> bool {
Ruleset::default()
.handle_access(AccessFs::Execute)
.and_then(|r| r.create())
.is_ok()
}
pub(super) fn apply_landlock(config: &SandboxConfig) -> Result<LandlockResult> {
if config.mode == SandboxMode::Disabled {
return Ok(LandlockResult {
fs_applied: false,
net_applied: false,
scope_applied: false,
effective_abi: None,
message: "Sandbox disabled".to_string(),
});
}
let abi = ABI_FS;
let read_access = AccessFs::from_read(abi);
let write_access = AccessFs::WriteFile
| AccessFs::ReadFile
| AccessFs::ReadDir
| AccessFs::MakeReg
| AccessFs::Truncate;
let mut ruleset = Ruleset::default()
.handle_access(AccessFs::from_all(abi))
.context("Failed to handle filesystem access")?;
if config.block_network {
ruleset = ruleset
.handle_access(AccessNet::BindTcp)
.and_then(|r| r.handle_access(AccessNet::ConnectTcp))
.context("Failed to handle TCP network access")?
.scope(Scope::from_all(ABI_SCOPE))
.context("Failed to handle scope restrictions")?;
}
let mut ruleset_created = ruleset
.create()
.context("Failed to create Landlock ruleset")?;
if let Err(e) = add_path_rule(&mut ruleset_created, "/proc", read_access) {
log::warn!("Could not add /proc rule: {}", e);
}
for account_path in ACCOUNT_DATABASE_PATHS {
if Path::new(account_path).exists()
&& let Err(e) = add_path_rule(
&mut ruleset_created,
account_path,
AccessFs::ReadFile.into(),
)
{
log::warn!("Could not add account database rule for {account_path}: {e}");
}
}
for sysfs_path in ["/sys/class/net", "/sys/devices"] {
if let Err(e) = add_path_rule(&mut ruleset_created, sysfs_path, read_access) {
log::warn!("Could not add {} rule: {}", sysfs_path, e);
}
}
for path in &config.read_paths {
if path.exists()
&& let Err(e) = add_path_rule(&mut ruleset_created, path, read_access)
{
log::warn!("Could not add read rule for {:?}: {}", path, e);
}
}
for path in &config.write_paths {
if path.exists() {
if let Err(e) = add_path_rule(&mut ruleset_created, path, write_access) {
log::warn!("Could not add write rule for {:?}: {}", path, e);
}
} else {
if let Some(parent) = path.parent()
&& parent.exists()
{
log::warn!(
"Write path {:?} does not exist; granting write to parent {:?}",
path,
parent
);
if let Err(e) = add_path_rule(&mut ruleset_created, parent, write_access) {
log::warn!("Could not add write rule for parent {:?}: {}", parent, e);
}
}
}
}
let status = ruleset_created
.restrict_self()
.context("Failed to apply Landlock restrictions")?;
let fs_applied = matches!(
status.ruleset,
RulesetStatus::FullyEnforced | RulesetStatus::PartiallyEnforced
);
let net_applied = config.block_network
&& fs_applied
&& matches!(
status.landlock,
LandlockStatus::Available { effective_abi, .. } if effective_abi >= ABI::V4
);
let scope_applied = config.block_network
&& fs_applied
&& matches!(
status.landlock,
LandlockStatus::Available { effective_abi, .. } if effective_abi >= ABI_SCOPE
);
let effective_abi = match status.landlock {
LandlockStatus::Available { effective_abi, .. } if fs_applied => {
Some(abi_version(effective_abi))
}
_ => None,
};
let message = match (&status.ruleset, &status.landlock) {
(RulesetStatus::FullyEnforced, _) => "Landlock fully enforced".to_string(),
(RulesetStatus::PartiallyEnforced, _) => "Landlock partially enforced".to_string(),
(RulesetStatus::NotEnforced, LandlockStatus::NotEnabled) => {
"Landlock disabled in kernel".to_string()
}
(RulesetStatus::NotEnforced, LandlockStatus::NotImplemented) => {
"Landlock not implemented in kernel".to_string()
}
(RulesetStatus::NotEnforced, _) => "Landlock not enforced".to_string(),
};
log::info!("Landlock: {}", message);
log::info!(
"Landlock: filesystem={}, network={}, scope={}, landlock_status={:?}",
fs_applied,
net_applied,
scope_applied,
status.landlock
);
Ok(LandlockResult {
fs_applied,
net_applied,
scope_applied,
effective_abi,
message,
})
}
fn add_path_rule(
ruleset: &mut landlock::RulesetCreated,
path: impl AsRef<Path>,
access: BitFlags<AccessFs>,
) -> Result<()> {
let path = path.as_ref();
let fd = PathFd::new(path).with_context(|| format!("Failed to open {:?}", path))?;
ruleset
.add_rule(PathBeneath::new(fd, access))
.with_context(|| format!("Failed to add rule for {:?}", path))?;
log::debug!("Landlock: Added rule for {:?}", path);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_available_does_not_panic() {
let _ = is_available();
}
#[test]
fn test_disabled_mode() {
let config = SandboxConfig {
mode: SandboxMode::Disabled,
block_network: true,
read_paths: vec![],
write_paths: vec![],
drop_uid: None,
};
let result = apply_landlock(&config).unwrap();
assert!(!result.fs_applied);
assert!(!result.net_applied);
assert!(!result.scope_applied);
assert_eq!(result.effective_abi, None);
}
#[test]
fn test_best_effort_does_not_panic() {
let config = SandboxConfig {
mode: SandboxMode::BestEffort,
block_network: true,
read_paths: vec![],
write_paths: vec![],
drop_uid: None,
};
let result = apply_landlock(&config).expect("best-effort must not error");
assert!(result.fs_applied || !result.scope_applied);
}
}