| 1 | use std::cell::Cell; |
| 2 | use std::ffi::{c_int, c_void}; |
| 3 | use std::time::Duration; |
| 4 | |
| 5 | use crate::cutils::string_from_ptr; |
| 6 | use crate::pam::rpassword::Hidden; |
| 7 | use crate::system::signal::{self, SignalSet}; |
| 8 | |
| 9 | use super::sys::*; |
| 10 | |
| 11 | use super::{PamError, PamErrorType, error::PamResult, rpassword, securemem::PamBuffer}; |
| 12 | |
| 13 | /// Each message in a PAM conversation will have a message style. Each of these |
| 14 | /// styles must be handled separately. |
| 15 | #[derive(Clone, Copy, Eq, PartialEq)] |
| 16 | pub enum PamMessageStyle { |
| 17 | /// Prompt for input using a message. The input should considered secret |
| 18 | /// and should be hidden from view. |
| 19 | PromptEchoOff = PAM_PROMPT_ECHO_OFF as isize, |
| 20 | /// Prompt for input using a message. The input does not have to be |
| 21 | /// considered a secret and may be displayed to the user. |
| 22 | PromptEchoOn = PAM_PROMPT_ECHO_ON as isize, |
| 23 | /// Display an error message. The user should not be prompted for any input. |
| 24 | ErrorMessage = PAM_ERROR_MSG as isize, |
| 25 | /// Display some informational text. The user should not be prompted for any |
| 26 | /// input. |
| 27 | TextInfo = PAM_TEXT_INFO as isize, |
| 28 | } |
| 29 | |
| 30 | impl PamMessageStyle { |
| 31 | pub fn from_int(val: c_int) -> Option<PamMessageStyle> { |
| 32 | use PamMessageStyle::*; |
| 33 | |
| 34 | match val as _ { |
| 35 | PAM_PROMPT_ECHO_OFF => Some(PromptEchoOff), |
| 36 | PAM_PROMPT_ECHO_ON => Some(PromptEchoOn), |
| 37 | PAM_ERROR_MSG => Some(ErrorMessage), |
| 38 | PAM_TEXT_INFO => Some(TextInfo), |
| 39 | _ => None, |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | pub trait Converser { |
| 45 | /// Handle a normal prompt, i.e. present some message and ask for a value. |
| 46 | /// The value is not considered a secret. |
| 47 | fn handle_normal_prompt(&self, msg: &str) -> PamResult<PamBuffer>; |
| 48 | |
| 49 | /// Handle a hidden prompt, i.e. present some message and ask for a value. |
| 50 | /// The value is considered secret and should not be visible. |
| 51 | fn handle_hidden_prompt(&self, msg: &str) -> PamResult<PamBuffer>; |
| 52 | |
| 53 | /// Display an error message to the user, the user does not need to input a |
| 54 | /// value. |
| 55 | fn handle_error(&self, msg: &str) -> PamResult<()>; |
| 56 | |
| 57 | /// Display an informational message to the user, the user does not need to |
| 58 | /// input a value. |
| 59 | fn handle_info(&self, msg: &str) -> PamResult<()>; |
| 60 | } |
| 61 | |
| 62 | /// Handle a single message in a conversation. |
| 63 | fn handle_message<C: Converser>( |
| 64 | app_data: &ConverserData<C>, |
| 65 | style: PamMessageStyle, |
| 66 | msg: &str, |
| 67 | ) -> PamResult<Option<PamBuffer>> { |
| 68 | use PamMessageStyle::*; |
| 69 | |
| 70 | match style { |
| 71 | PromptEchoOn | PromptEchoOff if app_data.no_interact => Err(PamError::InteractionRequired), |
| 72 | |
| 73 | PromptEchoOn => app_data.converser.handle_normal_prompt(msg).map(Some), |
| 74 | PromptEchoOff => { |
| 75 | let final_prompt = match app_data.auth_prompt.as_deref() { |
| 76 | None => { |
| 77 | // Suppress password prompt entirely when -p '' is passed. |
| 78 | String::new() |
| 79 | } |
| 80 | Some(prompt) => { |
| 81 | format!("[{}: {prompt}] {msg}", app_data.converser_name) |
| 82 | } |
| 83 | }; |
| 84 | app_data |
| 85 | .converser |
| 86 | .handle_hidden_prompt(&final_prompt) |
| 87 | .map(Some) |
| 88 | } |
| 89 | |
| 90 | ErrorMessage => app_data.converser.handle_error(msg).map(|()| None), |
| 91 | TextInfo => app_data.converser.handle_info(msg).map(|()| None), |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | /// A converser that uses stdin/stdout/stderr to display messages and to request |
| 96 | /// input from the user. |
| 97 | pub struct CLIConverser { |
| 98 | pub(super) name: String, |
| 99 | pub(super) use_askpass: bool, |
| 100 | pub(super) use_stdin: bool, |
| 101 | pub(super) bell: Cell<bool>, |
| 102 | pub(super) password_feedback: bool, |
| 103 | pub(super) password_timeout: Option<Duration>, |
| 104 | } |
| 105 | |
| 106 | use rpassword::Terminal; |
| 107 | |
| 108 | struct SignalGuard(Option<SignalSet>); |
| 109 | |
| 110 | impl SignalGuard { |
| 111 | fn unblock_interrupts() -> Self { |
| 112 | let cur_signals = SignalSet::empty().and_then(|mut set| { |
| 113 | set.add(signal::consts::SIGINT)?; |
| 114 | set.add(signal::consts::SIGQUIT)?; |
| 115 | set.unblock() |
| 116 | }); |
| 117 | |
| 118 | Self(cur_signals.ok()) |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | impl Drop for SignalGuard { |
| 123 | fn drop(&mut self) { |
| 124 | if let Some(signal) = &self.0 { |
| 125 | // Ignore any errors at this point |
| 126 | let _ = signal.set_mask(); |
| 127 | } |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | impl CLIConverser { |
| 132 | fn open(&self) -> PamResult<(Terminal<'_>, SignalGuard)> { |
| 133 | let term = if self.use_askpass { |
| 134 | Terminal::open_askpass()? |
| 135 | } else if self.use_stdin { |
| 136 | Terminal::open_stdie()? |
| 137 | } else { |
| 138 | let mut tty = Terminal::open_tty()?; |
| 139 | if self.bell.replace(false) { |
| 140 | tty.bell()?; |
| 141 | } |
| 142 | |
| 143 | tty |
| 144 | }; |
| 145 | |
| 146 | Ok((term, SignalGuard::unblock_interrupts())) |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | impl Converser for CLIConverser { |
| 151 | fn handle_normal_prompt(&self, msg: &str) -> PamResult<PamBuffer> { |
| 152 | let (mut tty, _guard) = self.open()?; |
| 153 | let input_needed = xlat!("input needed"); |
| 154 | tty.read_input( |
| 155 | &format!("[{}: {input_needed} {msg} ", self.name), |
| 156 | None, |
| 157 | Hidden::No, |
| 158 | ) |
| 159 | } |
| 160 | |
| 161 | fn handle_hidden_prompt(&self, msg: &str) -> PamResult<PamBuffer> { |
| 162 | let (mut tty, _guard) = self.open()?; |
| 163 | tty.read_input( |
| 164 | msg, |
| 165 | self.password_timeout, |
| 166 | if self.password_feedback { |
| 167 | Hidden::WithFeedback(()) |
| 168 | } else { |
| 169 | Hidden::Yes(()) |
| 170 | }, |
| 171 | ) |
| 172 | } |
| 173 | |
| 174 | fn handle_error(&self, msg: &str) -> PamResult<()> { |
| 175 | let (mut tty, _) = self.open()?; |
| 176 | Ok(tty.prompt(&format!("[{} error] {msg}\n", self.name))?) |
| 177 | } |
| 178 | |
| 179 | fn handle_info(&self, msg: &str) -> PamResult<()> { |
| 180 | let (mut tty, _) = self.open()?; |
| 181 | Ok(tty.prompt(&format!("[{}] {msg}\n", self.name))?) |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | /// Helper struct that contains the converser as well as panic boolean |
| 186 | pub(super) struct ConverserData<C> { |
| 187 | pub(super) converser: C, |
| 188 | pub(super) converser_name: String, |
| 189 | pub(super) no_interact: bool, |
| 190 | pub(super) auth_prompt: Option<String>, |
| 191 | // pam_authenticate does not return error codes returned by the conversation |
| 192 | // function; these are set by the conversation function instead of returning |
| 193 | // multiple error codes. |
| 194 | pub(super) error: Option<PamError>, |
| 195 | pub(super) panicked: bool, |
| 196 | } |
| 197 | |
| 198 | /// This function implements the conversation function of `pam_conv`. |
| 199 | /// |
| 200 | /// This function should always be called with an appdata_ptr that implements |
| 201 | /// the `Converser` trait. It then collects the messages provided into a vector |
| 202 | /// that is passed to the converser. The converser can then respond to those |
| 203 | /// messages and add their replies (where applicable). Finally the replies are |
| 204 | /// converted back to the C interface and returned to PAM. This function tries |
| 205 | /// to catch any unwinding panics and sets state to indicate that a panic |
| 206 | /// occurred. |
| 207 | /// |
| 208 | /// # Safety |
| 209 | /// * If called with an appdata_ptr that does not correspond with the Converser |
| 210 | /// this function will exhibit undefined behavior. |
| 211 | /// * The messages from PAM are assumed to be formatted correctly. |
| 212 | pub(super) unsafe extern "C" fn converse<C: Converser>( |
| 213 | num_msg: c_int, |
| 214 | msg: *mut *const pam_message, |
| 215 | response: *mut *mut pam_response, |
| 216 | appdata_ptr: *mut c_void, |
| 217 | ) -> c_int { |
| 218 | let result = std::panic::catch_unwind(|| { |
| 219 | let mut resp_bufs = Vec::with_capacity(num_msg as usize); |
| 220 | for i in 0..num_msg as usize { |
| 221 | // convert the input messages to Rust types |
| 222 | // SAFETY: the PAM contract ensures that `num_msg` does not exceed the amount |
| 223 | // of messages presented to this function in `msg`, and that it is not being |
| 224 | // written to at the same time as we are reading it. Note that the reference |
| 225 | // we create does not escape this loopy body. |
| 226 | let message: &pam_message = unsafe { &**msg.add(i) }; |
| 227 | |
| 228 | // SAFETY: PAM ensures that the messages passed are properly null-terminated |
| 229 | let msg = unsafe { string_from_ptr(message.msg) }; |
| 230 | let style = if let Some(style) = PamMessageStyle::from_int(message.msg_style) { |
| 231 | style |
| 232 | } else { |
| 233 | // early return if there is a failure to convert, pam would have given us nonsense |
| 234 | return PamErrorType::ConversationError; |
| 235 | }; |
| 236 | |
| 237 | // send the conversation off to the Rust part |
| 238 | // SAFETY: appdata_ptr contains the `*mut ConverserData` that is untouched by PAM |
| 239 | let app_data = unsafe { &mut *(appdata_ptr as *mut ConverserData<C>) }; |
| 240 | |
| 241 | if app_data.error.is_some() |
| 242 | && (style == PamMessageStyle::PromptEchoOff |
| 243 | || style == PamMessageStyle::PromptEchoOn) |
| 244 | { |
| 245 | return PamErrorType::ConversationError; |
| 246 | } |
| 247 | |
| 248 | match handle_message(app_data, style, &msg) { |
| 249 | Ok(resp_buf) => { |
| 250 | resp_bufs.push(resp_buf); |
| 251 | } |
| 252 | Err(err) => { |
| 253 | app_data.error = Some(err); |
| 254 | return PamErrorType::ConversationError; |
| 255 | } |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | // Allocate enough memory for the responses, which are initialized with zero. |
| 260 | // SAFETY: this will either allocate the required amount of (initialized) bytes, |
| 261 | // or return a null pointer. |
| 262 | let temp_resp = unsafe { |
| 263 | libc::calloc( |
| 264 | num_msg as libc::size_t, |
| 265 | std::mem::size_of::<pam_response>() as libc::size_t, |
| 266 | ) |
| 267 | } as *mut pam_response; |
| 268 | if temp_resp.is_null() { |
| 269 | return PamErrorType::BufferError; |
| 270 | } |
| 271 | |
| 272 | // Store the responses |
| 273 | for (i, resp_buf) in resp_bufs.into_iter().enumerate() { |
| 274 | // SAFETY: `i` will not exceed `num_msg` by the way `conversation_messages` |
| 275 | // is constructed, so `temp_resp` will have allocated-and-initialized data at |
| 276 | // the required offset that only we have a writable pointer to. |
| 277 | let response: &mut pam_response = unsafe { &mut *(temp_resp.add(i)) }; |
| 278 | |
| 279 | if let Some(secbuf) = resp_buf { |
| 280 | response.resp = secbuf.leak().as_ptr().cast(); |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | // Set the responses |
| 285 | // SAFETY: PAM contract says that we are passed a valid, non-null, writeable pointer here. |
| 286 | unsafe { *response = temp_resp }; |
| 287 | |
| 288 | PamErrorType::Success |
| 289 | }); |
| 290 | |
| 291 | // handle any unwinding panics that occurred here |
| 292 | let res = match result { |
| 293 | Ok(r) => r, |
| 294 | Err(_) => { |
| 295 | // notify caller that a panic has occurred |
| 296 | // SAFETY: appdata_ptr contains the `*mut ConverserData` that is untouched by PAM |
| 297 | let app_data = unsafe { &mut *(appdata_ptr as *mut ConverserData<C>) }; |
| 298 | app_data.panicked = true; |
| 299 | |
| 300 | PamErrorType::ConversationError |
| 301 | } |
| 302 | }; |
| 303 | res.as_int() |
| 304 | } |
| 305 | |
| 306 | #[allow(clippy::undocumented_unsafe_blocks)] |
| 307 | #[cfg(test)] |
| 308 | mod test { |
| 309 | use super::*; |
| 310 | use PamMessageStyle::*; |
| 311 | use std::pin::Pin; |
| 312 | |
| 313 | struct PamMessage { |
| 314 | msg: String, |
| 315 | style: PamMessageStyle, |
| 316 | } |
| 317 | |
| 318 | impl Converser for String { |
| 319 | fn handle_normal_prompt(&self, msg: &str) -> PamResult<PamBuffer> { |
| 320 | Ok(PamBuffer::new(format!("{self} says {msg}").into_bytes())) |
| 321 | } |
| 322 | |
| 323 | fn handle_hidden_prompt(&self, msg: &str) -> PamResult<PamBuffer> { |
| 324 | Ok(PamBuffer::new(msg.as_bytes().to_vec())) |
| 325 | } |
| 326 | |
| 327 | fn handle_error(&self, msg: &str) -> PamResult<()> { |
| 328 | panic!("{msg}") |
| 329 | } |
| 330 | |
| 331 | fn handle_info(&self, _msg: &str) -> PamResult<()> { |
| 332 | Ok(()) |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | // essentially do the inverse of the "conversation function" |
| 337 | fn dummy_pam(msgs: &[PamMessage], talkie: &pam_conv) -> Vec<Option<String>> { |
| 338 | let pam_msgs = msgs |
| 339 | .iter() |
| 340 | .map(|PamMessage { msg, style, .. }| pam_message { |
| 341 | msg: std::ffi::CString::new(&msg[..]).unwrap().into_raw(), |
| 342 | msg_style: *style as i32, |
| 343 | }) |
| 344 | .rev() |
| 345 | .collect::<Vec<pam_message>>(); |
| 346 | let mut ptrs = pam_msgs |
| 347 | .iter() |
| 348 | .map(|x| x as *const pam_message) |
| 349 | .rev() |
| 350 | .collect::<Vec<*const pam_message>>(); |
| 351 | |
| 352 | let mut raw_response = std::ptr::null_mut::<pam_response>(); |
| 353 | let conv_err = unsafe { |
| 354 | talkie.conv.expect("non-null fn ptr")( |
| 355 | ptrs.len() as i32, |
| 356 | ptrs.as_mut_ptr(), |
| 357 | &mut raw_response, |
| 358 | talkie.appdata_ptr, |
| 359 | ) |
| 360 | }; |
| 361 | |
| 362 | // deallocate the leaky strings |
| 363 | for rec in ptrs { |
| 364 | unsafe { |
| 365 | drop(std::ffi::CString::from_raw((*rec).msg as *mut _)); |
| 366 | } |
| 367 | } |
| 368 | if conv_err != 0 { |
| 369 | return vec![]; |
| 370 | } |
| 371 | |
| 372 | let result = msgs |
| 373 | .iter() |
| 374 | .enumerate() |
| 375 | .map(|(i, _)| unsafe { |
| 376 | let ptr = raw_response.add(i); |
| 377 | if (*ptr).resp.is_null() { |
| 378 | None |
| 379 | } else { |
| 380 | // "The resp_retcode member of this struct is unused and should be set to zero." |
| 381 | assert_eq!((*ptr).resp_retcode, 0); |
| 382 | let response = string_from_ptr((*ptr).resp); |
| 383 | libc::free((*ptr).resp as *mut _); |
| 384 | Some(response) |
| 385 | } |
| 386 | }) |
| 387 | .collect(); |
| 388 | |
| 389 | unsafe { libc::free(raw_response as *mut _) }; |
| 390 | result |
| 391 | } |
| 392 | |
| 393 | fn msg(style: PamMessageStyle, msg: &str) -> PamMessage { |
| 394 | let msg = msg.to_string(); |
| 395 | PamMessage { style, msg } |
| 396 | } |
| 397 | |
| 398 | // sanity check on the test cases; lib.rs is expected to manage the lifetime of the pointer |
| 399 | // inside the pam_conv object explicitly. |
| 400 | |
| 401 | use std::marker::PhantomData; |
| 402 | struct PamConvBorrow<'a> { |
| 403 | pam_conv: pam_conv, |
| 404 | _marker: std::marker::PhantomData<&'a ()>, |
| 405 | } |
| 406 | |
| 407 | impl<'a> PamConvBorrow<'a> { |
| 408 | fn new<C: Converser>(data: Pin<&'a mut ConverserData<C>>) -> PamConvBorrow<'a> { |
| 409 | let appdata_ptr = |
| 410 | unsafe { data.get_unchecked_mut() as *mut ConverserData<C> as *mut c_void }; |
| 411 | PamConvBorrow { |
| 412 | pam_conv: pam_conv { |
| 413 | conv: Some(converse::<C>), |
| 414 | appdata_ptr, |
| 415 | }, |
| 416 | _marker: PhantomData, |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | fn borrow(&self) -> &pam_conv { |
| 421 | &self.pam_conv |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | #[test] |
| 426 | fn miri_pam_gpt() { |
| 427 | let mut hello = Box::pin(ConverserData { |
| 428 | converser: "tux".to_string(), |
| 429 | converser_name: "tux".to_string(), |
| 430 | no_interact: false, |
| 431 | auth_prompt: Some("authenticate".to_owned()), |
| 432 | error: None, |
| 433 | panicked: false, |
| 434 | }); |
| 435 | let cookie = PamConvBorrow::new(hello.as_mut()); |
| 436 | let pam_conv = cookie.borrow(); |
| 437 | |
| 438 | assert_eq!(dummy_pam(&[], pam_conv), vec![]); |
| 439 | |
| 440 | assert_eq!( |
| 441 | dummy_pam(&[msg(PromptEchoOn, "hello")], pam_conv), |
| 442 | vec![Some("tux says hello".to_string())] |
| 443 | ); |
| 444 | |
| 445 | assert_eq!( |
| 446 | dummy_pam(&[msg(PromptEchoOff, "fish")], pam_conv), |
| 447 | vec![Some("[tux: authenticate] fish".to_string())] |
| 448 | ); |
| 449 | |
| 450 | assert_eq!(dummy_pam(&[msg(TextInfo, "mars")], pam_conv), vec![None]); |
| 451 | |
| 452 | assert_eq!( |
| 453 | dummy_pam( |
| 454 | &[ |
| 455 | msg(PromptEchoOff, "banging the rocks together"), |
| 456 | msg(TextInfo, ""), |
| 457 | msg(PromptEchoOn, ""), |
| 458 | ], |
| 459 | pam_conv |
| 460 | ), |
| 461 | vec![ |
| 462 | Some("[tux: authenticate] banging the rocks together".to_string()), |
| 463 | None, |
| 464 | Some("tux says ".to_string()), |
| 465 | ] |
| 466 | ); |
| 467 | |
| 468 | //assert!(!hello.panicked); // not allowed by borrow checker |
| 469 | let real_hello = unsafe { &mut *(pam_conv.appdata_ptr as *mut ConverserData<String>) }; |
| 470 | assert!(!real_hello.panicked); |
| 471 | |
| 472 | assert_eq!(dummy_pam(&[msg(ErrorMessage, "oops")], pam_conv), vec![]); |
| 473 | |
| 474 | assert!(hello.panicked); // allowed now |
| 475 | } |
| 476 | } |