Debian Codegraph @

src/system/mod.rs

raw symbols SCIP
1 // TODO: remove unused attribute when system is cleaned up
2 #[cfg(target_os = "linux")]
3 use std::str::FromStr;
4 use std::{
5 ffi::{CStr, c_int, c_long, c_uint},
6 fmt, fs, io,
7 mem::MaybeUninit,
8 ops,
9 os::unix,
10 path::PathBuf,
11 };
12
13 use crate::{
14 common::{Error, SudoPath, SudoString},
15 cutils::*,
16 };
17 use interface::{DeviceId, GroupId, ProcessId, UserId};
18 pub use libc::PATH_MAX;
19 use libc::{CLOSE_RANGE_CLOEXEC, EINVAL, ENOSYS, STDERR_FILENO};
20 use time::ProcessCreateTime;
21
22 use self::signal::SignalNumber;
23
24 pub(crate) mod audit;
25 // generalized traits for when we want to hide implementations
26 pub mod interface;
27
28 pub mod file;
29
30 pub mod time;
31
32 pub mod timestamp;
33
34 pub mod signal;
35
36 pub mod term;
37
38 pub mod wait;
39
40 #[cfg(not(any(target_os = "freebsd", target_os = "linux")))]
41 compile_error!("sudo-rs only works on Linux and FreeBSD");
42
43 pub(crate) fn _exit(status: c_int) -> ! {
44 // SAFETY: this function is safe to call
45 unsafe { libc::_exit(status) }
46 }
47
48 /// Mark every file descriptor that is not one of the IO streams as CLOEXEC.
49 pub(crate) fn mark_fds_as_cloexec() -> io::Result<()> {
50 let lowfd = STDERR_FILENO + 1;
51
52 // SAFETY: this function is safe to call:
53 // - any errors while closing a specific fd will be effectively ignored
54 #[allow(clippy::diverging_sub_expression)]
55 let res = unsafe {
56 'a: {
57 #[cfg(not(target_os = "linux"))]
58 break 'a cerr(libc::close_range(
59 lowfd as c_uint,
60 c_uint::MAX,
61 CLOSE_RANGE_CLOEXEC as c_int,
62 ));
63 // on Linux, close_range was only added in glibc 2.34, and is not
64 // part of musl, so we go perform a straight syscall instead
65 #[cfg(target_os = "linux")]
66 break 'a cerr(libc::syscall(
67 libc::SYS_close_range,
68 lowfd as c_uint,
69 c_uint::MAX,
70 CLOSE_RANGE_CLOEXEC as c_uint,
71 ));
72 }
73 };
74
75 match res {
76 Err(err) if err.raw_os_error() == Some(ENOSYS) || err.raw_os_error() == Some(EINVAL) => {
77 // The kernel doesn't support close_range or CLOSE_RANGE_CLOEXEC,
78 // fallback to finding all open fds using /proc/self/fd.
79
80 // FIXME use /dev/fd on macOS
81 for entry in fs::read_dir("/proc/self/fd")? {
82 let entry = entry?;
83 let file_name = entry.file_name();
84 let file_name = file_name.to_str().ok_or(io::Error::new(
85 io::ErrorKind::InvalidData,
86 "procfs returned non-integer fd name",
87 ))?;
88 if file_name == "." || file_name == ".." {
89 continue;
90 }
91 let fd = file_name.parse::<c_int>().map_err(|_| {
92 io::Error::new(
93 io::ErrorKind::InvalidData,
94 "procfs returned non-integer fd name",
95 )
96 })?;
97 if fd < lowfd {
98 continue;
99 }
100 // SAFETY: This only sets the CLOEXEC flag for the given fd. Nothing is
101 // going to need it after exec.
102 unsafe {
103 cerr(libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC))?;
104 }
105 }
106
107 Ok(())
108 }
109 Err(err) => Err(err),
110 Ok(_) => Ok(()),
111 }
112 }
113
114 pub(crate) enum ForkResult {
115 // Parent process branch with the child process' PID.
116 Parent(ProcessId),
117 // Child process branch.
118 Child,
119 }
120
121 /// Create a new process.
122 ///
123 /// # Safety
124 ///
125 /// Must not be called in multithreaded programs.
126 pub(crate) unsafe fn fork() -> io::Result<ForkResult> {
127 // FIXME add debug assertion that we are not currently using multiple threads.
128 // SAFETY: Calling async-signal-unsafe functions after fork is safe as the program is single
129 // threaded at this point according to the safety invariant of this function.
130 let pid = cerr(unsafe { libc::fork() })?;
131 if pid == 0 {
132 Ok(ForkResult::Child)
133 } else {
134 Ok(ForkResult::Parent(ProcessId::new(pid)))
135 }
136 }
137
138 /// Create a new process with extra precautions for usage in tests.
139 ///
140 /// # Safety
141 ///
142 /// In a multithreaded program, only async-signal-safe functions are guaranteed to work in the
143 /// child process until a call to `execve` or a similar function is done.
144 #[cfg(test)]
145 unsafe fn fork_for_test(child_func: impl FnOnce() -> std::convert::Infallible) -> ProcessId {
146 use std::io::Write;
147 use std::panic::{AssertUnwindSafe, catch_unwind};
148 use std::process::exit;
149
150 // SAFETY: Not really safe, but this is test only code.
151 match unsafe { fork() }.unwrap() {
152 ForkResult::Child => {
153 // Make sure that panics in the child always abort the process.
154 let err = match catch_unwind(AssertUnwindSafe(child_func)) {
155 Ok(res) => match res {},
156 Err(err) => err,
157 };
158
159 let s = if let Some(s) = err.downcast_ref::<&str>() {
160 s
161 } else if let Some(s) = err.downcast_ref::<String>() {
162 s
163 } else {
164 "Box<dyn Any>"
165 };
166 let _ = writeln!(std::io::stderr(), "{s}");
167
168 exit(101);
169 }
170 ForkResult::Parent(pid) => pid,
171 }
172 }
173
174 pub fn setsid() -> io::Result<ProcessId> {
175 // SAFETY: this function is memory-safe to call
176 Ok(ProcessId::new(cerr(unsafe { libc::setsid() })?))
177 }
178
179 #[derive(Clone)]
180 #[cfg_attr(test, derive(PartialEq))]
181 pub struct Hostname {
182 inner: String,
183 }
184
185 impl fmt::Debug for Hostname {
186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187 f.debug_tuple("Hostname").field(&self.inner).finish()
188 }
189 }
190
191 impl fmt::Display for Hostname {
192 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193 f.write_str(&self.inner)
194 }
195 }
196
197 impl ops::Deref for Hostname {
198 type Target = str;
199
200 fn deref(&self) -> &str {
201 &self.inner
202 }
203 }
204
205 impl Hostname {
206 #[cfg(test)]
207 pub fn fake(hostname: &str) -> Self {
208 Self {
209 inner: hostname.to_string(),
210 }
211 }
212
213 pub fn resolve() -> Self {
214 // see `man 2 gethostname`
215 const MAX_HOST_NAME_SIZE_ACCORDING_TO_SUSV2: c_long = 255;
216
217 // POSIX.1 systems limit hostnames to `HOST_NAME_MAX` bytes
218 // not including null-byte in the count
219 let max_hostname_size = sysconf(libc::_SC_HOST_NAME_MAX)
220 .unwrap_or(MAX_HOST_NAME_SIZE_ACCORDING_TO_SUSV2)
221 as usize;
222
223 let buffer_size = max_hostname_size + 1 /* null byte delimiter */ ;
224 let mut buf = vec![0; buffer_size];
225
226 // SAFETY: we are passing a valid pointer to gethostname
227 match cerr(unsafe { libc::gethostname(buf.as_mut_ptr(), buffer_size) }) {
228 Ok(_) => Self {
229 // SAFETY: gethostname succeeded, so `buf` will hold a null-terminated C string
230 inner: unsafe { string_from_ptr(buf.as_ptr()) },
231 },
232
233 // ENAMETOOLONG is returned when hostname is greater than `buffer_size`
234 Err(_) => {
235 // but we have chosen a `buffer_size` larger than `max_hostname_size` so no truncation error is possible
236 panic!("Unexpected error while retrieving hostname, this should not happen");
237 }
238 }
239 }
240 }
241
242 pub fn syslog(priority: c_int, facility: c_int, message: &CStr) {
243 const MSG: &CStr = c"%s";
244
245 // SAFETY:
246 // - "MSG" is a constant expression that is a null-terminated C string that represents "%s";
247 // this also means that to achieve safety we MUST pass one more argument to syslog that is a proper
248 // pointer to a null-terminated C string
249 // - message.as_ptr() is a pointer to a proper null-terminated C string (message being a &CStr)
250 // for more info: read the manpage for syslog(2)
251 unsafe {
252 libc::syslog(priority | facility, MSG.as_ptr(), message.as_ptr());
253 }
254 }
255
256 /// Makes sure that that the target is included in the groups, and is its first element
257 fn inject_group(target: GroupId, groups: &mut Vec<GroupId>) {
258 if let Some(index) = groups.iter().position(|id| id == &target) {
259 // make sure the requested group id is the first in the list (necessary on FreeBSD)
260 groups.swap(0, index)
261 } else {
262 // add target group to list of additional groups if not present
263 groups.insert(0, target);
264 }
265 }
266
267 /// Set the supplementary groups -- returns a c_int to mimic a libc function
268 fn set_supplementary_groups(groups: &[GroupId]) -> io::Result<()> {
269 // On FreeBSD, setgruops expects the size to be passed as a i32, so the below
270 // conversion protects a very extreme case of arithmetic conversion error
271 #[allow(irrefutable_let_patterns)]
272 #[allow(clippy::useless_conversion)]
273 let Ok(len) = groups.len().try_into() else {
274 return Err(io::Error::other("too many groups"));
275 };
276 // SAFETY: setgroups is passed a valid pointer to a chunk of memory of the correct size
277 // We can cast to gid_t because `GroupId` is marked as transparent
278 cerr(unsafe { libc::setgroups(len, groups.as_ptr().cast::<libc::gid_t>()) })?;
279
280 Ok(())
281 }
282
283 /// set target user and groups (uid, gid, additional groups) for a command
284 pub fn set_target_user(
285 cmd: &mut std::process::Command,
286 mut target_user: User,
287 target_group: Group,
288 ) {
289 use std::os::unix::process::CommandExt;
290
291 inject_group(target_group.gid, &mut target_user.groups);
292
293 // we need to do this in a `pre_exec` call since the `groups` method in `process::Command` is unstable
294 // see https://github.com/rust-lang/rust/blob/a01b4cc9f375f1b95fa8195daeea938d3d9c4c34/library/std/src/sys/unix/process/process_unix.rs#L329-L352
295 // for the std implementation of the libc calls to `setgroups`, `setgid` and `setuid`
296 // SAFETY: Setuid, setgid and setgroups are async-signal-safe.
297 unsafe {
298 cmd.pre_exec(move || {
299 set_supplementary_groups(&target_user.groups)?;
300 // setgid and setuid set the real, effective and saved version of the gid and uid
301 // respectively rather than just the real gid and uid. The original sudo uses setresgid
302 // and setresuid instead with all three arguments equal, but as this does the same as
303 // setgid and setuid using the latter is fine too.
304 cerr(libc::setgid(target_group.gid.inner()))?;
305 cerr(libc::setuid(target_user.uid.inner()))?;
306
307 Ok(())
308 });
309 }
310 }
311
312 /// Send a signal to a process with the specified ID.
313 pub fn kill(pid: ProcessId, signal: SignalNumber) -> io::Result<()> {
314 // SAFETY: This function cannot cause UB even if `pid` is not a valid process ID or if
315 // `signal` is not a valid signal code.
316 cerr(unsafe { libc::kill(pid.inner(), signal) }).map(|_| ())
317 }
318
319 /// Send a signal to a process group with the specified ID.
320 pub fn killpg(pgid: ProcessId, signal: SignalNumber) -> io::Result<()> {
321 // SAFETY: This function cannot cause UB even if `pgid` is not a valid process ID or if
322 // `signal` is not a valid signal code.
323 cerr(unsafe { libc::killpg(pgid.inner(), signal) }).map(|_| ())
324 }
325
326 /// Get the process group ID of the current process.
327 pub fn getpgrp() -> ProcessId {
328 // SAFETY: This function is always safe to call
329 ProcessId::new(unsafe { libc::getpgrp() })
330 }
331
332 /// Get a process group ID.
333 pub fn getpgid(pid: ProcessId) -> io::Result<ProcessId> {
334 // SAFETY: This function cannot cause UB even if `pid` is not a valid process ID
335 Ok(ProcessId::new(cerr(unsafe { libc::getpgid(pid.inner()) })?))
336 }
337
338 /// Set a process group ID.
339 pub fn setpgid(pid: ProcessId, pgid: ProcessId) -> io::Result<()> {
340 // SAFETY: This function cannot cause UB even if `pid` or `pgid` are not a valid process IDs:
341 // https://pubs.opengroup.org/onlinepubs/007904975/functions/setpgid.html
342 cerr(unsafe { libc::setpgid(pid.inner(), pgid.inner()) }).map(|_| ())
343 }
344
345 pub fn chown<S: AsRef<CStr>>(
346 path: &S,
347 uid: impl Into<UserId>,
348 gid: impl Into<GroupId>,
349 ) -> io::Result<()> {
350 let path = path.as_ref().as_ptr();
351 let uid = uid.into();
352 let gid = gid.into();
353
354 // SAFETY: path is a valid pointer to a null-terminated C string; chown cannot cause safety
355 // issues even if uid and/or gid would be invalid identifiers.
356 cerr(unsafe { libc::chown(path, uid.inner(), gid.inner()) }).map(|_| ())
357 }
358
359 #[derive(Debug, Clone, PartialEq)]
360 pub struct User {
361 pub uid: UserId,
362 pub gid: GroupId,
363 pub name: SudoString,
364 pub home: SudoPath,
365 pub shell: PathBuf,
366 pub groups: Vec<GroupId>,
367 }
368
369 impl User {
370 /// # Safety
371 /// This function expects `pwd` to be a result from a successful call to `getpwXXX_r`.
372 /// (It can cause UB if any of `pwd`'s pointed-to strings does not have a null-terminator.)
373 unsafe fn from_libc(pwd: &libc::passwd) -> Result<User, Error> {
374 // NOTE: on Linux, getgrouplist could be used to simply inquire as to the size needed;
375 // but on FreeBSD, getgrouplist does not specify this in its function contract, so a
376 // blind allocation loop is needed.
377 let Some(groups_buffer) =
378 dynamic_fill::<libc::gid_t, std::num::TryFromIntError>(32..65536, |groups_buffer| {
379 let mut buf_len: c_int = groups_buffer.len() as c_int;
380 // SAFETY: getgrouplist is passed valid pointers
381 // in particular `groups_buffer` is an array of `buf.len()` bytes, as required
382 let result = unsafe {
383 libc::getgrouplist(
384 pwd.pw_name,
385 pwd.pw_gid,
386 groups_buffer.as_mut_ptr(),
387 &mut buf_len,
388 )
389 };
390
391 Ok(if result != -1 {
392 Some(buf_len.try_into()?)
393 } else {
394 None
395 })
396 })
397 .expect("negative group size, this should not happen")
398 else {
399 panic!("user has too many groups (> 65536), this should not happen");
400 };
401
402 // SAFETY: All pointers were initialized by a successful call to `getpwXXX_r` as per the
403 // safety invariant of this function.
404 unsafe {
405 Ok(User {
406 uid: UserId::new(pwd.pw_uid),
407 gid: GroupId::new(pwd.pw_gid),
408 name: SudoString::new(string_from_ptr(pwd.pw_name))?,
409 home: SudoPath::new(os_string_from_ptr(pwd.pw_dir).into())?,
410 shell: os_string_from_ptr(pwd.pw_shell).into(),
411 groups: groups_buffer
412 .iter()
413 .map(|id| GroupId::new(*id))
414 .collect::<Vec<_>>(),
415 })
416 }
417 }
418
419 pub fn from_uid(uid: UserId) -> Result<Option<User>, Error> {
420 let max_pw_size = sysconf(libc::_SC_GETPW_R_SIZE_MAX).unwrap_or(16_384);
421 let mut buf = vec![0; max_pw_size as usize];
422 let mut pwd = MaybeUninit::uninit();
423 let mut pwd_ptr = std::ptr::null_mut();
424 // SAFETY: getpwuid_r is passed valid (although partly uninitialized) pointers to memory,
425 // in particular `buf` points to an array of `buf.len()` bytes, as required.
426 // After this call, if `pwd_ptr` is not NULL, `*pwd_ptr` and `pwd` will be aliased;
427 // but we never dereference `pwd_ptr`.
428 cerr(unsafe {
429 libc::getpwuid_r(
430 uid.inner(),
431 pwd.as_mut_ptr(),
432 buf.as_mut_ptr(),
433 buf.len(),
434 &mut pwd_ptr,
435 )
436 })?;
437 if pwd_ptr.is_null() {
438 Ok(None)
439 } else {
440 // SAFETY: pwd_ptr was not null, and getpwuid_r succeeded, so we have assurances that
441 // the `pwd` structure was written to by getpwuid_r
442 let pwd = unsafe { pwd.assume_init() };
443 // SAFETY: `pwd` was obtained by a call to getpwXXX_r, as required.
444 unsafe { Self::from_libc(&pwd).map(Some) }
445 }
446 }
447
448 pub fn effective_uid() -> UserId {
449 // SAFETY: this function cannot cause memory safety issues
450 UserId::new(unsafe { libc::geteuid() })
451 }
452
453 pub fn effective_gid() -> GroupId {
454 // SAFETY: this function cannot cause memory safety issues
455 GroupId::new(unsafe { libc::getegid() })
456 }
457
458 pub fn real_uid() -> UserId {
459 // SAFETY: this function cannot cause memory safety issues
460 UserId::new(unsafe { libc::getuid() })
461 }
462
463 pub fn real_gid() -> GroupId {
464 // SAFETY: this function cannot cause memory safety issues
465 GroupId::new(unsafe { libc::getgid() })
466 }
467
468 pub fn real() -> Result<Option<User>, Error> {
469 Self::from_uid(Self::real_uid())
470 }
471
472 pub fn primary_group(&self) -> std::io::Result<Group> {
473 // Use from_gid_unchecked here to ensure that we can still resolve when
474 // the /etc/group entry for the primary group is missing.
475 Group::from_gid_unchecked(self.gid)
476 }
477
478 pub fn from_name(name_c: &CStr) -> Result<Option<User>, Error> {
479 let max_pw_size = sysconf(libc::_SC_GETPW_R_SIZE_MAX).unwrap_or(16_384);
480 let mut buf = vec![0; max_pw_size as usize];
481 let mut pwd = MaybeUninit::uninit();
482 let mut pwd_ptr = std::ptr::null_mut();
483
484 // SAFETY: analogous to getpwuid_r above
485 cerr(unsafe {
486 libc::getpwnam_r(
487 name_c.as_ptr(),
488 pwd.as_mut_ptr(),
489 buf.as_mut_ptr(),
490 buf.len(),
491 &mut pwd_ptr,
492 )
493 })?;
494 if pwd_ptr.is_null() {
495 Ok(None)
496 } else {
497 // SAFETY: pwd_ptr was not null, and getpwnam_r succeeded, so we have assurances that
498 // the `pwd` structure was written to by getpwnam_r
499 let pwd = unsafe { pwd.assume_init() };
500 // SAFETY: `pwd` was obtained by a call to getpwXXX_r, as required.
501 unsafe { Self::from_libc(&pwd).map(Some) }
502 }
503 }
504 }
505
506 #[derive(Debug, Clone)]
507 #[cfg_attr(test, derive(PartialEq))]
508 pub struct Group {
509 pub gid: GroupId,
510 pub name: Option<String>,
511 }
512
513 impl Group {
514 /// # Safety
515 /// This function expects `grp` to be a result from a successful call to `getgrXXX_r`.
516 /// In particular the grp.gr_mem pointer is assumed to be non-null, and pointing to a
517 /// null-terminated list; the pointed-to strings are expected to be null-terminated.
518 unsafe fn from_libc(grp: &libc::group) -> Group {
519 // SAFETY: The name pointer is initialized by a successful call to `getgrXXX_r` as per the
520 // safety invariant of this function.
521 let name = unsafe { string_from_ptr(grp.gr_name) };
522 Group {
523 gid: GroupId::new(grp.gr_gid),
524 name: Some(name),
525 }
526 }
527
528 /// Lookup group for gid without returning an error when a /etc/group entry is missing.
529 fn from_gid_unchecked(gid: GroupId) -> std::io::Result<Group> {
530 // Set an arbitrary upper limit of two terabytes/two gigabytes for the temporary buffer
531 let initial_gr_size = sysconf(libc::_SC_GETGR_R_SIZE_MAX).unwrap_or(16_384) as usize;
532 let max_gr_size = std::cmp::max(i32::MAX as usize, usize::MAX >> 24);
533
534 let mut grp = MaybeUninit::uninit();
535 let mut grp_ptr = std::ptr::null_mut();
536 let Some(_buf) = dynamic_fill(initial_gr_size..max_gr_size, |buf| {
537 // SAFETY: analogous to getpwuid_r above
538 let result = unsafe {
539 libc::getgrgid_r(
540 gid.inner(),
541 grp.as_mut_ptr(),
542 buf.as_mut_ptr(),
543 buf.len(),
544 &mut grp_ptr,
545 )
546 };
547 match result {
548 0 => Ok(Some(buf.len())),
549 libc::ERANGE => Ok(None),
550 _ => Err(io::Error::from_raw_os_error(result)),
551 }
552 })?
553 else {
554 panic!("group buffer size exceeds limit (>{max_gr_size})");
555 };
556
557 if grp_ptr.is_null() {
558 Ok(Group { gid, name: None })
559 } else {
560 // SAFETY: grp_ptr was not null, and getgrgid_r succeeded, so we have assurances that
561 // the `grp` structure was written to by getgrgid_r
562 let grp = unsafe { grp.assume_init() };
563 // SAFETY: `pwd` was obtained by a call to getgrXXX_r, as required.
564 Ok(unsafe { Group::from_libc(&grp) })
565 }
566 }
567
568 pub fn from_gid(gid: GroupId) -> std::io::Result<Option<Group>> {
569 let group = Self::from_gid_unchecked(gid)?;
570 if group.name.is_none() {
571 // No entry in /etc/group
572 Ok(None)
573 } else {
574 Ok(Some(group))
575 }
576 }
577
578 pub fn from_name(name_c: &CStr) -> std::io::Result<Option<Group>> {
579 // Set an arbitrary upper limit of two terabytes/two gigabytes for the temporary buffer
580 let initial_gr_size = sysconf(libc::_SC_GETGR_R_SIZE_MAX).unwrap_or(16_384) as usize;
581 let max_gr_size = std::cmp::max(i32::MAX as usize, usize::MAX >> 24);
582 let mut grp = MaybeUninit::uninit();
583 let mut grp_ptr = std::ptr::null_mut();
584 let Some(_buf) = dynamic_fill(initial_gr_size..max_gr_size, |buf| {
585 // SAFETY: analogous to getpwuid_r above
586 let result = unsafe {
587 libc::getgrnam_r(
588 name_c.as_ptr(),
589 grp.as_mut_ptr(),
590 buf.as_mut_ptr(),
591 buf.len(),
592 &mut grp_ptr,
593 )
594 };
595 match result {
596 0 => Ok(Some(buf.len())),
597 libc::ERANGE => Ok(None),
598 _ => Err(io::Error::from_raw_os_error(result)),
599 }
600 })?
601 else {
602 panic!("group buffer size exceeds limit (>{max_gr_size})");
603 };
604
605 if grp_ptr.is_null() {
606 Ok(None)
607 } else {
608 // SAFETY: grp_ptr was not null, and getgrgid_r succeeded, so we have assurances that
609 // the `grp` structure was written to by getgrgid_r
610 let grp = unsafe { grp.assume_init() };
611 // SAFETY: `pwd` was obtained by a call to getgrXXX_r, as required.
612 Ok(Some(unsafe { Group::from_libc(&grp) }))
613 }
614 }
615 }
616
617 pub enum WithProcess {
618 Current,
619 Other(ProcessId),
620 }
621
622 impl WithProcess {
623 #[cfg(target_os = "linux")]
624 fn to_proc_string(&self) -> String {
625 match self {
626 WithProcess::Current => "self".into(),
627 WithProcess::Other(pid) => pid.to_string(),
628 }
629 }
630 }
631
632 #[derive(Debug, Clone)]
633 pub struct Process {
634 pub parent_pid: Option<ProcessId>,
635 pub session_id: ProcessId,
636 }
637
638 impl Process {
639 pub fn new() -> Process {
640 Process {
641 parent_pid: Self::parent_id(),
642 session_id: Self::session_id(),
643 }
644 }
645
646 /// Return the process identifier for the current process
647 pub fn process_id() -> ProcessId {
648 // NOTE libstd casts the `i32` that `libc::getpid` returns into `u32`
649 // here we cast it back into `i32` (`ProcessId`)
650 ProcessId::new(std::process::id() as i32)
651 }
652
653 /// Return the parent process identifier for the current process
654 pub fn parent_id() -> Option<ProcessId> {
655 // NOTE libstd casts the `i32` that `libc::getppid` returns into `u32`
656 // here we cast it back into `i32` (`ProcessId`)
657 let pid = ProcessId::new(unix::process::parent_id() as i32);
658 if !pid.is_valid() { None } else { Some(pid) }
659 }
660
661 /// Get the session id for the current process
662 pub fn session_id() -> ProcessId {
663 // SAFETY: this function is explicitly safe to call with argument 0,
664 // and more generally getsid will never cause memory safety issues.
665 ProcessId::new(unsafe { libc::getsid(0) })
666 }
667
668 /// Returns the device identifier of the TTY device that is currently
669 /// attached to the given process
670 #[cfg(target_os = "linux")]
671 pub fn tty_device_id(pid: WithProcess) -> std::io::Result<Option<DeviceId>> {
672 // device id of tty is displayed as a signed integer of 32 bits
673 let data: i32 = read_proc_stat(pid, 6 /* tty_nr */)?;
674 if data == 0 {
675 Ok(None)
676 } else {
677 // While the integer was displayed as signed in the proc stat file,
678 // we actually need to interpret the bits of that integer as an unsigned
679 // int. We convert via u32 because a direct conversion to DeviceId
680 // would use sign extension, which would result in a different bit
681 // representation
682 Ok(Some(DeviceId::new(data as u64)))
683 }
684 }
685
686 #[cfg(target_os = "freebsd")]
687 fn get_proc_info(pid: WithProcess) -> std::io::Result<libc::kinfo_proc> {
688 use std::ffi::c_void;
689 use std::ptr;
690
691 let mut ki_proc: Vec<libc::kinfo_proc> = Vec::with_capacity(1);
692
693 let pid = match pid {
694 WithProcess::Current => std::process::id() as i32,
695 WithProcess::Other(pid) => pid.inner(),
696 };
697
698 loop {
699 let mut size = ki_proc.capacity() * size_of::<libc::kinfo_proc>();
700 // SAFETY: KERN_PROC_PID only reads data into the ki_proc list. It
701 // does not write more than `size` bytes to the pointer.
702 match cerr(unsafe {
703 libc::sysctl(
704 [
705 libc::CTL_KERN,
706 libc::KERN_PROC,
707 libc::KERN_PROC_PID,
708 pid,
709 size_of::<libc::kinfo_proc>() as i32,
710 1,
711 ]
712 .as_ptr(),
713 4,
714 ki_proc.as_mut_ptr().cast::<c_void>(),
715 &mut size,
716 ptr::null(),
717 0,
718 )
719 }) {
720 Ok(_) => {
721 assert!(size >= size_of::<libc::kinfo_proc>());
722 // SAFETY: The above sysctl has initialized at least `size` bytes. We have
723 // asserted that this is at least a single element.
724 unsafe {
725 ki_proc.set_len(1);
726 }
727 break;
728 }
729 Err(e) if e.raw_os_error() == Some(libc::ENOMEM) => {
730 // Vector not big enough. Grow it by 10% and try again.
731 ki_proc.reserve(ki_proc.capacity() + (ki_proc.capacity() + 9) / 10);
732 }
733 Err(e) => return Err(e),
734 }
735 }
736
737 Ok(ki_proc[0])
738 }
739
740 /// Returns the device identifier of the TTY device that is currently
741 /// attached to the given process
742 #[cfg(target_os = "freebsd")]
743 pub fn tty_device_id(pid: WithProcess) -> std::io::Result<Option<DeviceId>> {
744 let ki_proc = Self::get_proc_info(pid)?;
745
746 if ki_proc.ki_tdev == !0 {
747 Ok(None)
748 } else {
749 Ok(Some(DeviceId::new(ki_proc.ki_tdev)))
750 }
751 }
752
753 /// Get the process starting time of a specific process
754 #[cfg(target_os = "linux")]
755 pub fn starting_time(pid: WithProcess) -> io::Result<ProcessCreateTime> {
756 let process_start: u64 = read_proc_stat(pid, 21 /* start_time */)?;
757
758 // the startime field is stored in ticks since the system start, so we need to know how many
759 // ticks go into a second
760 let ticks_per_second = crate::cutils::sysconf(libc::_SC_CLK_TCK).ok_or_else(|| {
761 io::Error::other("Could not retrieve system config variable for ticks per second")
762 })? as u64;
763
764 // finally compute the system time at which the process was started
765 Ok(ProcessCreateTime::new(
766 (process_start / ticks_per_second) as i64,
767 ((process_start % ticks_per_second) * (1_000_000_000 / ticks_per_second)) as i64,
768 ))
769 }
770
771 /// Get the process starting time of a specific process
772 #[cfg(target_os = "freebsd")]
773 pub fn starting_time(pid: WithProcess) -> io::Result<ProcessCreateTime> {
774 let ki_proc = Self::get_proc_info(pid)?;
775
776 let ki_start = ki_proc.ki_start;
777 #[allow(clippy::useless_conversion)]
778 Ok(ProcessCreateTime::new(
779 i64::from(ki_start.tv_sec),
780 i64::from(ki_start.tv_usec) * 1000,
781 ))
782 }
783 }
784
785 /// Read the n-th field (with 0-based indexing) from `/proc/<pid>/self`.
786 ///
787 /// See ["Table 1-4: Contents of the stat fields" of "The /proc
788 /// Filesystem"][proc_stat_fields] in the Linux docs for all available fields.
789 ///
790 /// IMPORTANT: the first two fields are not accessible with this routine.
791 ///
792 /// [proc_stat_fields]: https://www.kernel.org/doc/html/latest/filesystems/proc.html#id10
793 #[cfg(target_os = "linux")]
794 fn read_proc_stat<T: FromStr>(pid: WithProcess, field_idx: isize) -> io::Result<T> {
795 // the first two fields are skipped by the code below, and we never need them,
796 // so no point in implementing code for it in this private function.
797 debug_assert!(field_idx >= 2);
798
799 // read from a specific pid file, or use `self` to refer to our own process
800 let pidref = pid.to_proc_string();
801
802 // read the data from the stat file for the process with the given pid
803 let path = PathBuf::from_iter(&["/proc", &pidref, "stat"]);
804 let proc_stat = std::fs::read(path)?;
805
806 // first get the part of the stat file past the second argument, we then reverse
807 // search for a ')' character and start the search for the starttime field from there on
808 let skip_past_second_arg = proc_stat.iter().rposition(|b| *b == b')').ok_or_else(|| {
809 io::Error::new(
810 io::ErrorKind::InvalidInput,
811 "Could not find position of 'comm' field in process stat",
812 )
813 })?;
814 let mut stat = &proc_stat[skip_past_second_arg..];
815
816 // we've now passed the first two fields, so we are at index 1, now we skip over
817 // fields until we arrive at the field we are searching for
818 let mut curr_field = 1;
819 while curr_field < field_idx && !stat.is_empty() {
820 if stat[0] == b' ' {
821 curr_field += 1;
822 }
823 stat = &stat[1..];
824 }
825
826 // The expected field cannot be in the file anymore when we are at EOF
827 if stat.is_empty() {
828 return Err(io::Error::new(
829 io::ErrorKind::InvalidData,
830 "Stat file was not of the expected format",
831 ));
832 }
833
834 // we've now arrived at the field we are looking for, we now check how
835 // long this field is by finding where the next space is
836 let mut idx = 0;
837 while stat[idx] != b' ' && idx < stat.len() {
838 idx += 1;
839 }
840 let field = &stat[0..idx];
841
842 // we first convert the data to a string slice, this should not fail with a normal /proc filesystem
843 let fielddata = std::str::from_utf8(field).map_err(|_| {
844 io::Error::new(
845 io::ErrorKind::InvalidInput,
846 "Could not interpret byte slice as string",
847 )
848 })?;
849
850 // then we convert the string slice to whatever the requested type was
851 fielddata.parse().map_err(|_| {
852 io::Error::new(
853 io::ErrorKind::InvalidInput,
854 "Could not interpret string as number",
855 )
856 })
857 }
858
859 pub fn escape_os_str_lossy(s: &std::ffi::OsStr) -> String {
860 s.to_string_lossy().escape_default().collect()
861 }
862
863 pub fn make_zeroed_sigaction() -> libc::sigaction {
864 // SAFETY: since sigaction is a C struct, all-zeroes is a valid representation
865 // We cannot use a "literal struct" initialization method since the exact representation
866 // of libc::sigaction is not fixed, see e.g. https://github.com/trifectatechfoundation/sudo-rs/issues/829
867 unsafe { std::mem::zeroed() }
868 }
869
870 #[cfg(all(test, target_os = "linux"))]
871 pub(crate) const ROOT_GROUP_NAME: &str = "root";
872
873 #[cfg(all(test, not(target_os = "linux")))]
874 pub(crate) const ROOT_GROUP_NAME: &str = "wheel";
875
876 #[allow(clippy::undocumented_unsafe_blocks)]
877 #[cfg(test)]
878 mod tests {
879 use std::{
880 ffi::c_char,
881 io::{self, Read, Write},
882 os::{
883 fd::{AsFd, AsRawFd},
884 unix::net::UnixStream,
885 },
886 process::exit,
887 };
888
889 use libc::SIGKILL;
890
891 use crate::system::interface::{GroupId, ProcessId, UserId};
892
893 use super::{
894 Group, ROOT_GROUP_NAME, User, WithProcess, fork_for_test, getpgrp, setpgid,
895 wait::{Wait, WaitOptions},
896 };
897
898 pub(super) fn tempfile() -> std::io::Result<std::fs::File> {
899 let timestamp = std::time::SystemTime::now()
900 .duration_since(std::time::UNIX_EPOCH)
901 .expect("Failed to get system time")
902 .as_nanos();
903 let pid = std::process::id();
904
905 let filename = format!("sudo_rs_test_{pid}_{timestamp}");
906 let path = std::path::PathBuf::from("/tmp").join(filename);
907 std::fs::File::options()
908 .read(true)
909 .write(true)
910 .create_new(true)
911 .open(path)
912 }
913
914 #[test]
915 fn test_get_user_and_group_by_id() {
916 let fixed_users = &[
917 (UserId::ROOT, "root"),
918 (User::from_name(c"daemon").unwrap().unwrap().uid, "daemon"),
919 ];
920 for &(id, name) in fixed_users {
921 let root = User::from_uid(id).unwrap().unwrap();
922 assert_eq!(root.uid, id);
923 assert_eq!(root.name, name);
924 }
925
926 let fixed_groups = &[
927 (GroupId::new(0), ROOT_GROUP_NAME),
928 (Group::from_name(c"daemon").unwrap().unwrap().gid, "daemon"),
929 ];
930 for &(id, name) in fixed_groups {
931 let root = Group::from_gid(id).unwrap().unwrap();
932 assert_eq!(root.gid, id);
933 assert_eq!(root.name.unwrap(), name);
934 }
935 }
936
937 #[test]
938 fn miri_test_group_impl() {
939 use super::Group;
940 use std::ffi::CString;
941
942 fn test(name: &str, passwd: &str, gid: libc::gid_t, mem: &[&str]) {
943 assert_eq!(
944 {
945 let c_mem: Vec<CString> =
946 mem.iter().map(|&s| CString::new(s).unwrap()).collect();
947 let c_name = CString::new(name).unwrap();
948 let c_passwd = CString::new(passwd).unwrap();
949 unsafe {
950 Group::from_libc(&libc::group {
951 gr_name: c_name.as_ptr() as *mut _,
952 gr_passwd: c_passwd.as_ptr() as *mut _,
953 gr_gid: gid,
954 gr_mem: c_mem
955 .iter()
956 .map(|cs| cs.as_ptr() as *mut _)
957 .chain(std::iter::once(std::ptr::null_mut()))
958 .collect::<Vec<*mut c_char>>()
959 .as_mut_ptr(),
960 })
961 }
962 },
963 Group {
964 name: Some(name.to_string()),
965 gid: GroupId::new(gid),
966 }
967 )
968 }
969
970 test("dr. bill", "fidelio", 1999, &["eyes", "wide", "shut"]);
971 test("eris", "fnord", 5, &[]);
972 test("abc", "password123", 42, &[""]);
973 }
974
975 #[test]
976 fn get_process_tty_device() {
977 assert!(super::Process::tty_device_id(WithProcess::Current).is_ok());
978 }
979
980 #[test]
981 fn pgid_test() {
982 use super::{getpgid, setpgid};
983
984 let pgrp = getpgrp();
985 assert_eq!(getpgid(ProcessId::new(0)).unwrap(), pgrp);
986 assert_eq!(
987 getpgid(ProcessId::new(std::process::id() as i32)).unwrap(),
988 pgrp
989 );
990
991 let child_pid = unsafe {
992 super::fork_for_test(|| {
993 // wait for the parent.
994 std::thread::sleep(std::time::Duration::from_secs(1));
995 exit(0);
996 })
997 };
998
999 // The child should be in our process group.
1000 assert_eq!(
1001 getpgid(child_pid).unwrap(),
1002 getpgid(ProcessId::new(0)).unwrap(),
1003 );
1004 // Move the child to its own process group
1005 setpgid(child_pid, child_pid).unwrap();
1006 // The process group of the child should have changed.
1007 assert_eq!(getpgid(child_pid).unwrap(), child_pid);
1008 }
1009 #[test]
1010 fn kill_test() {
1011 let mut child = std::process::Command::new("/bin/sleep")
1012 .arg("1")
1013 .spawn()
1014 .unwrap();
1015 super::kill(ProcessId::new(child.id() as i32), SIGKILL).unwrap();
1016 assert!(!child.wait().unwrap().success());
1017 }
1018 #[test]
1019 fn killpg_test() {
1020 // Create a socket so the children write to it if they aren't terminated by `killpg`.
1021 let (mut rx, mut tx) = UnixStream::pair().unwrap();
1022
1023 let pid1 = unsafe {
1024 fork_for_test(|| {
1025 std::thread::sleep(std::time::Duration::from_secs(1));
1026 tx.write_all(&[42]).unwrap();
1027 exit(0);
1028 })
1029 };
1030
1031 let pid2 = unsafe {
1032 fork_for_test(|| {
1033 std::thread::sleep(std::time::Duration::from_secs(1));
1034 tx.write_all(&[42]).unwrap();
1035 exit(0);
1036 })
1037 };
1038
1039 drop(tx);
1040
1041 let pgid = pid1;
1042 // Move the children to their own process group.
1043 setpgid(pid1, pgid).unwrap();
1044 setpgid(pid2, pgid).unwrap();
1045 // Send `SIGKILL` to the children process group.
1046 super::killpg(pgid, SIGKILL).unwrap();
1047 // Ensure that the child were terminated before writing.
1048 assert_eq!(
1049 rx.read_exact(&mut [0; 2]).unwrap_err().kind(),
1050 std::io::ErrorKind::UnexpectedEof
1051 );
1052 }
1053
1054 fn is_cloexec<F: AsFd>(fd: &F) -> bool {
1055 crate::cutils::cerr(unsafe { libc::fcntl(fd.as_fd().as_raw_fd(), libc::F_GETFD) }).unwrap()
1056 & libc::FD_CLOEXEC
1057 == libc::FD_CLOEXEC
1058 }
1059
1060 #[test]
1061 fn mark_fds_as_cloexec() {
1062 let child_pid = unsafe {
1063 fork_for_test(|| {
1064 let should_close =
1065 std::fs::File::create(std::env::temp_dir().join("should_close.txt")).unwrap();
1066 crate::cutils::cerr(libc::fcntl(
1067 should_close.as_fd().as_raw_fd(),
1068 libc::F_SETFD,
1069 0,
1070 ))
1071 .unwrap();
1072 assert!(!is_cloexec(&should_close));
1073
1074 super::mark_fds_as_cloexec().unwrap();
1075
1076 assert!(is_cloexec(&should_close));
1077
1078 assert!(!is_cloexec(&io::stdin()));
1079 assert!(!is_cloexec(&io::stdout()));
1080 assert!(!is_cloexec(&io::stderr()));
1081
1082 exit(0)
1083 })
1084 };
1085
1086 let (_, status) = child_pid.wait(WaitOptions::new()).unwrap();
1087 assert_eq!(status.exit_status(), Some(0));
1088 }
1089
1090 #[cfg(target_os = "linux")]
1091 #[test]
1092 fn proc_stat_test() {
1093 use super::{Process, WithProcess::Current, read_proc_stat};
1094 // The process can be '(uninterruptible) sleeping' or 'running': it looks like the state
1095 // field of /proc/pid/stat will show the state for the main thread of the process rather
1096 // than for the process as a whole.
1097 let state = read_proc_stat::<char>(Current, 2).unwrap();
1098 assert!("SDR".contains(state), "{state} is not S, D or R");
1099 let parent = Process::parent_id().unwrap();
1100 // field 3 is always the parent process
1101 assert_eq!(
1102 parent,
1103 ProcessId::new(read_proc_stat::<i32>(Current, 3).unwrap())
1104 );
1105 // this next field should always be 0 (which precedes an important bit of info for us!)
1106 assert_eq!(0, read_proc_stat::<i32>(Current, 20).unwrap());
1107 }
1108 }