| 1 | mod event; |
| 2 | mod io_util; |
| 3 | mod no_pty; |
| 4 | #[cfg(target_os = "linux")] |
| 5 | mod noexec; |
| 6 | mod use_pty; |
| 7 | |
| 8 | use std::{ |
| 9 | borrow::Cow, |
| 10 | convert::Infallible, |
| 11 | env, |
| 12 | ffi::{OsStr, OsString, c_int}, |
| 13 | io, |
| 14 | os::unix::{ffi::OsStrExt, process::CommandExt}, |
| 15 | path::{Path, PathBuf}, |
| 16 | process::{self, Command}, |
| 17 | time::Duration, |
| 18 | }; |
| 19 | |
| 20 | use crate::{ |
| 21 | common::{ |
| 22 | HARDENED_ENUM_VALUE_0, HARDENED_ENUM_VALUE_1, HARDENED_ENUM_VALUE_2, bin_serde::BinPipe, |
| 23 | }, |
| 24 | exec::no_pty::exec_no_pty, |
| 25 | log::{dev_info, dev_warn, user_error}, |
| 26 | system::{ |
| 27 | _exit, ForkResult, Group, User, fork, |
| 28 | interface::ProcessId, |
| 29 | kill, killpg, mark_fds_as_cloexec, set_target_user, setpgid, |
| 30 | signal::{SignalNumber, SignalSet, SignalsState, consts::*, exit_with_signal, signal_name}, |
| 31 | term::UserTerm, |
| 32 | wait::{Wait, WaitError, WaitOptions}, |
| 33 | }, |
| 34 | }; |
| 35 | |
| 36 | use self::{ |
| 37 | event::{EventRegistry, Process}, |
| 38 | io_util::was_interrupted, |
| 39 | use_pty::{SIGCONT_BG, SIGCONT_FG, exec_pty}, |
| 40 | }; |
| 41 | |
| 42 | #[cfg(target_os = "linux")] |
| 43 | use self::noexec::SpawnNoexecHandler; |
| 44 | #[cfg(not(target_os = "linux"))] |
| 45 | enum SpawnNoexecHandler {} |
| 46 | #[cfg(not(target_os = "linux"))] |
| 47 | impl SpawnNoexecHandler { |
| 48 | fn spawn(self) {} |
| 49 | } |
| 50 | |
| 51 | #[derive(Debug, Copy, Clone)] |
| 52 | #[cfg_attr(test, derive(PartialEq))] |
| 53 | #[repr(u32)] |
| 54 | pub enum Umask { |
| 55 | /// Keep the umask of the parent process. |
| 56 | Preserve = HARDENED_ENUM_VALUE_0, |
| 57 | /// Mask out more of the permission bits in the new umask. |
| 58 | Extend(libc::mode_t) = HARDENED_ENUM_VALUE_1, |
| 59 | /// Override the umask of the parent process entirely with the given umask. |
| 60 | Override(libc::mode_t) = HARDENED_ENUM_VALUE_2, |
| 61 | } |
| 62 | |
| 63 | pub struct RunOptions<'a> { |
| 64 | pub command: &'a Path, |
| 65 | pub arguments: &'a [OsString], |
| 66 | pub arg0: Option<&'a Path>, |
| 67 | pub chdir: Option<PathBuf>, |
| 68 | pub is_login: bool, |
| 69 | pub user: &'a User, |
| 70 | pub group: &'a Group, |
| 71 | pub umask: Umask, |
| 72 | |
| 73 | pub background: bool, |
| 74 | pub use_pty: bool, |
| 75 | pub noexec: bool, |
| 76 | } |
| 77 | |
| 78 | /// Based on `ogsudo`s `exec_pty` function. |
| 79 | /// |
| 80 | /// Returns the [`ExitReason`] of the command and a function that restores the default handler for |
| 81 | /// signals once its called. |
| 82 | pub fn run_command( |
| 83 | options: RunOptions<'_>, |
| 84 | env: impl IntoIterator<Item = (impl AsRef<OsStr>, impl AsRef<OsStr>)>, |
| 85 | ) -> io::Result<ExitReason> { |
| 86 | if options.background { |
| 87 | // SAFETY: There should be no other threads at this point. |
| 88 | match unsafe { fork() }? { |
| 89 | ForkResult::Parent(_) => process::exit(0), |
| 90 | ForkResult::Child => { |
| 91 | // Child continues in an orphaned process group. |
| 92 | // Reads from the terminal fail with EIO. |
| 93 | // Writes succeed unless tostop is set on the terminal. |
| 94 | setpgid(ProcessId::new(0), ProcessId::new(0))?; |
| 95 | } |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | // FIXME: should we pipe the stdio streams? |
| 100 | let qualified_path = options.command; |
| 101 | let mut command = Command::new(qualified_path); |
| 102 | // reset env and set filtered environment |
| 103 | command.args(options.arguments).env_clear().envs(env); |
| 104 | // set the arg0 to the requested string |
| 105 | // TODO: this mechanism could perhaps also be used to set the arg0 for login shells, as below |
| 106 | if let Some(arg0) = options.arg0 { |
| 107 | command.arg0(arg0); |
| 108 | } |
| 109 | |
| 110 | if options.is_login { |
| 111 | // signal to the operating system that the command is a login shell by prefixing "-" |
| 112 | let mut process_name = qualified_path |
| 113 | .file_name() |
| 114 | .map(|osstr| osstr.as_bytes().to_vec()) |
| 115 | .unwrap_or_default(); |
| 116 | process_name.insert(0, b'-'); |
| 117 | command.arg0(OsStr::from_bytes(&process_name)); |
| 118 | } |
| 119 | |
| 120 | let spawn_noexec_handler = if options.noexec { |
| 121 | #[cfg(not(target_os = "linux"))] |
| 122 | return Err(io::Error::new( |
| 123 | io::ErrorKind::Other, |
| 124 | "NOEXEC is currently only supported on Linux", |
| 125 | )); |
| 126 | |
| 127 | #[cfg(target_os = "linux")] |
| 128 | Some(noexec::add_noexec_filter(&mut command)?) |
| 129 | } else { |
| 130 | None |
| 131 | }; |
| 132 | |
| 133 | // Decide if the pwd should be changed. `--chdir` takes precedence over `-i`. |
| 134 | let path = options |
| 135 | .chdir |
| 136 | .as_ref() |
| 137 | .map(|chdir| chdir.to_owned()) |
| 138 | .or_else(|| options.is_login.then(|| options.user.home.clone().into())) |
| 139 | .clone(); |
| 140 | |
| 141 | // set target user and groups |
| 142 | set_target_user(&mut command, options.user.clone(), options.group.clone()); |
| 143 | |
| 144 | // change current directory if necessary. |
| 145 | if let Some(path) = path { |
| 146 | let is_chdir = options.chdir.is_some(); |
| 147 | |
| 148 | // SAFETY: Chdir as used internally by set_current_dir is async-signal-safe. The logger we |
| 149 | // use is also async-signal-safe. |
| 150 | unsafe { |
| 151 | command.pre_exec(move || { |
| 152 | if let Err(err) = env::set_current_dir(&path) { |
| 153 | user_error!( |
| 154 | "unable to change directory to {path}: {error}", |
| 155 | path = path.display(), |
| 156 | error = err |
| 157 | ); |
| 158 | if is_chdir { |
| 159 | return Err(err); |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | Ok(()) |
| 164 | }); |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | // SAFETY: Umask is async-signal-safe. |
| 169 | unsafe { |
| 170 | let umask = options.umask; |
| 171 | |
| 172 | command.pre_exec(move || { |
| 173 | match umask { |
| 174 | Umask::Preserve => {} |
| 175 | Umask::Extend(umask) => { |
| 176 | // The only options to get the existing umask are overwriting it or |
| 177 | // parsing a /proc file. Given that this is a single-threaded context, |
| 178 | // overwrite it with a safe value is fine and the simpler option. |
| 179 | let existing_umask = libc::umask(0o777); |
| 180 | libc::umask(existing_umask | umask); |
| 181 | } |
| 182 | Umask::Override(umask) => { |
| 183 | libc::umask(umask); |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | Ok(()) |
| 188 | }); |
| 189 | } |
| 190 | |
| 191 | let sudo_pid = ProcessId::new(std::process::id() as i32); |
| 192 | |
| 193 | if options.use_pty { |
| 194 | match UserTerm::open() { |
| 195 | Ok(user_tty) => exec_pty( |
| 196 | sudo_pid, |
| 197 | spawn_noexec_handler, |
| 198 | command, |
| 199 | user_tty, |
| 200 | options.user, |
| 201 | options.background, |
| 202 | ), |
| 203 | Err(err) => { |
| 204 | dev_info!("Could not open user's terminal, not allocating a pty: {err}"); |
| 205 | exec_no_pty(sudo_pid, spawn_noexec_handler, command) |
| 206 | } |
| 207 | } |
| 208 | } else { |
| 209 | exec_no_pty(sudo_pid, spawn_noexec_handler, command) |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | /// Exit reason for the command executed by sudo. |
| 214 | #[derive(Debug)] |
| 215 | pub enum ExitReason { |
| 216 | Code(i32), |
| 217 | Signal(i32), |
| 218 | } |
| 219 | |
| 220 | impl ExitReason { |
| 221 | pub(crate) fn exit_process(self) -> Result<Infallible, crate::common::Error> { |
| 222 | match self { |
| 223 | ExitReason::Code(code) => process::exit(code), |
| 224 | ExitReason::Signal(signal) => exit_with_signal(signal), |
| 225 | } |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | fn exec_command( |
| 230 | mut command: Command, |
| 231 | original_set: Option<SignalSet>, |
| 232 | mut original_signal: SignalsState, |
| 233 | mut errpipe_tx: BinPipe<i32>, |
| 234 | ) -> ! { |
| 235 | // Restore the signal handlers of modified signals |
| 236 | if let Err(err) = original_signal.restore() { |
| 237 | dev_warn!("cannot restore signal states: {err}"); |
| 238 | } |
| 239 | |
| 240 | // Restore the signal mask now that the handlers have been setup. |
| 241 | if let Some(set) = original_set { |
| 242 | if let Err(err) = set.set_mask() { |
| 243 | dev_warn!("cannot restore signal mask: {err}"); |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | if let Err(err) = mark_fds_as_cloexec() { |
| 248 | dev_warn!("failed to close the universe: {err}"); |
| 249 | // Send the error to the monitor using the pipe. |
| 250 | if let Some(error_code) = err.raw_os_error() { |
| 251 | errpipe_tx.write(&error_code).ok(); |
| 252 | } |
| 253 | |
| 254 | // We call `_exit` instead of `exit` to avoid flushing the parent's IO streams by accident. |
| 255 | _exit(1); |
| 256 | } |
| 257 | |
| 258 | let err = command.exec(); |
| 259 | |
| 260 | dev_warn!("failed to execute command: {err}"); |
| 261 | // If `exec` returns, it means that executing the command failed. Send the error to the |
| 262 | // monitor using the pipe. |
| 263 | if let Some(error_code) = err.raw_os_error() { |
| 264 | errpipe_tx.write(&error_code).ok(); |
| 265 | } |
| 266 | |
| 267 | // We call `_exit` instead of `exit` to avoid flushing the parent's IO streams by accident. |
| 268 | _exit(1); |
| 269 | } |
| 270 | |
| 271 | // Kill the process with increasing urgency. |
| 272 | // |
| 273 | // Based on `terminate_command`. |
| 274 | fn terminate_process(pid: ProcessId, use_killpg: bool) { |
| 275 | let kill_fn = if use_killpg { killpg } else { kill }; |
| 276 | kill_fn(pid, SIGHUP).ok(); |
| 277 | kill_fn(pid, SIGTERM).ok(); |
| 278 | std::thread::sleep(Duration::from_secs(2)); |
| 279 | kill_fn(pid, SIGKILL).ok(); |
| 280 | } |
| 281 | |
| 282 | trait HandleSigchld: Process { |
| 283 | const OPTIONS: WaitOptions; |
| 284 | |
| 285 | fn on_exit(&mut self, exit_code: c_int, registry: &mut EventRegistry<Self>); |
| 286 | fn on_term(&mut self, signal: SignalNumber, registry: &mut EventRegistry<Self>); |
| 287 | fn on_stop(&mut self, signal: SignalNumber, registry: &mut EventRegistry<Self>); |
| 288 | } |
| 289 | |
| 290 | fn handle_sigchld<T: HandleSigchld>( |
| 291 | handler: &mut T, |
| 292 | registry: &mut EventRegistry<T>, |
| 293 | child_name: &'static str, |
| 294 | child_pid: ProcessId, |
| 295 | ) { |
| 296 | let status = loop { |
| 297 | match child_pid.wait(T::OPTIONS) { |
| 298 | Err(WaitError::Io(err)) if was_interrupted(&err) => {} |
| 299 | // This only happens if we receive `SIGCHLD` but there's no status update from the |
| 300 | // monitor. |
| 301 | Err(WaitError::Io(err)) => { |
| 302 | return dev_info!("cannot wait for {child_pid} ({child_name}): {err}"); |
| 303 | } |
| 304 | // This only happens if the monitor exited and any process already waited for the |
| 305 | // monitor. |
| 306 | Err(WaitError::NotReady) => { |
| 307 | return dev_info!("{child_pid} ({child_name}) has no status report"); |
| 308 | } |
| 309 | Ok((_pid, status)) => break status, |
| 310 | } |
| 311 | }; |
| 312 | if let Some(exit_code) = status.exit_status() { |
| 313 | dev_info!("{child_pid} ({child_name}) exited with status code {exit_code}"); |
| 314 | handler.on_exit(exit_code, registry) |
| 315 | } else if let Some(signal) = status.stop_signal() { |
| 316 | dev_info!( |
| 317 | "{child_pid} ({child_name}) was stopped by {}", |
| 318 | signal_fmt(signal), |
| 319 | ); |
| 320 | handler.on_stop(signal, registry) |
| 321 | } else if let Some(signal) = status.term_signal() { |
| 322 | dev_info!( |
| 323 | "{child_pid} ({child_name}) was terminated by {}", |
| 324 | signal_fmt(signal), |
| 325 | ); |
| 326 | handler.on_term(signal, registry) |
| 327 | } else if status.did_continue() { |
| 328 | dev_info!("{child_pid} ({child_name}) continued execution"); |
| 329 | } else { |
| 330 | dev_warn!("unexpected wait status for {child_pid} ({child_name})") |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | fn signal_fmt(signal: SignalNumber) -> Cow<'static, str> { |
| 335 | match signal_name(signal) { |
| 336 | name @ Cow::Owned(_) => match signal { |
| 337 | SIGCONT_BG => "SIGCONT_BG".into(), |
| 338 | SIGCONT_FG => "SIGCONT_FG".into(), |
| 339 | _ => name, |
| 340 | }, |
| 341 | name => name, |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | const fn cond_fmt<'a>(cond: bool, true_s: &'a str, false_s: &'a str) -> &'a str { |
| 346 | if cond { true_s } else { false_s } |
| 347 | } |
| 348 | |
| 349 | const fn opt_fmt(cond: bool, s: &str) -> &str { |
| 350 | cond_fmt(cond, s, "") |
| 351 | } |