Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_sys/src/session.rs

9.6 KiB, 3 runs

created by r1870400018:76755, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! Dropping a root process to a user, with a check that the drop held, and the ownership test a
2//! root process applies to anything it trusts.
3//!
4//! [`drop_to`] sets the supplementary groups, then the real, effective and saved group ids, then
5//! the three user ids, in that order: the groups and the gid need the privilege the uid change
6//! gives up. It then reads all three back with `getresuid`, `getresgid` and `getgroups`, and where
7//! the target is not root, tries to take uid 0 back and requires that to fail. A drop that did not
8//! hold is an error, never a warning, so the caller cannot `exec` on a half-dropped process.
9//!
10//! [`strict_owner`] is OpenSSH's StrictModes for a root daemon: the path and every directory above
11//! it, along the path as named and along the path it resolves to, must be owned by root and not
12//! writable by group or others. Otherwise a user who can write any one of them can replace what
13//! root reads.
14//!
15//! The system calls come from `nix`, which owns the `unsafe` this crate forbids.
16
17use oxedyne_fe2o3_core::prelude::*;
18
19use nix::unistd::{
20 getgrouplist,
21 getgroups,
22 getresgid,
23 getresuid,
24 setgroups,
25 setresgid,
26 setresuid,
27 setsid,
28 Gid,
29 Uid,
30 User,
31};
32
33use std::{
34 collections::BTreeSet,
35 ffi::CString,
36 fs,
37 os::unix::fs::MetadataExt,
38 path::{
39 Component,
40 Path,
41 PathBuf,
42 },
43};
44
45/// The ids a process runs as once dropped.
46#[derive(Clone, Debug, Eq, PartialEq)]
47pub struct Identity {
48 pub uid: u32,
49 pub gid: u32,
50 pub groups: Vec<u32>, // Supplementary groups, the primary gid among them.
51}
52
53impl Identity {
54 /// The user's ids from the password and group databases, as `initgroups` would set them.
55 pub fn of_user(name: &str) -> Outcome<Self> {
56 let user = match User::from_name(name) {
57 Ok(Some(u)) => u,
58 Ok(None) => return Err(err!("No user named '{}' in the password database.", name;
59 Missing, Input)),
60 Err(e) => return Err(err!("Looking up user '{}': {}.", name, e; IO, System)),
61 };
62 let cname = res!(CString::new(name.as_bytes()).map_err(|_|
63 err!("User name '{}' holds a NUL byte.", name; Invalid, Input)));
64 let groups = match getgrouplist(&cname, user.gid) {
65 Ok(g) => g,
66 Err(e) => return Err(err!("Reading the groups of user '{}': {}.", name, e; IO, System)),
67 };
68 Ok(Self::new(user.uid.as_raw(), user.gid.as_raw(), groups.iter().map(|g| g.as_raw()).collect()))
69 }
70
71 /// An identity with `groups` sorted and free of repeats, and `gid` among them.
72 pub fn new(uid: u32, gid: u32, groups: Vec<u32>) -> Self {
73 let mut set: BTreeSet<u32> = groups.into_iter().collect();
74 set.insert(gid);
75 Self { uid, gid, groups: set.into_iter().collect() }
76 }
77
78 /// The ids the calling process runs as now, taking the real ids.
79 pub fn current() -> Outcome<Self> {
80 let u = res!(getresuid().map_err(|e| err!("getresuid: {}.", e; IO, System)));
81 let g = res!(getresgid().map_err(|e| err!("getresgid: {}.", e; IO, System)));
82 let groups = res!(getgroups().map_err(|e| err!("getgroups: {}.", e; IO, System)));
83 Ok(Self::new(u.real.as_raw(), g.real.as_raw(), groups.iter().map(|g| g.as_raw()).collect()))
84 }
85}
86
87/// A user's entry in the password database, found by uid or name through NSS (`getpwuid_r`,
88/// `getpwnam_r`).
89#[derive(Clone, Debug, Eq, PartialEq)]
90pub struct Account {
91 pub name: String,
92 pub uid: u32,
93 pub gid: u32,
94 pub home: PathBuf, // empty when the entry names none
95 pub shell: PathBuf, // the login shell, empty when the entry names none
96}
97
98impl From<User> for Account {
99 fn from(u: User) -> Self {
100 Self {
101 name: u.name,
102 uid: u.uid.as_raw(),
103 gid: u.gid.as_raw(),
104 home: u.dir,
105 shell: u.shell,
106 }
107 }
108}
109
110impl Account {
111 pub fn of_uid(uid: u32) -> Outcome<Self> {
112 match User::from_uid(Uid::from_raw(uid)) {
113 Ok(Some(u)) => Ok(Self::from(u)),
114 Ok(None) => Err(err!("No user with uid {} in the password database.", uid; Missing, Input)),
115 Err(e) => Err(err!("Looking up uid {}: {}.", uid, e; IO, System)),
116 }
117 }
118
119 pub fn of_name(name: &str) -> Outcome<Self> {
120 match User::from_name(name) {
121 Ok(Some(u)) => Ok(Self::from(u)),
122 Ok(None) => Err(err!("No user '{}' in the password database.", name; Missing, Input)),
123 Err(e) => Err(err!("Looking up user '{}': {}.", name, e; IO, System)),
124 }
125 }
126}
127
128/// The calling process's real, effective and saved uids, in that order.
129pub fn uids() -> Outcome<[u32; 3]> {
130 let u = res!(getresuid().map_err(|e| err!("getresuid: {}.", e; IO, System)));
131 Ok([u.real.as_raw(), u.effective.as_raw(), u.saved.as_raw()])
132}
133
134/// Drops the calling process to `id` and checks that the drop held. Needs root, or `CAP_SETUID`
135/// and `CAP_SETGID`. Every thread must be dropped, so call it before any thread is started.
136pub fn drop_to(id: &Identity) -> Outcome<()> {
137 let groups: Vec<Gid> = id.groups.iter().map(|g| Gid::from_raw(*g)).collect();
138 let gid = Gid::from_raw(id.gid);
139 let uid = Uid::from_raw(id.uid);
140 res!(setgroups(&groups).map_err(|e|
141 err!("Setting supplementary groups {:?}: {}.", id.groups, e; IO, System)));
142 res!(setresgid(gid, gid, gid).map_err(|e| err!("setresgid({}): {}.", id.gid, e; IO, System)));
143 res!(setresuid(uid, uid, uid).map_err(|e| err!("setresuid({}): {}.", id.uid, e; IO, System)));
144 check_dropped(id)
145}
146
147/// Is the calling process exactly `id`, in all three user ids, all three group ids and its
148/// supplementary groups, and, where `id` is not root, unable to take uid 0 back?
149pub fn check_dropped(id: &Identity) -> Outcome<()> {
150 let u = res!(getresuid().map_err(|e| err!("getresuid: {}.", e; IO, System)));
151 let ids = [u.real.as_raw(), u.effective.as_raw(), u.saved.as_raw()];
152 if ids.iter().any(|x| *x != id.uid) {
153 return Err(err!("The drop to uid {} did not hold: real, effective and saved uids are {:?}.",
154 id.uid, ids; Invalid, System));
155 }
156 let g = res!(getresgid().map_err(|e| err!("getresgid: {}.", e; IO, System)));
157 let ids = [g.real.as_raw(), g.effective.as_raw(), g.saved.as_raw()];
158 if ids.iter().any(|x| *x != id.gid) {
159 return Err(err!("The drop to gid {} did not hold: real, effective and saved gids are {:?}.",
160 id.gid, ids; Invalid, System));
161 }
162 let now = res!(getgroups().map_err(|e| err!("getgroups: {}.", e; IO, System)));
163 let mut now: BTreeSet<u32> = now.iter().map(|g| g.as_raw()).collect();
164 // The kernel may or may not list the primary gid among the supplementary groups.
165 now.insert(id.gid);
166 let want: BTreeSet<u32> = id.groups.iter().copied().collect();
167 if now != want {
168 return Err(err!("The drop to groups {:?} did not hold: the process has {:?}.",
169 want, now; Invalid, System));
170 }
171 if id.uid != 0 {
172 let root = Uid::from_raw(0);
173 if setresuid(root, root, root).is_ok() {
174 return Err(err!("The drop to uid {} did not hold: uid 0 could be taken back.",
175 id.uid; Invalid, System));
176 }
177 }
178 Ok(())
179}
180
181/// Starts a new session with the caller as its leader, so it has no controlling terminal, and
182/// answers the session id.
183pub fn new_session() -> Outcome<i32> {
184 match setsid() {
185 Ok(pid) => Ok(pid.as_raw()),
186 Err(e) => Err(err!("setsid: {}.", e; IO, System)),
187 }
188}
189
190/// Is `path`, and every directory above it, owned by root and not writable by group or others,
191/// both along the path as named and along the path it resolves to? A symbolic link on the way
192/// must itself be owned by root; its own mode bits mean nothing. `path` must be absolute.
193pub fn strict_owner(path: &Path) -> Outcome<()> {
194 if !path.is_absolute() {
195 return Err(err!("strict_owner needs an absolute path, not '{}'.", path.display();
196 Invalid, Input));
197 }
198 res!(strict_chain(path));
199 let real = res!(fs::canonicalize(path).map_err(|e|
200 err!("Resolving '{}': {}.", path.display(), e; IO, File, Read)));
201 if real != path {
202 res!(strict_chain(&real));
203 }
204 Ok(())
205}
206
207/// Checks each prefix of `path`, from the root down, without following the last component.
208fn strict_chain(path: &Path) -> Outcome<()> {
209 let mut at = PathBuf::new();
210 for c in path.components() {
211 match c {
212 Component::RootDir => at.push("/"),
213 Component::Normal(n) => at.push(n),
214 Component::CurDir => continue,
215 Component::ParentDir => return Err(err!("strict_owner refuses '..' in '{}'.",
216 path.display(); Invalid, Input)),
217 Component::Prefix(_) => return Err(err!("strict_owner met a path prefix in '{}'.",
218 path.display(); Invalid, Input)),
219 }
220 let m = res!(fs::symlink_metadata(&at).map_err(|e|
221 err!("Reading the owner of '{}': {}.", at.display(), e; IO, File, Read)));
222 res!(strict_entry(&at, m.uid(), m.mode(), m.file_type().is_symlink()));
223 }
224 Ok(())
225}
226
227/// The test [`strict_owner`] applies to one entry, from its owner and mode.
228pub fn strict_entry(at: &Path, uid: u32, mode: u32, is_link: bool) -> Outcome<()> {
229 if uid != 0 {
230 return Err(err!("'{}' is owned by uid {}, not root.", at.display(), uid; Invalid, Input));
231 }
232 // fixed: S_IWGRP | S_IWOTH, the POSIX mode bits.
233 if !is_link && mode & 0o022 != 0 {
234 return Err(err!("'{}' is writable by group or others (mode {:o}).", at.display(),
235 mode & 0o7777; Invalid, Input));
236 }
237 Ok(())
238}