use anyhow::{Context, Result};
use landlock::{
ABI, Access, AccessFs, AccessNet, BitFlags, LandlockStatus, NetPort, 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"];
const DNS_RESOLVER_PATHS: [&str; 3] = ["/etc/host.conf", "/etc/hosts", "/etc/resolv.conf"];
const DNS_TCP_CONNECT_PORTS: [u16; 1] = [53];
fn dns_resolver_paths(allow_dns_resolution: bool) -> &'static [&'static str] {
if allow_dns_resolution {
&DNS_RESOLVER_PATHS
} else {
&[]
}
}
fn allowed_tcp_connect_ports(config: &SandboxConfig, allow_dns_resolution: bool) -> &'static [u16] {
if config.block_network && allow_dns_resolution {
&DNS_TCP_CONNECT_PORTS
} else {
&[]
}
}
pub(super) struct LandlockResult {
pub fs_applied: bool,
pub fs_fully_enforced: 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,
allow_dns_resolution: bool,
) -> Result<LandlockResult> {
if config.mode == SandboxMode::Disabled {
return Ok(LandlockResult {
fs_applied: false,
fs_fully_enforced: 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 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")?;
let mut path_rule_failures = Vec::new();
add_policy_path_rule(
&mut ruleset_created,
Path::new("/proc"),
read_access,
config.mode,
&mut path_rule_failures,
)?;
for account_path in ACCOUNT_DATABASE_PATHS {
let account_path = Path::new(account_path);
if account_path.exists() {
add_policy_path_rule(
&mut ruleset_created,
account_path,
AccessFs::ReadFile.into(),
config.mode,
&mut path_rule_failures,
)?;
}
}
for resolver_path in dns_resolver_paths(allow_dns_resolution) {
let resolver_path = Path::new(resolver_path);
if resolver_path.exists() {
add_policy_path_rule(
&mut ruleset_created,
resolver_path,
AccessFs::ReadFile.into(),
config.mode,
&mut path_rule_failures,
)?;
}
}
for sysfs_path in ["/sys/class/net", "/sys/devices"] {
add_policy_path_rule(
&mut ruleset_created,
Path::new(sysfs_path),
read_access,
config.mode,
&mut path_rule_failures,
)?;
}
for path in &config.read_paths {
if path.exists() {
add_policy_path_rule(
&mut ruleset_created,
path,
read_access,
config.mode,
&mut path_rule_failures,
)?;
} else {
record_missing_path(config.mode, path, &mut path_rule_failures)?;
}
}
for port in allowed_tcp_connect_ports(config, allow_dns_resolution) {
ruleset_created = ruleset_created
.add_rule(NetPort::new(*port, AccessNet::ConnectTcp))
.with_context(|| format!("Failed to allow TCP connect to DNS port {port}"))?;
}
let status = ruleset_created
.restrict_self()
.context("Failed to apply Landlock restrictions")?;
let fs_applied = matches!(
status.ruleset,
RulesetStatus::FullyEnforced | RulesetStatus::PartiallyEnforced
);
let fs_fully_enforced =
path_rule_failures.is_empty() && matches!(status.ruleset, RulesetStatus::FullyEnforced);
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 mut 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(),
};
if !path_rule_failures.is_empty() {
message.push_str(&format!(
"; {} filesystem path rule(s) incomplete",
path_rule_failures.len()
));
}
log::info!("Landlock: {}", message);
log::info!(
"Landlock: filesystem={}, network={}, scope={}, landlock_status={:?}",
fs_applied,
net_applied,
scope_applied,
status.landlock
);
Ok(LandlockResult {
fs_applied,
fs_fully_enforced,
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(())
}
fn add_policy_path_rule(
ruleset: &mut landlock::RulesetCreated,
path: &Path,
access: BitFlags<AccessFs>,
mode: SandboxMode,
failures: &mut Vec<String>,
) -> Result<()> {
if let Err(error) = add_path_rule(ruleset, path, access) {
if mode == SandboxMode::Strict {
return Err(error)
.with_context(|| format!("Strict mode requires the Landlock rule for {:?}", path));
}
log::warn!("Could not add Landlock rule for {:?}: {}", path, error);
failures.push(path.display().to_string());
}
Ok(())
}
fn record_missing_path(mode: SandboxMode, path: &Path, failures: &mut Vec<String>) -> Result<()> {
if mode == SandboxMode::Strict {
anyhow::bail!(
"Strict mode requires configured sandbox path {:?} to exist",
path
);
}
log::warn!("Configured sandbox path {:?} does not exist", path);
failures.push(path.display().to_string());
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![],
drop_uid: None,
};
let result = apply_landlock(&config, true).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![],
drop_uid: None,
};
let result = apply_landlock(&config, true).expect("best-effort must not error");
assert!(result.fs_applied || !result.scope_applied);
}
#[test]
fn test_dns_resolver_file_policy_is_exact() {
assert_eq!(dns_resolver_paths(false), &[] as &[&str]);
assert_eq!(
dns_resolver_paths(true),
["/etc/host.conf", "/etc/hosts", "/etc/resolv.conf"]
);
}
#[test]
fn test_dns_tcp_connect_policy_is_exact() {
let blocked_without_dns = SandboxConfig {
block_network: true,
..SandboxConfig::default()
};
assert_eq!(
allowed_tcp_connect_ports(&blocked_without_dns, false),
&[] as &[u16]
);
let blocked_with_dns = SandboxConfig {
block_network: true,
..SandboxConfig::default()
};
assert_eq!(allowed_tcp_connect_ports(&blocked_with_dns, true), [53]);
let unrestricted = SandboxConfig::default();
assert_eq!(
allowed_tcp_connect_ports(&unrestricted, true),
&[] as &[u16]
);
}
#[test]
fn strict_mode_rejects_a_missing_requested_path() {
let mut failures = Vec::new();
let error = record_missing_path(
SandboxMode::Strict,
Path::new("/rustnet-test-path-that-does-not-exist"),
&mut failures,
)
.unwrap_err();
assert!(
error
.to_string()
.contains("requires configured sandbox path")
);
assert!(failures.is_empty());
}
#[test]
fn best_effort_records_a_missing_requested_path() {
let mut failures = Vec::new();
record_missing_path(
SandboxMode::BestEffort,
Path::new("/rustnet-test-path-that-does-not-exist"),
&mut failures,
)
.unwrap();
assert_eq!(failures.len(), 1);
}
}