use anyhow::{Context, Result};
use caps::{CapSet, Capability};
pub(crate) fn drop_cap_net_raw() -> Result<bool> {
let has_cap = caps::has_cap(None, CapSet::Effective, Capability::CAP_NET_RAW)
.context("Failed to check CAP_NET_RAW in effective set")?;
if !has_cap {
log::debug!("CAP_NET_RAW not in effective set, nothing to drop");
return Ok(false);
}
caps::drop(None, CapSet::Effective, Capability::CAP_NET_RAW)
.context("Failed to drop CAP_NET_RAW from effective set")?;
log::debug!("Dropped CAP_NET_RAW from effective set");
if caps::has_cap(None, CapSet::Permitted, Capability::CAP_NET_RAW).unwrap_or(false) {
if let Err(e) = caps::drop(None, CapSet::Permitted, Capability::CAP_NET_RAW) {
log::warn!("Could not drop CAP_NET_RAW from permitted set: {}", e);
} else {
log::debug!("Dropped CAP_NET_RAW from permitted set");
}
}
Ok(true)
}
pub(crate) fn has_cap_net_raw() -> bool {
caps::has_cap(None, CapSet::Effective, Capability::CAP_NET_RAW).unwrap_or(false)
}
pub(crate) fn drop_ebpf_caps() -> Result<u32> {
let mut dropped = 0;
for cap in [Capability::CAP_BPF, Capability::CAP_PERFMON] {
let has_effective = caps::has_cap(None, CapSet::Effective, cap).unwrap_or(false);
if !has_effective {
continue;
}
caps::drop(None, CapSet::Effective, cap)
.with_context(|| format!("Failed to drop {:?} from effective set", cap))?;
if caps::has_cap(None, CapSet::Permitted, cap).unwrap_or(false)
&& let Err(e) = caps::drop(None, CapSet::Permitted, cap)
{
log::warn!("Could not drop {:?} from permitted set: {}", cap, e);
}
log::debug!("Dropped {:?}", cap);
dropped += 1;
}
Ok(dropped)
}
pub fn drop_thread_cap_net_raw(thread: &str) {
match drop_cap_net_raw() {
Ok(_) => log::debug!("Dropped CAP_NET_RAW in {thread}"),
Err(e) => log::warn!("Failed to drop CAP_NET_RAW in {thread}: {e}"),
}
}
pub fn drop_unused_thread_caps(thread: &str) {
drop_thread_cap_net_raw(thread);
match drop_ebpf_caps() {
Ok(_) => log::debug!("Dropped eBPF capabilities in {thread}"),
Err(e) => log::warn!("Failed to drop eBPF capabilities in {thread}: {e}"),
}
}
pub(crate) fn clear_ambient_caps() -> Result<()> {
caps::clear(None, CapSet::Ambient).context("Failed to clear ambient capability set")?;
log::debug!("Cleared ambient capability set");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_has_cap_net_raw_does_not_panic() {
let _ = has_cap_net_raw();
}
#[test]
fn test_drop_cap_net_raw_without_capability() {
let result = drop_cap_net_raw();
assert!(result.is_ok());
}
#[test]
fn test_drop_ebpf_caps_does_not_panic() {
let result = drop_ebpf_caps();
assert!(result.is_ok());
}
}