use std::path::PathBuf;
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
pub mod privdrop;
#[cfg(target_os = "freebsd")]
mod freebsd;
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "windows")]
mod windows;
#[cfg(all(target_os = "linux", feature = "landlock"))]
pub use linux::capabilities;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SandboxMode {
#[default]
BestEffort,
Strict,
Disabled,
}
#[derive(Debug)]
pub struct PrivilegeDropError;
impl std::fmt::Display for PrivilegeDropError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("required root UID/GID drop failed")
}
}
impl std::error::Error for PrivilegeDropError {}
impl SandboxMode {
pub fn from_flags(no_sandbox: bool, strict: bool) -> Self {
if no_sandbox {
SandboxMode::Disabled
} else if strict {
SandboxMode::Strict
} else {
SandboxMode::BestEffort
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SandboxStatus {
FullyEnforced,
PartiallyEnforced,
#[default]
NotApplied,
Error,
}
impl SandboxStatus {
pub fn label(&self) -> &'static str {
match self {
SandboxStatus::FullyEnforced => "Fully enforced",
SandboxStatus::PartiallyEnforced => "Partially enforced",
SandboxStatus::NotApplied => "Not applied",
SandboxStatus::Error => "Error",
}
}
}
#[derive(Debug, Clone, Default)]
pub struct SandboxConfig {
pub mode: SandboxMode,
pub block_network: bool,
pub read_paths: Vec<PathBuf>,
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
pub drop_uid: Option<privdrop::DropTarget>,
}
#[derive(Debug, Clone, Default)]
pub struct SandboxReport {
pub status: SandboxStatus,
pub message: String,
pub fs_restricted: bool,
pub net_restricted: bool,
pub uid_dropped: bool,
#[cfg(target_os = "linux")]
pub cap_net_raw_dropped: bool,
#[cfg(target_os = "linux")]
pub ebpf_caps_dropped: bool,
#[cfg(target_os = "linux")]
pub scope_restricted: bool,
#[cfg(target_os = "linux")]
pub landlock_available: bool,
#[cfg(target_os = "linux")]
pub landlock_abi: Option<u8>,
#[cfg(target_os = "linux")]
pub no_new_privs: bool,
#[cfg(target_os = "macos")]
pub seatbelt_applied: bool,
#[cfg(target_os = "windows")]
pub privileges_removed: bool,
#[cfg(target_os = "windows")]
pub privileges_removed_count: u32,
#[cfg(target_os = "windows")]
pub job_object_applied: bool,
}
impl SandboxReport {
pub fn from_error(error: &anyhow::Error) -> Self {
Self {
status: SandboxStatus::Error,
message: error.to_string(),
..Self::default()
}
}
#[cfg(any(target_os = "macos", target_os = "freebsd"))]
pub(crate) fn uid_drop_only(banner: &str, outcome: &UidDropOutcome) -> Self {
Self {
status: if outcome.dropped {
SandboxStatus::PartiallyEnforced
} else {
SandboxStatus::NotApplied
},
message: outcome.message_after(banner),
uid_dropped: outcome.dropped,
..Self::default()
}
}
}
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
pub(crate) struct UidDropOutcome {
pub(crate) dropped: bool,
pub(crate) message: Option<String>,
}
#[cfg(any(target_os = "macos", target_os = "freebsd"))]
impl UidDropOutcome {
pub(crate) fn message_after(&self, banner: &str) -> String {
match &self.message {
Some(message) => format!("{}; {}", banner, message),
None => banner.to_string(),
}
}
}
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
pub(crate) fn drop_root_step(
config: &SandboxConfig,
attribution_note: &str,
) -> anyhow::Result<UidDropOutcome> {
let Some(target) = config.drop_uid else {
return Ok(UidDropOutcome {
dropped: false,
message: None,
});
};
privdrop::drop_to(target).map_err(|error| error.context(PrivilegeDropError))?;
log::info!("Dropped root privileges (verified); {}", attribution_note);
Ok(UidDropOutcome {
dropped: true,
message: Some(format!(
"root dropped to uid {} gid {}",
target.uid, target.gid
)),
})
}
pub fn apply_sandbox(config: &SandboxConfig) -> anyhow::Result<SandboxReport> {
apply_sandbox_with_policy(config, false)
}
pub fn apply_sandbox_allowing_dns(config: &SandboxConfig) -> anyhow::Result<SandboxReport> {
apply_sandbox_with_policy(config, true)
}
fn apply_sandbox_with_policy(
config: &SandboxConfig,
allow_dns_resolution: bool,
) -> anyhow::Result<SandboxReport> {
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
let _ = allow_dns_resolution;
#[cfg(target_os = "linux")]
return linux::apply(config, allow_dns_resolution);
#[cfg(target_os = "macos")]
return macos::apply(config, allow_dns_resolution);
#[cfg(target_os = "windows")]
return windows::apply(config);
#[cfg(target_os = "freebsd")]
return freebsd::apply(config);
#[cfg(not(any(
target_os = "linux",
target_os = "macos",
target_os = "windows",
target_os = "freebsd"
)))]
{
log::warn!("Sandboxing not implemented for this platform");
let _ = (config, allow_dns_resolution);
Ok(SandboxReport {
message: "Sandboxing not implemented for this platform".to_string(),
..SandboxReport::default()
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_mode_from_flags() {
assert_eq!(
SandboxMode::from_flags(false, false),
SandboxMode::BestEffort
);
assert_eq!(SandboxMode::from_flags(false, true), SandboxMode::Strict);
assert_eq!(SandboxMode::from_flags(true, false), SandboxMode::Disabled);
}
#[test]
fn test_report_from_error_defaults_everything_off() {
let report = SandboxReport::from_error(&anyhow::anyhow!("boom"));
assert_eq!(report.status, SandboxStatus::Error);
assert_eq!(report.message, "boom");
assert!(!report.fs_restricted);
assert!(!report.net_restricted);
assert!(!report.uid_dropped);
}
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
#[test]
fn requested_uid_drop_failure_is_fatal_in_every_enforcing_mode() {
for mode in [SandboxMode::BestEffort, SandboxMode::Strict] {
let config = SandboxConfig {
mode,
drop_uid: Some(privdrop::DropTarget { uid: 0, gid: 0 }),
..SandboxConfig::default()
};
let error = drop_root_step(&config, "test attribution")
.err()
.expect("a requested identity drop must fail closed");
assert!(error.is::<PrivilegeDropError>());
assert!(format!("{error:#}").contains("refusing to 'drop' to uid 0 / gid 0"));
}
}
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
#[test]
fn absent_uid_drop_target_preserves_explicit_opt_out() {
for mode in [SandboxMode::BestEffort, SandboxMode::Strict] {
let config = SandboxConfig {
mode,
drop_uid: None,
..SandboxConfig::default()
};
let outcome = drop_root_step(&config, "test attribution").unwrap();
assert!(!outcome.dropped);
assert!(outcome.message.is_none());
}
}
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
#[test]
fn disabled_sandbox_does_not_attempt_uid_drop() {
let report = apply_sandbox(&SandboxConfig {
mode: SandboxMode::Disabled,
drop_uid: Some(privdrop::DropTarget { uid: 0, gid: 0 }),
..SandboxConfig::default()
})
.unwrap();
assert!(!report.uid_dropped);
assert_eq!(report.status, SandboxStatus::NotApplied);
}
}