|
| 1 | +use caps::{CapSet, Capability, CapsHashSet}; |
| 2 | +use nix::unistd::{getgid, getuid, setgid, setgroups, setuid}; |
| 3 | + |
| 4 | +#[derive(Debug)] |
| 5 | +pub enum Error { |
| 6 | + CapsReadError(caps::errors::CapsError), |
| 7 | + CapsUpdateError(caps::errors::CapsError), |
| 8 | + DropGroupsError(nix::Error), |
| 9 | + SetGidError(nix::Error), |
| 10 | + SetUidError(nix::Error), |
| 11 | + InsufficientCapabilities, |
| 12 | + NoCapabilities, |
| 13 | +} |
| 14 | + |
| 15 | +impl std::fmt::Display for Error { |
| 16 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 17 | + match self { |
| 18 | + Self::CapsReadError(e) => write!(f, "Failed to read process capabilities: {}", e), |
| 19 | + Self::CapsUpdateError(e) => write!(f, "Failed updating process capabilities: {}", e), |
| 20 | + Self::DropGroupsError(e) => write!(f, "Failed to drop supplementary groups: {}", e), |
| 21 | + Self::SetGidError(e) => write!(f, "Failed to setgid: {}", e), |
| 22 | + Self::SetUidError(e) => write!(f, "Failed to setuid: {}", e), |
| 23 | + Self::InsufficientCapabilities => write!( |
| 24 | + f, |
| 25 | + "Insufficient process capabilities, insecure memory might get used" |
| 26 | + ), |
| 27 | + Self::NoCapabilities => { |
| 28 | + write!(f, "No process capabilities, insecure memory might get used") |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +impl std::error::Error for Error {} |
| 35 | + |
| 36 | +pub fn drop_unnecessary_capabilities() -> Result<(), Error> { |
| 37 | + // Load current process capabilities |
| 38 | + let permitted_caps = caps::read(None, CapSet::Permitted).map_err(Error::CapsReadError)?; |
| 39 | + |
| 40 | + if permitted_caps.contains(&Capability::CAP_IPC_LOCK) { |
| 41 | + // Check if CAP_SETPCAP is available (needed to drop bounding set and groups) |
| 42 | + let has_setpcap = caps::has_cap(None, CapSet::Permitted, Capability::CAP_SETPCAP) |
| 43 | + .map_err(Error::CapsReadError)?; |
| 44 | + |
| 45 | + let mut drop_caps = CapsHashSet::new(); |
| 46 | + drop_caps.insert(Capability::CAP_IPC_LOCK); |
| 47 | + |
| 48 | + // Clear other capabilities and apply only CAP_IPC_LOCK |
| 49 | + caps::set(None, CapSet::Effective, &drop_caps).map_err(Error::CapsUpdateError)?; |
| 50 | + caps::set(None, CapSet::Permitted, &drop_caps).map_err(Error::CapsUpdateError)?; |
| 51 | + |
| 52 | + // Drop supplementary groups and switch to real UID/GID. |
| 53 | + if has_setpcap { |
| 54 | + setgroups(&[]).map_err(Error::DropGroupsError)?; |
| 55 | + setgid(getgid()).map_err(Error::SetGidError)?; |
| 56 | + setuid(getuid()).map_err(Error::SetUidError)?; |
| 57 | + } else { |
| 58 | + return Err(Error::InsufficientCapabilities); |
| 59 | + } |
| 60 | + } else if permitted_caps.is_empty() { |
| 61 | + return Err(Error::NoCapabilities); |
| 62 | + } else { |
| 63 | + return Err(Error::InsufficientCapabilities); |
| 64 | + } |
| 65 | + |
| 66 | + Ok(()) |
| 67 | +} |
0 commit comments