#[cfg(feature = "alloc")]
use crate::ErrorKind;
use crate::{Result, sys};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
#[repr(u8)]
pub enum Capability {
Chown = 0,
DacOverride = 1,
DacReadSearch = 2,
Fowner = 3,
Fsetid = 4,
Kill = 5,
Setgid = 6,
Setuid = 7,
Setpcap = 8,
LinuxImmutable = 9,
NetBindService = 10,
NetBroadcast = 11,
NetAdmin = 12,
NetRaw = 13,
IpcLock = 14,
IpcOwner = 15,
SysModule = 16,
SysRawio = 17,
SysChroot = 18,
SysPtrace = 19,
SysPacct = 20,
SysAdmin = 21,
SysBoot = 22,
SysNice = 23,
SysResource = 24,
SysTime = 25,
SysTtyConfig = 26,
Mknod = 27,
Lease = 28,
AuditWrite = 29,
AuditControl = 30,
Setfcap = 31,
MacOverride = 32,
MacAdmin = 33,
Syslog = 34,
WakeAlarm = 35,
BlockSuspend = 36,
AuditRead = 37,
Perfmon = 38,
Bpf = 39,
CheckpointRestore = 40,
}
impl Capability {
pub const ALL: [Self; 41] = [
Self::Chown,
Self::DacOverride,
Self::DacReadSearch,
Self::Fowner,
Self::Fsetid,
Self::Kill,
Self::Setgid,
Self::Setuid,
Self::Setpcap,
Self::LinuxImmutable,
Self::NetBindService,
Self::NetBroadcast,
Self::NetAdmin,
Self::NetRaw,
Self::IpcLock,
Self::IpcOwner,
Self::SysModule,
Self::SysRawio,
Self::SysChroot,
Self::SysPtrace,
Self::SysPacct,
Self::SysAdmin,
Self::SysBoot,
Self::SysNice,
Self::SysResource,
Self::SysTime,
Self::SysTtyConfig,
Self::Mknod,
Self::Lease,
Self::AuditWrite,
Self::AuditControl,
Self::Setfcap,
Self::MacOverride,
Self::MacAdmin,
Self::Syslog,
Self::WakeAlarm,
Self::BlockSuspend,
Self::AuditRead,
Self::Perfmon,
Self::Bpf,
Self::CheckpointRestore,
];
#[inline]
pub const fn number(self) -> u32 {
self as u32
}
pub const fn from_number(number: u32) -> Option<Self> {
if (number as usize) < Self::ALL.len() {
Some(Self::ALL[number as usize])
} else {
None
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct CapabilitySet(u64);
impl CapabilitySet {
pub const EMPTY: Self = Self(0);
#[inline]
pub const fn empty() -> Self {
Self(0)
}
pub const fn of(capabilities: &[Capability]) -> Self {
let mut bits = 0;
let mut i = 0;
while i < capabilities.len() {
bits |= 1 << capabilities[i].number();
i += 1;
}
Self(bits)
}
#[inline]
pub const fn from_bits(bits: u64) -> Self {
Self(bits)
}
#[inline]
pub const fn bits(self) -> u64 {
self.0
}
#[inline]
pub const fn is_empty(self) -> bool {
self.0 == 0
}
#[inline]
pub const fn contains(self, capability: Capability) -> bool {
self.0 & 1 << capability.number() != 0
}
#[inline]
pub const fn is_superset(self, other: Self) -> bool {
self.0 & other.0 == other.0
}
#[inline]
#[must_use]
pub const fn with(self, capability: Capability) -> Self {
Self(self.0 | 1 << capability.number())
}
#[inline]
#[must_use]
pub const fn without(self, capability: Capability) -> Self {
Self(self.0 & !(1 << capability.number()))
}
#[inline]
#[must_use]
pub const fn union(self, other: Self) -> Self {
Self(self.0 | other.0)
}
#[inline]
#[must_use]
pub const fn intersection(self, other: Self) -> Self {
Self(self.0 & other.0)
}
#[inline]
#[must_use]
pub const fn difference(self, other: Self) -> Self {
Self(self.0 & !other.0)
}
#[inline]
pub fn insert(&mut self, capability: Capability) {
*self = self.with(capability);
}
#[inline]
pub fn remove(&mut self, capability: Capability) {
*self = self.without(capability);
}
pub fn iter(self) -> impl Iterator<Item = Capability> {
Capability::ALL
.into_iter()
.filter(move |&capability| self.contains(capability))
}
}
impl From<Capability> for CapabilitySet {
#[inline]
fn from(capability: Capability) -> Self {
Self::empty().with(capability)
}
}
impl FromIterator<Capability> for CapabilitySet {
fn from_iter<I: IntoIterator<Item = Capability>>(iter: I) -> Self {
iter.into_iter().fold(Self::empty(), Self::with)
}
}
impl core::ops::BitOr for CapabilitySet {
type Output = Self;
#[inline]
fn bitor(self, other: Self) -> Self {
self.union(other)
}
}
impl core::ops::BitOr<Capability> for CapabilitySet {
type Output = Self;
#[inline]
fn bitor(self, capability: Capability) -> Self {
self.with(capability)
}
}
impl core::ops::BitAnd for CapabilitySet {
type Output = Self;
#[inline]
fn bitand(self, other: Self) -> Self {
self.intersection(other)
}
}
impl core::ops::Sub for CapabilitySet {
type Output = Self;
#[inline]
fn sub(self, other: Self) -> Self {
self.difference(other)
}
}
impl core::fmt::Debug for CapabilitySet {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let mut set = f.debug_set();
set.entries(self.iter());
for number in Capability::ALL.len() as u32..64 {
if self.0 & 1 << number != 0 {
set.entry(&number);
}
}
set.finish()
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Capabilities {
pub effective: CapabilitySet,
pub permitted: CapabilitySet,
pub inheritable: CapabilitySet,
}
impl Capabilities {
pub const fn all_three(set: CapabilitySet) -> Self {
Self {
effective: set,
permitted: set,
inheritable: set,
}
}
}
pub fn capabilities() -> Result<Capabilities> {
let [effective, permitted, inheritable] = sys::process::cred::capabilities()?;
Ok(Capabilities {
effective: CapabilitySet(effective),
permitted: CapabilitySet(permitted),
inheritable: CapabilitySet(inheritable),
})
}
pub fn set_capabilities(capabilities: &Capabilities) -> Result<()> {
sys::process::cred::set_capabilities([
capabilities.effective.0,
capabilities.permitted.0,
capabilities.inheritable.0,
])
}
pub fn bounding_set() -> Result<CapabilitySet> {
sys::process::cred::probe(sys::process::cred::has_bounding).map(CapabilitySet)
}
pub fn drop_bounding(capability: Capability) -> Result<()> {
sys::process::cred::drop_bounding(capability.number())
}
pub fn ambient_set() -> Result<CapabilitySet> {
sys::process::cred::probe(sys::process::cred::has_ambient).map(CapabilitySet)
}
pub fn raise_ambient(capability: Capability) -> Result<()> {
sys::process::cred::raise_ambient(capability.number())
}
pub fn lower_ambient(capability: Capability) -> Result<()> {
sys::process::cred::lower_ambient(capability.number())
}
pub fn clear_ambient() -> Result<()> {
sys::process::cred::clear_ambient()
}
pub fn keep_capabilities() -> Result<bool> {
sys::process::cred::keep_capabilities()
}
pub fn set_keep_capabilities(keep: bool) -> Result<()> {
sys::process::cred::set_keep_capabilities(keep)
}
crate::macros::flags! {
pub struct SecureBits: u32 {
const NO_ROOT = 1;
const NO_ROOT_LOCKED = 1 << 1;
const NO_SETUID_FIXUP = 1 << 2;
const NO_SETUID_FIXUP_LOCKED = 1 << 3;
const KEEP_CAPS = 1 << 4;
const KEEP_CAPS_LOCKED = 1 << 5;
const NO_CAP_AMBIENT_RAISE = 1 << 6;
const NO_CAP_AMBIENT_RAISE_LOCKED = 1 << 7;
}
}
pub fn secure_bits() -> Result<SecureBits> {
sys::process::cred::secure_bits().map(SecureBits)
}
pub fn set_secure_bits(bits: SecureBits) -> Result<()> {
sys::process::cred::set_secure_bits(bits.bits())
}
pub fn user_id() -> u32 {
sys::process::cred::ids()[0]
}
pub fn effective_user_id() -> u32 {
sys::process::cred::ids()[1]
}
pub fn group_id() -> u32 {
sys::process::cred::ids()[2]
}
pub fn effective_group_id() -> u32 {
sys::process::cred::ids()[3]
}
pub fn groups(buf: &mut [u32]) -> Result<usize> {
sys::process::cred::groups(buf)
}
#[cfg(feature = "alloc")]
pub fn groups_vec() -> Result<alloc::vec::Vec<u32>> {
let mut groups = alloc::vec::Vec::new();
loop {
let count = sys::process::cred::groups(&mut [])?;
groups.clear();
groups
.try_reserve_exact(count)
.map_err(|_| ErrorKind::OutOfMemory)?;
groups.resize(count, 0);
match sys::process::cred::groups(&mut groups) {
Ok(count) => {
groups.truncate(count);
return Ok(groups);
}
Err(error) if error.kind() == ErrorKind::InvalidInput && count > 0 => {}
Err(error) => return Err(error),
}
}
}
pub fn set_user_ids(real: Option<u32>, effective: Option<u32>, saved: Option<u32>) -> Result<()> {
sys::process::cred::set_user_ids([real, effective, saved])
}
pub fn set_group_ids(real: Option<u32>, effective: Option<u32>, saved: Option<u32>) -> Result<()> {
sys::process::cred::set_group_ids([real, effective, saved])
}
pub fn set_groups(groups: &[u32]) -> Result<()> {
sys::process::cred::set_groups(groups)
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct SystemName(sys::process::cred::UtsName);
impl SystemName {
fn field(&self, index: usize) -> &[u8] {
let field = &self.0[index];
let len = field.iter().position(|&byte| byte == 0);
&field[..len.unwrap_or(field.len())]
}
pub fn system(&self) -> &[u8] {
self.field(0)
}
pub fn host_name(&self) -> &[u8] {
self.field(1)
}
pub fn release(&self) -> &[u8] {
self.field(2)
}
pub fn version(&self) -> &[u8] {
self.field(3)
}
pub fn machine(&self) -> &[u8] {
self.field(4)
}
pub fn domain_name(&self) -> &[u8] {
self.field(5)
}
}
impl core::fmt::Debug for SystemName {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let mut debug = f.debug_struct("SystemName");
let fields: [(&str, &[u8]); 6] = [
("system", self.system()),
("host_name", self.host_name()),
("release", self.release()),
("version", self.version()),
("machine", self.machine()),
("domain_name", self.domain_name()),
];
for (name, value) in fields {
debug.field(name, &format_args!("\"{}\"", value.escape_ascii()));
}
debug.finish()
}
}
pub fn system_name() -> Result<SystemName> {
sys::process::cred::uname().map(SystemName)
}