Skip to main content

byssus/privileges/
apply.rs

1//! Applying and verifying a privilege-normalization plan.
2
3use std::io;
4use std::os::fd::BorrowedFd;
5
6use rustix::fs::{Mode, OFlags, ResolveFlags};
7use rustix::process::{Gid, Uid};
8use rustix::thread::{CapabilitySet, CapabilitySets};
9
10use super::plan::{Credentials, Op, PrivilegePlan};
11use crate::fsops;
12
13/// The calling process's credential state.
14///
15/// Credentials come from system calls rather than `/proc/self/status`, so a
16/// file mounted over procfs cannot misreport them.
17#[derive(Debug, Clone, PartialEq, Eq, Default)]
18pub struct ProcessState {
19    /// Real, effective and saved UIDs.
20    pub uids: [u32; 3],
21    /// Real, effective and saved GIDs.
22    pub gids: [u32; 3],
23    /// Supplementary groups.
24    pub groups: Vec<u32>,
25    /// Number of threads.
26    pub threads: u32,
27    /// `CapInh`.
28    pub cap_inheritable: u64,
29    /// `CapPrm`.
30    pub cap_permitted: u64,
31    /// `CapEff`.
32    pub cap_effective: u64,
33    /// `CapBnd`.
34    pub cap_bounding: u64,
35    /// `CapAmb`.
36    pub cap_ambient: u64,
37    /// `NoNewPrivs`.
38    pub no_new_privs: bool,
39    /// Securebits.
40    pub secure_bits: u32,
41}
42
43impl ProcessState {
44    /// Reads the calling process's state. `proc` must be a verified procfs
45    /// descriptor (see [`crate::probe::verify_procfs`]); it is used only for
46    /// the thread count, which no system call reports.
47    pub fn read_self(proc: BorrowedFd<'_>) -> io::Result<Self> {
48        let caps = rustix::thread::capabilities(None)?;
49        Ok(Self {
50            uids: res_ids(libc::getresuid)?,
51            gids: res_ids(libc::getresgid)?,
52            groups: rustix::process::getgroups()?
53                .into_iter()
54                .map(Gid::as_raw)
55                .collect(),
56            threads: thread_count(proc)?,
57            cap_inheritable: caps.inheritable.bits(),
58            cap_permitted: caps.permitted.bits(),
59            cap_effective: caps.effective.bits(),
60            cap_bounding: read_set(rustix::thread::capability_is_in_bounding_set)?,
61            cap_ambient: read_set(rustix::thread::capability_is_in_ambient_set)?,
62            no_new_privs: rustix::thread::no_new_privs()?,
63            secure_bits: rustix::thread::capabilities_secure_bits()?.bits(),
64        })
65    }
66
67    /// Current credentials in the form the planner uses.
68    #[must_use]
69    pub fn credentials(&self) -> Credentials {
70        Credentials {
71            uids: self.uids,
72            caps: CapabilitySets {
73                effective: CapabilitySet::from_bits_retain(self.cap_effective),
74                permitted: CapabilitySet::from_bits_retain(self.cap_permitted),
75                inheritable: CapabilitySet::from_bits_retain(self.cap_inheritable),
76            },
77        }
78    }
79}
80
81/// Calls `getresuid` or `getresgid`.
82fn res_ids(
83    get: unsafe extern "C" fn(*mut u32, *mut u32, *mut u32) -> libc::c_int,
84) -> io::Result<[u32; 3]> {
85    let mut ids = [0u32; 3];
86    let [real, effective, saved] = &mut ids;
87    // SAFETY: `get` is `getresuid` or `getresgid`, and each pointer is valid
88    // for writing one ID.
89    let ret = unsafe { get(real, effective, saved) };
90    if ret == 0 {
91        Ok(ids)
92    } else {
93        Err(io::Error::last_os_error())
94    }
95}
96
97/// Reads a capability set one capability at a time, up to the first
98/// capability the kernel does not know.
99fn read_set(is_set: fn(CapabilitySet) -> rustix::io::Result<bool>) -> io::Result<u64> {
100    let mut bits = 0;
101    for n in 0..64 {
102        match is_set(CapabilitySet::from_bits_retain(1 << n)) {
103            Ok(true) => bits |= 1 << n,
104            Ok(false) => {}
105            Err(rustix::io::Errno::INVAL) if n > 0 => break,
106            Err(e) => return Err(e.into()),
107        }
108    }
109    Ok(bits)
110}
111
112/// Reads the thread count from `self/status` beneath the verified procfs
113/// descriptor, without crossing into anything mounted over procfs.
114fn thread_count(proc: BorrowedFd<'_>) -> io::Result<u32> {
115    let resolve = ResolveFlags::BENEATH | ResolveFlags::NO_XDEV | ResolveFlags::NO_MAGICLINKS;
116    let fd = fsops::retry_eagain(|| {
117        rustix::fs::openat2(
118            proc,
119            "self/status",
120            OFlags::RDONLY | OFlags::CLOEXEC,
121            Mode::empty(),
122            resolve,
123        )
124    })?;
125    let text = io::read_to_string(std::fs::File::from(fd))?;
126    text.lines()
127        .find_map(|line| line.strip_prefix("Threads:"))
128        .and_then(|value| value.trim().parse().ok())
129        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "no thread count in status"))
130}
131
132/// Applying the plan failed.
133#[derive(Debug, thiserror::Error)]
134pub enum ApplyError {
135    /// The process has more than one thread; per-thread credential syscalls
136    /// would leave other threads privileged.
137    #[error("cannot normalize privileges: process has {0} threads, expected 1")]
138    MultiThreaded(u32),
139    /// An operation failed.
140    #[error("privilege operation {op} failed: {source}")]
141    Op {
142        /// Description of the operation.
143        op: String,
144        /// Underlying error.
145        source: io::Error,
146    },
147    /// The resulting credentials differ from the plan.
148    #[error("privileges not as expected after normalization: {0}")]
149    Verification(String),
150}
151
152/// Applies `plan` to the current process and verifies the result. `proc` must
153/// be a verified procfs descriptor.
154pub fn apply(plan: &PrivilegePlan, proc: BorrowedFd<'_>) -> Result<ProcessState, ApplyError> {
155    let read_state = || {
156        ProcessState::read_self(proc).map_err(|source| ApplyError::Op {
157            op: "read process state".into(),
158            source,
159        })
160    };
161    let before = read_state()?;
162    if before.threads != 1 {
163        return Err(ApplyError::MultiThreaded(before.threads));
164    }
165    for op in &plan.ops {
166        apply_op(op).map_err(|source| ApplyError::Op {
167            op: format!("{op:?}"),
168            source,
169        })?;
170    }
171    let after = read_state()?;
172    verify(plan, &after).map_err(ApplyError::Verification)?;
173    Ok(after)
174}
175
176fn apply_op(op: &Op) -> io::Result<()> {
177    match op {
178        Op::ClearAmbient => rustix::thread::clear_ambient_capability_set()?,
179        Op::SetCaps(sets) => rustix::thread::set_capabilities(None, *sets)?,
180        Op::DropBoundingExcept(keep) => drop_bounding_except(*keep)?,
181        Op::SetSecureBits(bits) => {
182            // Setting replaces every bit; keep restrictions already in place.
183            let current = rustix::thread::capabilities_secure_bits()?;
184            rustix::thread::set_capabilities_secure_bits(current | *bits)?;
185        }
186        Op::SetKeepCaps(enable) => rustix::thread::set_keep_capabilities(*enable)?,
187        Op::SetGroups(groups) => {
188            let gids: Vec<Gid> = groups.iter().map(|&g| Gid::from_raw(g)).collect();
189            rustix::thread::set_thread_groups(&gids)?;
190        }
191        Op::SetResGid(gid) => {
192            let g = Gid::from_raw(*gid);
193            rustix::thread::set_thread_res_gid(g, g, g)?;
194        }
195        Op::SetResUid(uid) => {
196            let u = Uid::from_raw(*uid);
197            rustix::thread::set_thread_res_uid(u, u, u)?;
198        }
199        Op::SetNoNewPrivs => rustix::thread::set_no_new_privs(true)?,
200    }
201    Ok(())
202}
203
204fn drop_bounding_except(keep: CapabilitySet) -> io::Result<()> {
205    let excess = read_set(rustix::thread::capability_is_in_bounding_set)? & !keep.bits();
206    for n in (0..64).filter(|n| excess & (1u64 << n) != 0) {
207        rustix::thread::remove_capability_from_bounding_set(CapabilitySet::from_bits_retain(
208            1u64 << n,
209        ))?;
210    }
211    Ok(())
212}
213
214/// Checks that `status` matches what `plan` promised.
215pub fn verify(plan: &PrivilegePlan, status: &ProcessState) -> Result<(), String> {
216    let mut problems = Vec::new();
217    let expected_caps = plan.final_caps.bits();
218    if let Some(expected) = &plan.final_groups {
219        if status.gids.iter().any(|&g| g != expected.gid) {
220            problems.push(format!(
221                "GIDs {:?}, expected all {}",
222                status.gids, expected.gid
223            ));
224        }
225        if sorted(&status.groups) != sorted(&expected.groups) {
226            problems.push(format!(
227                "supplementary groups {:?}, expected {:?}",
228                status.groups, expected.groups
229            ));
230        }
231    }
232    if status.uids.iter().any(|&u| u != plan.final_uid) {
233        problems.push(format!(
234            "UIDs {:?}, expected all {}",
235            status.uids, plan.final_uid
236        ));
237    }
238    for (label, actual) in [
239        ("effective", status.cap_effective),
240        ("permitted", status.cap_permitted),
241    ] {
242        if actual != expected_caps {
243            problems.push(format!(
244                "{label} capabilities {actual:#x}, expected {expected_caps:#x}"
245            ));
246        }
247    }
248    if status.cap_inheritable != 0 {
249        problems.push(format!(
250            "inheritable capabilities {:#x}",
251            status.cap_inheritable
252        ));
253    }
254    if status.cap_ambient != 0 {
255        problems.push(format!("ambient capabilities {:#x}", status.cap_ambient));
256    }
257    if !status.no_new_privs {
258        problems.push("no_new_privs is not set".into());
259    }
260    for op in &plan.ops {
261        if let Op::SetSecureBits(bits) = op {
262            if status.secure_bits & bits.bits() != bits.bits() {
263                problems.push(format!(
264                    "securebits {:#x}, expected at least {:#x}",
265                    status.secure_bits,
266                    bits.bits()
267                ));
268            }
269        }
270    }
271    if plan
272        .ops
273        .iter()
274        .any(|op| matches!(op, Op::DropBoundingExcept(_)))
275        && status.cap_bounding & !expected_caps != 0
276    {
277        problems.push(format!(
278            "bounding set {:#x} exceeds {expected_caps:#x}",
279            status.cap_bounding
280        ));
281    }
282    if problems.is_empty() {
283        Ok(())
284    } else {
285        Err(problems.join("; "))
286    }
287}
288
289/// `groups` sorted and deduplicated; the kernel keeps groups sorted.
290fn sorted(groups: &[u32]) -> Vec<u32> {
291    let mut groups = groups.to_vec();
292    groups.sort_unstable();
293    groups.dedup();
294    groups
295}
296
297const CAPABILITY_NAMES: [&str; 41] = [
298    "chown",
299    "dac_override",
300    "dac_read_search",
301    "fowner",
302    "fsetid",
303    "kill",
304    "setgid",
305    "setuid",
306    "setpcap",
307    "linux_immutable",
308    "net_bind_service",
309    "net_broadcast",
310    "net_admin",
311    "net_raw",
312    "ipc_lock",
313    "ipc_owner",
314    "sys_module",
315    "sys_rawio",
316    "sys_chroot",
317    "sys_ptrace",
318    "sys_pacct",
319    "sys_admin",
320    "sys_boot",
321    "sys_nice",
322    "sys_resource",
323    "sys_time",
324    "sys_tty_config",
325    "mknod",
326    "lease",
327    "audit_write",
328    "audit_control",
329    "setfcap",
330    "mac_override",
331    "mac_admin",
332    "syslog",
333    "wake_alarm",
334    "block_suspend",
335    "audit_read",
336    "perfmon",
337    "bpf",
338    "checkpoint_restore",
339];
340
341/// Renders a capability set as names, e.g. `cap_sys_admin`.
342#[must_use]
343pub fn describe_caps(set: CapabilitySet) -> String {
344    if set.is_empty() {
345        return "none".into();
346    }
347    (0..64usize)
348        .filter(|n| set.bits() & (1u64 << n) != 0)
349        .map(|n| {
350            CAPABILITY_NAMES
351                .get(n)
352                .map_or_else(|| format!("cap_{n}"), |name| format!("cap_{name}"))
353        })
354        .collect::<Vec<_>>()
355        .join(",")
356}
357
358#[cfg(test)]
359mod tests {
360    use std::os::fd::AsFd;
361
362    use super::*;
363    use crate::privileges::plan::{FinalGroups, LOCKED_SECURE_BITS, PrivilegePlan};
364
365    fn normalized() -> ProcessState {
366        ProcessState {
367            uids: [991; 3],
368            gids: [991; 3],
369            groups: vec![5, 991],
370            threads: 1,
371            cap_inheritable: 0,
372            cap_permitted: 1 << 21,
373            cap_effective: 1 << 21,
374            cap_bounding: 1 << 21,
375            cap_ambient: 0,
376            no_new_privs: true,
377            secure_bits: LOCKED_SECURE_BITS.bits(),
378        }
379    }
380
381    fn plan(final_uid: u32, with_bounding: bool) -> PrivilegePlan {
382        let mut ops = vec![Op::ClearAmbient];
383        if with_bounding {
384            ops.push(Op::DropBoundingExcept(CapabilitySet::SYS_ADMIN));
385            ops.push(Op::SetSecureBits(LOCKED_SECURE_BITS));
386        }
387        PrivilegePlan {
388            ops,
389            warnings: vec![],
390            final_uid,
391            final_caps: CapabilitySet::SYS_ADMIN,
392            final_groups: Some(FinalGroups {
393                gid: 991,
394                groups: vec![991, 5],
395            }),
396        }
397    }
398
399    #[test]
400    fn credentials_for_planning() {
401        let creds = normalized().credentials();
402        assert_eq!(creds.uids, [991; 3]);
403        assert_eq!(creds.caps.effective, CapabilitySet::SYS_ADMIN);
404        assert_eq!(creds.caps.permitted, CapabilitySet::SYS_ADMIN);
405        assert_eq!(creds.caps.inheritable, CapabilitySet::empty());
406    }
407
408    /// The system-call readings agree with what the kernel reports in
409    /// `/proc/self/status`.
410    #[test]
411    fn reads_own_state() {
412        let proc = crate::probe::verify_procfs(std::path::Path::new("/proc")).unwrap();
413        let s = ProcessState::read_self(proc.as_fd()).unwrap();
414        let status = std::fs::read_to_string("/proc/self/status").unwrap();
415        let field = |key: &str| {
416            status
417                .lines()
418                .find_map(|line| line.strip_prefix(key)?.strip_prefix(':'))
419                .unwrap()
420                .trim()
421                .to_owned()
422        };
423        let ids = |key| -> Vec<u32> {
424            field(key)
425                .split_whitespace()
426                .take(3)
427                .map(|id| id.parse().unwrap())
428                .collect()
429        };
430        let hex = |key| u64::from_str_radix(&field(key), 16).unwrap();
431        assert_eq!(s.uids.to_vec(), ids("Uid"));
432        assert_eq!(s.gids.to_vec(), ids("Gid"));
433        let groups: Vec<u32> = field("Groups")
434            .split_whitespace()
435            .map(|id| id.parse().unwrap())
436            .collect();
437        assert_eq!(sorted(&s.groups), sorted(&groups));
438        assert!(s.threads >= 1);
439        assert_eq!(s.cap_inheritable, hex("CapInh"));
440        assert_eq!(s.cap_permitted, hex("CapPrm"));
441        assert_eq!(s.cap_effective, hex("CapEff"));
442        assert_eq!(s.cap_bounding, hex("CapBnd"));
443        assert_eq!(s.cap_ambient, hex("CapAmb"));
444        assert_eq!(s.no_new_privs, field("NoNewPrivs") == "1");
445    }
446
447    #[test]
448    fn verify_accepts_expected_state() {
449        assert_eq!(verify(&plan(991, true), &normalized()), Ok(()));
450    }
451
452    #[test]
453    fn verify_reports_each_problem() {
454        let base = normalized();
455        let check = |mutate: &dyn Fn(&mut ProcessState), with_bounding: bool, needle: &str| {
456            let mut s = base.clone();
457            mutate(&mut s);
458            let err = verify(&plan(991, with_bounding), &s).unwrap_err();
459            assert!(err.contains(needle), "{needle}: {err}");
460        };
461        check(&|s| s.uids[2] = 0, false, "UIDs");
462        check(&|s| s.gids[1] = 0, false, "GIDs");
463        check(&|s| s.groups.push(0), false, "supplementary groups");
464        check(&|s| s.groups.clear(), false, "supplementary groups");
465        check(&|s| s.cap_effective |= 1, false, "effective");
466        check(&|s| s.cap_permitted |= 1, false, "permitted");
467        check(&|s| s.cap_inheritable = 1, false, "inheritable");
468        check(&|s| s.cap_ambient = 1, false, "ambient");
469        check(&|s| s.no_new_privs = false, false, "no_new_privs");
470        check(&|s| s.cap_bounding = u64::MAX, true, "bounding");
471        check(&|s| s.secure_bits &= !1, true, "securebits");
472
473        // Securebits set beyond those planned are fine.
474        let mut s = base.clone();
475        s.secure_bits |= 1 << 8;
476        assert_eq!(verify(&plan(991, true), &s), Ok(()));
477
478        // Bounding set is not checked when it could not be changed.
479        let mut s = base.clone();
480        s.cap_bounding = u64::MAX;
481        assert_eq!(verify(&plan(991, false), &s), Ok(()));
482
483        // Groups are not checked when no user switch was planned.
484        let mut s = base.clone();
485        s.gids = [0; 3];
486        s.groups = vec![0];
487        let mut p = plan(991, false);
488        p.final_groups = None;
489        assert_eq!(verify(&p, &s), Ok(()));
490    }
491
492    #[test]
493    fn describes_caps() {
494        assert_eq!(describe_caps(CapabilitySet::empty()), "none");
495        assert_eq!(describe_caps(CapabilitySet::SYS_ADMIN), "cap_sys_admin");
496        assert_eq!(
497            describe_caps(CapabilitySet::SYS_ADMIN | CapabilitySet::from_bits_retain(1)),
498            "cap_chown,cap_sys_admin"
499        );
500        assert_eq!(
501            describe_caps(CapabilitySet::from_bits_retain(1 << 50)),
502            "cap_50"
503        );
504    }
505}