| 1 | //! Parts of the code below are Copyright (c) 2023, Conrad Kleinespel et al |
| 2 | //! |
| 3 | //! This module contains code that was originally written by Conrad Kleinespel for the rpassword |
| 4 | //! crate. No copyright notices were found in the original code. |
| 5 | //! |
| 6 | //! See: <https://docs.rs/rpassword/latest/rpassword/> |
| 7 | //! |
| 8 | //! Most code was replaced and so is no longer a derived work; work that we kept: |
| 9 | //! |
| 10 | //! - the "HiddenInput" struct and implementation, with changes: |
| 11 | //! * replaced occurrences of explicit 'i32' and 'c_int' with RawFd |
| 12 | //! * open the TTY ourselves to mitigate Linux CVE-2023-2002 |
| 13 | //! - the general idea of a "SafeString" type that clears its memory |
| 14 | //! (although much more robust than in the original code) |
| 15 | |
| 16 | use std::ffi::c_void; |
| 17 | use std::io::{self, ErrorKind}; |
| 18 | use std::os::fd::{AsFd, AsRawFd, BorrowedFd}; |
| 19 | use std::path::PathBuf; |
| 20 | use std::time::{Duration, Instant}; |
| 21 | use std::{fs, mem}; |
| 22 | |
| 23 | use libc::{ |
| 24 | ECHO, ECHONL, ICANON, SIGALRM, SIGHUP, SIGINT, SIGQUIT, SIGTERM, SIGTSTP, SIGTTIN, SIGTTOU, |
| 25 | TCSANOW, VEOF, VERASE, VKILL, tcsetattr, termios, |
| 26 | }; |
| 27 | |
| 28 | use crate::cutils::{cerr, safe_isatty}; |
| 29 | use crate::pam::{PamError, PamResult, askpass}; |
| 30 | use crate::system::signal::{ |
| 31 | self, SignalHandler, SignalHandlerBehavior, SignalsState, exit_with_signal, |
| 32 | }; |
| 33 | use crate::system::wait::{Wait, WaitError, WaitOptions}; |
| 34 | |
| 35 | use super::securemem::PamBuffer; |
| 36 | |
| 37 | struct HiddenInput<'a> { |
| 38 | tty: BorrowedFd<'a>, |
| 39 | term_orig: termios, |
| 40 | } |
| 41 | |
| 42 | impl HiddenInput<'_> { |
| 43 | fn new(tty: BorrowedFd) -> io::Result<HiddenInput> { |
| 44 | // Make two copies of the terminal settings. The first one will be modified |
| 45 | // and the second one will act as a backup for when we want to set the |
| 46 | // terminal back to its original state. |
| 47 | let mut term = safe_tcgetattr(tty)?; |
| 48 | let term_orig = safe_tcgetattr(tty)?; |
| 49 | |
| 50 | // Hide the password. This is what makes this function useful. |
| 51 | term.c_lflag &= !ECHO; |
| 52 | |
| 53 | // But don't hide the NL character when the user hits ENTER. |
| 54 | term.c_lflag |= ECHONL; |
| 55 | |
| 56 | // Disable canonical mode to read character by character when pwfeedback is enabled. |
| 57 | term.c_lflag &= !ICANON; |
| 58 | |
| 59 | // Save the settings for now. |
| 60 | // SAFETY: we are passing tcsetattr a valid file descriptor and pointer-to-struct |
| 61 | cerr(unsafe { tcsetattr(tty.as_raw_fd(), TCSANOW, &term) })?; |
| 62 | |
| 63 | Ok(HiddenInput { tty, term_orig }) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | impl Drop for HiddenInput<'_> { |
| 68 | fn drop(&mut self) { |
| 69 | // Set the the mode back to normal |
| 70 | // SAFETY: we are passing tcsetattr a valid file descriptor and pointer-to-struct |
| 71 | unsafe { |
| 72 | tcsetattr(self.tty.as_raw_fd(), TCSANOW, &self.term_orig); |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | fn safe_tcgetattr(tty: impl AsFd) -> io::Result<termios> { |
| 78 | let mut term = mem::MaybeUninit::<termios>::uninit(); |
| 79 | // SAFETY: we are passing tcgetattr a pointer to valid memory |
| 80 | cerr(unsafe { ::libc::tcgetattr(tty.as_fd().as_raw_fd(), term.as_mut_ptr()) })?; |
| 81 | // SAFETY: if the previous call was a success, `tcgetattr` has initialized `term` |
| 82 | Ok(unsafe { term.assume_init() }) |
| 83 | } |
| 84 | |
| 85 | fn erase_feedback(sink: &mut dyn io::Write, i: usize) { |
| 86 | const BACKSPACE: u8 = 0x08; |
| 87 | for _ in 0..i { |
| 88 | if sink.write(&[BACKSPACE, b' ', BACKSPACE]).is_err() { |
| 89 | return; |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | // Erase everyting after the cursor to make sure we don't leak the password |
| 94 | // size through the amount of spaces that are shown if you select the line |
| 95 | // containing the password in your terminal emulator. |
| 96 | // CSI n K: Erase in Line, 0 = erase from cursor to end of line |
| 97 | let _ = sink.write(b"\x1b[0K"); |
| 98 | } |
| 99 | |
| 100 | #[derive(Clone)] |
| 101 | pub(super) enum Hidden<T> { |
| 102 | No, |
| 103 | Yes(T), |
| 104 | WithFeedback(T), |
| 105 | } |
| 106 | |
| 107 | /// Prompt for a password while optionally showing feedback to the user. |
| 108 | fn prompt_password( |
| 109 | source: BorrowedFd<'_>, |
| 110 | sink: &mut dyn io::Write, |
| 111 | prompt: &str, |
| 112 | timeout: Option<Duration>, |
| 113 | hidden: Hidden<()>, |
| 114 | ) -> PamResult<PamBuffer> { |
| 115 | 'getpass: loop { |
| 116 | let hide_input = match hidden.clone() { |
| 117 | // If input is not a tty, we can't hide feedback. |
| 118 | _ if !safe_isatty(source) => Hidden::No, |
| 119 | |
| 120 | Hidden::No => Hidden::No, |
| 121 | Hidden::Yes(()) => Hidden::Yes(HiddenInput::new(source)?), |
| 122 | Hidden::WithFeedback(()) => Hidden::WithFeedback(HiddenInput::new(source)?), |
| 123 | }; |
| 124 | let mut reader = TimeoutRead::new(source, timeout); |
| 125 | |
| 126 | // Write prompt after hiding input to ensure the prompt shows after resuming sudo-rs if it |
| 127 | // was started in the background using & rather than -b. |
| 128 | write_unbuffered(sink, prompt.as_bytes())?; |
| 129 | |
| 130 | let handlers = { |
| 131 | // Creating a new SignalsState is fine here as we are guaranteed to restore the signals |
| 132 | // again before returning. |
| 133 | let original_signals: &mut SignalsState = &mut SignalsState::save().unwrap(); |
| 134 | [ |
| 135 | SIGALRM, SIGINT, SIGHUP, SIGQUIT, SIGTERM, SIGTSTP, SIGTTIN, SIGTTOU, |
| 136 | ] |
| 137 | .map(|signal| { |
| 138 | SignalHandler::register( |
| 139 | signal, |
| 140 | SignalHandlerBehavior::StorePending, |
| 141 | original_signals, |
| 142 | ) |
| 143 | .unwrap() |
| 144 | }) |
| 145 | }; |
| 146 | |
| 147 | let res = read_unbuffered(&mut reader, sink, &hide_input); |
| 148 | |
| 149 | drop(hide_input); |
| 150 | drop(handlers); |
| 151 | |
| 152 | while let Some(signal) = signal::take_first_pending() { |
| 153 | match signal { |
| 154 | SIGTSTP | SIGTTIN | SIGTTOU => { |
| 155 | crate::system::kill(crate::system::Process::process_id(), signal)?; |
| 156 | continue 'getpass; |
| 157 | } |
| 158 | _ => { |
| 159 | exit_with_signal(signal).unwrap(); |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | return res; |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | /// Heuristically determine the length of the final (potentially incomplete) UTF8 sequence |
| 169 | fn last_char_size(slice: &[u8]) -> usize { |
| 170 | let start = |byte| byte & 0b1100_0000 == 0b1100_0000; |
| 171 | let trail = |byte| byte & 0b1100_0000 == 0b1000_0000; |
| 172 | |
| 173 | match slice { |
| 174 | [] => 0, |
| 175 | [.., a, b] if start(a) && trail(b) => 2, |
| 176 | [.., a, b, c] if start(a) && [b, c].into_iter().all(trail) => 3, |
| 177 | [.., a, b, c, d] if start(a) && [b, c, d].into_iter().all(trail) => 4, |
| 178 | _ => 1, |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | /// Reads a password from the given file descriptor while optionally showing feedback to the user. |
| 183 | fn read_unbuffered( |
| 184 | source: &mut TimeoutRead<'_>, |
| 185 | sink: &mut dyn io::Write, |
| 186 | hide_input: &Hidden<HiddenInput>, |
| 187 | ) -> PamResult<PamBuffer> { |
| 188 | struct Bullets<'a> { |
| 189 | visible_len: Option<usize>, |
| 190 | sink: &'a mut dyn io::Write, |
| 191 | } |
| 192 | |
| 193 | const BULLET: &[u8] = b"*"; |
| 194 | |
| 195 | impl Bullets<'_> { |
| 196 | fn push(&mut self) { |
| 197 | if let Some(ref mut len) = self.visible_len { |
| 198 | let _ = self.sink.write(BULLET); |
| 199 | *len += 1; |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | fn pop(&mut self) { |
| 204 | match self.visible_len { |
| 205 | Some(ref mut len) if *len > 0 => { |
| 206 | erase_feedback(self.sink, 1); |
| 207 | *len -= 1; |
| 208 | } |
| 209 | _ => {} |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | fn clear(&mut self) { |
| 214 | if let Some(ref mut len) = self.visible_len { |
| 215 | erase_feedback(self.sink, *len); |
| 216 | *len = 0; |
| 217 | } |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | // Ensure we erase the password feedback no matter how we exit read_unbuffered |
| 222 | impl Drop for Bullets<'_> { |
| 223 | fn drop(&mut self) { |
| 224 | self.clear(); |
| 225 | let _ = self.sink.write(b"\n"); |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | let mut feedback = Bullets { |
| 230 | visible_len: matches!(hide_input, Hidden::WithFeedback(_)).then_some(0), |
| 231 | sink, |
| 232 | }; |
| 233 | |
| 234 | let mut password = PamBuffer::default(); |
| 235 | let mut pw_len = 0; |
| 236 | |
| 237 | loop { |
| 238 | let read_byte = match source.read_byte() { |
| 239 | Ok(Some(byte)) => byte, |
| 240 | Ok(None) => break, |
| 241 | Err(err) if err.kind() == io::ErrorKind::TimedOut => return Err(PamError::TimedOut), |
| 242 | Err(err) => return Err(PamError::IoError(err)), |
| 243 | }; |
| 244 | |
| 245 | if read_byte == b'\n' || read_byte == b'\r' { |
| 246 | return Ok(password); |
| 247 | } |
| 248 | |
| 249 | if let Hidden::Yes(input) | Hidden::WithFeedback(input) = hide_input { |
| 250 | if read_byte == input.term_orig.c_cc[VEOF] { |
| 251 | break; |
| 252 | } |
| 253 | |
| 254 | if read_byte == input.term_orig.c_cc[VERASE] { |
| 255 | feedback.pop(); |
| 256 | let chunk = last_char_size(&password[..pw_len]); |
| 257 | password[pw_len - chunk..pw_len].fill(0); |
| 258 | pw_len -= chunk; |
| 259 | continue; |
| 260 | } |
| 261 | |
| 262 | if read_byte == input.term_orig.c_cc[VKILL] { |
| 263 | feedback.clear(); |
| 264 | password.fill(0); |
| 265 | pw_len = 0; |
| 266 | continue; |
| 267 | } |
| 268 | |
| 269 | if read_byte == b'\t' && feedback.visible_len.is_some() { |
| 270 | feedback.clear(); |
| 271 | feedback.visible_len = None; |
| 272 | let _ = feedback.sink.write(b"(no echo)"); |
| 273 | continue; |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | if let Some(dest) = password.get_mut(pw_len) { |
| 278 | *dest = read_byte; |
| 279 | pw_len += 1; |
| 280 | if last_char_size(&password[..pw_len]) == 1 { |
| 281 | feedback.push(); |
| 282 | } |
| 283 | } else { |
| 284 | return Err(PamError::IncorrectPasswordAttempt); |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | if pw_len == 0 { |
| 289 | // In case of EOF or Ctrl-D we don't want to ask for a password a second |
| 290 | // time, so return an error. |
| 291 | Err(PamError::NoPasswordProvided) |
| 292 | } else { |
| 293 | Ok(password) |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | /// Write something and immediately flush |
| 298 | fn write_unbuffered(sink: &mut dyn io::Write, text: &[u8]) -> io::Result<()> { |
| 299 | sink.write_all(text)?; |
| 300 | sink.flush() |
| 301 | } |
| 302 | |
| 303 | struct TimeoutRead<'a> { |
| 304 | timeout_at: Option<Instant>, |
| 305 | fd: BorrowedFd<'a>, |
| 306 | } |
| 307 | |
| 308 | impl<'a> TimeoutRead<'a> { |
| 309 | fn new(fd: BorrowedFd<'a>, timeout: Option<Duration>) -> TimeoutRead<'a> { |
| 310 | TimeoutRead { |
| 311 | timeout_at: timeout.map(|timeout| Instant::now() + timeout), |
| 312 | fd, |
| 313 | } |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | impl TimeoutRead<'_> { |
| 318 | fn read_byte(&mut self) -> io::Result<Option<u8>> { |
| 319 | let pollmask = libc::POLLIN | libc::POLLRDHUP; |
| 320 | |
| 321 | let mut pollfd = [libc::pollfd { |
| 322 | fd: self.fd.as_raw_fd(), |
| 323 | events: pollmask, |
| 324 | revents: 0, |
| 325 | }; 1]; |
| 326 | |
| 327 | let timeout = match self.timeout_at { |
| 328 | Some(timeout_at) => { |
| 329 | let now = Instant::now(); |
| 330 | if now > timeout_at { |
| 331 | return Err(io::Error::from(ErrorKind::TimedOut)); |
| 332 | } |
| 333 | |
| 334 | (timeout_at - now) |
| 335 | .as_millis() |
| 336 | .try_into() |
| 337 | .unwrap_or(i32::MAX) |
| 338 | } |
| 339 | None => -1, |
| 340 | }; |
| 341 | |
| 342 | if cfg!(miri) { |
| 343 | // Miri doesn't support poll: rust-lang/miri#4413 |
| 344 | // FIXME(#1500) remove once miri supports it |
| 345 | pollfd[0].revents = libc::POLLIN; |
| 346 | } else { |
| 347 | // SAFETY: pollfd is initialized and its length matches |
| 348 | cerr(unsafe { |
| 349 | libc::poll( |
| 350 | pollfd.as_mut_ptr(), |
| 351 | pollfd.len().try_into().unwrap(), |
| 352 | timeout, |
| 353 | ) |
| 354 | })?; |
| 355 | } |
| 356 | |
| 357 | // There may yet be data waiting to be read even if POLLHUP is set. |
| 358 | if pollfd[0].revents & (pollmask | libc::POLLHUP) > 0 { |
| 359 | let mut buf = [0u8]; |
| 360 | |
| 361 | // SAFETY: buf is initialized and its length matches |
| 362 | let ret = cerr(unsafe { |
| 363 | libc::read( |
| 364 | self.fd.as_raw_fd(), |
| 365 | buf.as_mut_ptr() as *mut c_void, |
| 366 | buf.len(), |
| 367 | ) |
| 368 | })?; |
| 369 | |
| 370 | if ret != 1 { |
| 371 | return Ok(None); |
| 372 | } |
| 373 | |
| 374 | Ok(Some(buf[0])) |
| 375 | } else { |
| 376 | Err(io::Error::from(io::ErrorKind::TimedOut)) |
| 377 | } |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | /// A data structure representing either /dev/tty or /dev/stdin+stderr |
| 382 | pub enum Terminal<'a> { |
| 383 | Tty(fs::File), |
| 384 | StdIE(io::StdinLock<'a>, io::StderrLock<'a>), |
| 385 | Askpass(PathBuf, io::Sink), |
| 386 | } |
| 387 | |
| 388 | impl Terminal<'_> { |
| 389 | /// Open the current TTY for user communication |
| 390 | pub fn open_tty() -> PamResult<Self> { |
| 391 | // control ourselves that we are really talking to a TTY |
| 392 | // mitigates: https://marc.info/?l=oss-security&m=168164424404224 |
| 393 | Ok(Terminal::Tty( |
| 394 | fs::OpenOptions::new() |
| 395 | .read(true) |
| 396 | .write(true) |
| 397 | .open("/dev/tty") |
| 398 | .map_err(|_| PamError::TtyRequired)?, |
| 399 | )) |
| 400 | } |
| 401 | |
| 402 | /// Open standard input and standard error for user communication |
| 403 | pub fn open_stdie() -> io::Result<Self> { |
| 404 | Ok(Terminal::StdIE(io::stdin().lock(), io::stderr().lock())) |
| 405 | } |
| 406 | |
| 407 | pub fn open_askpass() -> PamResult<Self> { |
| 408 | let Some(program) = std::env::var_os("SUDO_ASKPASS") else { |
| 409 | return Err(PamError::NoAskpassProgram); |
| 410 | }; |
| 411 | let program = PathBuf::from(program); |
| 412 | |
| 413 | if program.is_absolute() { |
| 414 | Ok(Terminal::Askpass(program, io::sink())) |
| 415 | } else { |
| 416 | Err(PamError::InvalidAskpassProgram(program)) |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | /// Reads input with TTY echo and visual feedback set according to the `hidden` parameter. |
| 421 | pub(super) fn read_input( |
| 422 | &mut self, |
| 423 | prompt: &str, |
| 424 | timeout: Option<Duration>, |
| 425 | hidden: Hidden<()>, |
| 426 | ) -> PamResult<PamBuffer> { |
| 427 | match self { |
| 428 | Terminal::StdIE(stdin, stdout) => { |
| 429 | prompt_password(stdin.as_fd(), stdout, prompt, timeout, hidden) |
| 430 | } |
| 431 | Terminal::Tty(file) => { |
| 432 | prompt_password(file.as_fd(), &mut &*file, prompt, timeout, hidden) |
| 433 | } |
| 434 | Terminal::Askpass(program, sink) => { |
| 435 | let (command_pid, askpass_stdout) = askpass::spawn_askpass(program, prompt)?; |
| 436 | |
| 437 | let mut reader = TimeoutRead::new(askpass_stdout.as_fd(), None); |
| 438 | let password = read_unbuffered(&mut reader, sink, &Hidden::No)?; |
| 439 | |
| 440 | loop { |
| 441 | match command_pid.wait(WaitOptions::new()) { |
| 442 | Ok(_) => break, |
| 443 | Err(WaitError::Io(err)) if err.kind() == io::ErrorKind::Interrupted => {} |
| 444 | Err(WaitError::Io(err)) => return Err(PamError::IoError(err)), |
| 445 | Err(WaitError::NotReady) => unreachable!(), |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | Ok(password) |
| 450 | } |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | /// Display information |
| 455 | pub fn prompt(&mut self, text: &str) -> io::Result<()> { |
| 456 | write_unbuffered(self.sink(), text.as_bytes()) |
| 457 | } |
| 458 | |
| 459 | /// Ring the bell |
| 460 | pub fn bell(&mut self) -> io::Result<()> { |
| 461 | const BELL: &[u8; 1] = b"\x07"; |
| 462 | write_unbuffered(self.sink(), BELL) |
| 463 | } |
| 464 | |
| 465 | // boilerplate reduction functions |
| 466 | fn sink(&mut self) -> &mut dyn io::Write { |
| 467 | match self { |
| 468 | Terminal::StdIE(_, x) => x, |
| 469 | Terminal::Tty(x) => x, |
| 470 | Terminal::Askpass(_, x) => x, |
| 471 | } |
| 472 | } |
| 473 | } |
| 474 | |
| 475 | #[cfg(test)] |
| 476 | mod test { |
| 477 | use std::fs::File; |
| 478 | use std::io::{Read, Write}; |
| 479 | use std::os::fd::FromRawFd; |
| 480 | |
| 481 | use libc::O_CLOEXEC; |
| 482 | |
| 483 | use super::*; |
| 484 | |
| 485 | fn make_pipe() -> (File, File) { |
| 486 | // SAFETY: A valid pointer to a mutable array of 2 fds is passed in. |
| 487 | unsafe { |
| 488 | let mut pipes = [-1, -1]; |
| 489 | cerr(libc::pipe2(pipes.as_mut_ptr(), O_CLOEXEC)).unwrap(); |
| 490 | (File::from_raw_fd(pipes[0]), File::from_raw_fd(pipes[1])) |
| 491 | } |
| 492 | } |
| 493 | |
| 494 | #[test] |
| 495 | fn miri_test_read() { |
| 496 | let mut stdout = Vec::new(); |
| 497 | let (mut rx, mut tx) = make_pipe(); |
| 498 | tx.write_all("password123\nhello world".as_bytes()).unwrap(); |
| 499 | drop(tx); |
| 500 | let buf = read_unbuffered( |
| 501 | &mut TimeoutRead::new(rx.as_fd(), None), |
| 502 | &mut stdout, |
| 503 | &Hidden::No, |
| 504 | ) |
| 505 | .unwrap(); |
| 506 | // check that the \n is not part of input |
| 507 | assert_eq!( |
| 508 | buf.iter() |
| 509 | .map(|&b| b as char) |
| 510 | .take_while(|&x| x != '\0') |
| 511 | .collect::<String>(), |
| 512 | "password123" |
| 513 | ); |
| 514 | // check that the \n is also consumed but the rest of the input is still there |
| 515 | let mut data = vec![0; "hello world".len()]; |
| 516 | rx.read_exact(&mut data).unwrap(); |
| 517 | assert_eq!(data, b"hello world"); |
| 518 | } |
| 519 | |
| 520 | #[test] |
| 521 | fn miri_test_longpwd() { |
| 522 | let mut stdout = Vec::new(); |
| 523 | let (rx, mut tx) = make_pipe(); |
| 524 | tx.write_all("a".repeat(511).as_bytes()).unwrap(); |
| 525 | drop(tx); |
| 526 | assert!( |
| 527 | read_unbuffered( |
| 528 | &mut TimeoutRead::new(rx.as_fd(), None), |
| 529 | &mut stdout, |
| 530 | &Hidden::No |
| 531 | ) |
| 532 | .is_ok() |
| 533 | ); |
| 534 | |
| 535 | let (rx, mut tx) = make_pipe(); |
| 536 | tx.write_all("a".repeat(512).as_bytes()).unwrap(); |
| 537 | drop(tx); |
| 538 | assert!( |
| 539 | read_unbuffered( |
| 540 | &mut TimeoutRead::new(rx.as_fd(), None), |
| 541 | &mut stdout, |
| 542 | &Hidden::No |
| 543 | ) |
| 544 | .is_err() |
| 545 | ); |
| 546 | } |
| 547 | |
| 548 | #[test] |
| 549 | fn miri_test_write() { |
| 550 | let mut data = Vec::new(); |
| 551 | write_unbuffered(&mut data, b"prompt").unwrap(); |
| 552 | assert_eq!(std::str::from_utf8(&data).unwrap(), "prompt"); |
| 553 | } |
| 554 | } |