| 1 | use std::{ |
| 2 | ffi::{CStr, CString, OsStr, OsString, c_int, c_void}, |
| 3 | io, |
| 4 | os::raw::c_char, |
| 5 | os::unix::prelude::OsStrExt, |
| 6 | ptr::NonNull, |
| 7 | time::Duration, |
| 8 | }; |
| 9 | |
| 10 | use crate::system::signal::{self, SignalSet}; |
| 11 | |
| 12 | use converse::ConverserData; |
| 13 | use error::pam_err; |
| 14 | pub use error::{PamError, PamErrorType, PamResult}; |
| 15 | use sys::*; |
| 16 | |
| 17 | mod askpass; |
| 18 | mod converse; |
| 19 | mod error; |
| 20 | mod rpassword; |
| 21 | mod securemem; |
| 22 | |
| 23 | #[cfg_attr(target_os = "linux", path = "sys_linuxpam.rs")] |
| 24 | #[cfg_attr(target_os = "freebsd", path = "sys_openpam.rs")] |
| 25 | #[allow(nonstandard_style)] |
| 26 | pub mod sys; |
| 27 | |
| 28 | #[link(name = "pam")] |
| 29 | unsafe extern "C" {} |
| 30 | |
| 31 | #[cfg(target_os = "freebsd")] |
| 32 | const PAM_DATA_SILENT: std::ffi::c_int = 0; |
| 33 | |
| 34 | pub use converse::CLIConverser; |
| 35 | |
| 36 | pub struct PamContext { |
| 37 | data_ptr: *mut ConverserData<CLIConverser>, |
| 38 | pamh: *mut pam_handle_t, |
| 39 | silent: bool, |
| 40 | allow_null_auth_token: bool, |
| 41 | last_pam_status: Option<c_int>, |
| 42 | session_started: bool, |
| 43 | } |
| 44 | |
| 45 | impl PamContext { |
| 46 | /// Build the PamContext with the CLI conversation function. |
| 47 | /// |
| 48 | /// The target user is optional and may also be set after the context was |
| 49 | /// constructed or not set at all in which case PAM will ask for a |
| 50 | /// username. |
| 51 | /// |
| 52 | /// This function will error when initialization of the PAM session somehow failed. |
| 53 | #[allow(clippy::too_many_arguments)] |
| 54 | pub fn new_cli( |
| 55 | converser_name: &str, |
| 56 | service_name: &str, |
| 57 | use_askpass: bool, |
| 58 | use_stdin: bool, |
| 59 | bell: bool, |
| 60 | no_interact: bool, |
| 61 | password_feedback: bool, |
| 62 | password_timeout: Option<Duration>, |
| 63 | target_user: Option<&str>, |
| 64 | ) -> PamResult<PamContext> { |
| 65 | let converser = CLIConverser { |
| 66 | bell: bell.into(), |
| 67 | name: converser_name.to_owned(), |
| 68 | use_askpass, |
| 69 | use_stdin, |
| 70 | password_feedback, |
| 71 | password_timeout, |
| 72 | }; |
| 73 | |
| 74 | let c_service_name = CString::new(service_name)?; |
| 75 | let c_user = target_user.map(CString::new).transpose()?; |
| 76 | let c_user_ptr = match c_user { |
| 77 | Some(ref c) => c.as_ptr(), |
| 78 | None => std::ptr::null(), |
| 79 | }; |
| 80 | |
| 81 | // this will be de-allocated explicitly in this type's drop method |
| 82 | let data_ptr = Box::into_raw(Box::new(ConverserData { |
| 83 | converser, |
| 84 | converser_name: converser_name.to_owned(), |
| 85 | no_interact, |
| 86 | auth_prompt: Some(xlat!("authenticate").to_owned()), |
| 87 | error: None, |
| 88 | panicked: false, |
| 89 | })); |
| 90 | |
| 91 | let mut pamh = std::ptr::null_mut(); |
| 92 | // SAFETY: we are passing the required fields to `pam_start`; in particular, the value |
| 93 | // of `pamh` set above is not used, but will be overwritten by `pam_start`. |
| 94 | let res = unsafe { |
| 95 | pam_start( |
| 96 | c_service_name.as_ptr(), |
| 97 | c_user_ptr, |
| 98 | &pam_conv { |
| 99 | conv: Some(converse::converse::<CLIConverser>), |
| 100 | appdata_ptr: data_ptr as *mut c_void, |
| 101 | }, |
| 102 | &mut pamh, |
| 103 | ) |
| 104 | }; |
| 105 | |
| 106 | pam_err(res)?; |
| 107 | |
| 108 | assert!(!pamh.is_null()); |
| 109 | |
| 110 | Ok(PamContext { |
| 111 | data_ptr, |
| 112 | pamh, |
| 113 | silent: false, |
| 114 | allow_null_auth_token: true, |
| 115 | last_pam_status: None, |
| 116 | session_started: false, |
| 117 | }) |
| 118 | } |
| 119 | |
| 120 | pub fn set_auth_prompt(&mut self, prompt: Option<String>) { |
| 121 | // SAFETY: self.data_ptr was created by Box::into_raw |
| 122 | unsafe { |
| 123 | (*self.data_ptr).auth_prompt = prompt; |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | /// Set whether output of pam calls should be silent or not, by default |
| 128 | /// PAM calls are not silent. |
| 129 | pub fn mark_silent(&mut self, silent: bool) { |
| 130 | self.silent = silent; |
| 131 | } |
| 132 | |
| 133 | /// Set whether or not to allow empty authentication tokens, by default such |
| 134 | /// tokens are allowed. |
| 135 | pub fn mark_allow_null_auth_token(&mut self, allow: bool) { |
| 136 | self.allow_null_auth_token = allow; |
| 137 | } |
| 138 | |
| 139 | /// Get the PAM flag value for the silent flag |
| 140 | fn silent_flag(&self) -> i32 { |
| 141 | if self.silent { PAM_SILENT as _ } else { 0 } |
| 142 | } |
| 143 | |
| 144 | /// Get the PAM flag value for the disallow_null_authtok flag |
| 145 | fn disallow_null_auth_token_flag(&self) -> i32 { |
| 146 | if self.allow_null_auth_token { |
| 147 | 0 |
| 148 | } else { |
| 149 | PAM_DISALLOW_NULL_AUTHTOK as _ |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | /// Run authentication for the account |
| 154 | pub fn authenticate(&mut self, for_user: &str) -> PamResult<()> { |
| 155 | let mut flags = 0; |
| 156 | flags |= self.silent_flag(); |
| 157 | flags |= self.disallow_null_auth_token_flag(); |
| 158 | |
| 159 | // Temporarily mask SIGINT and SIGQUIT. |
| 160 | let cur_signals = SignalSet::empty().and_then(|mut set| { |
| 161 | set.add(signal::consts::SIGINT)?; |
| 162 | set.add(signal::consts::SIGQUIT)?; |
| 163 | set.block() |
| 164 | }); |
| 165 | |
| 166 | // SAFETY: `self.pamh` contains a correct handle (obtained from `pam_start`) |
| 167 | let auth_res = pam_err(unsafe { pam_authenticate(self.pamh, flags) }); |
| 168 | |
| 169 | // Restore signals |
| 170 | if let Ok(set) = cur_signals { |
| 171 | set.set_mask().map_err(PamError::IoError)?; |
| 172 | } |
| 173 | |
| 174 | if self.has_panicked() { |
| 175 | panic!("Panic during pam authentication"); |
| 176 | } |
| 177 | |
| 178 | // SAFETY: self.data_ptr was created by Box::into_raw |
| 179 | if let Some(error) = unsafe { (*self.data_ptr).error.take() } { |
| 180 | return Err(error); |
| 181 | } |
| 182 | |
| 183 | #[allow(clippy::question_mark)] |
| 184 | if let Err(err) = auth_res { |
| 185 | return Err(err); |
| 186 | } |
| 187 | |
| 188 | // Check that no PAM module changed the user. |
| 189 | match self.get_user() { |
| 190 | Ok(pam_user) => { |
| 191 | if pam_user != for_user { |
| 192 | return Err(PamError::InvalidUser(pam_user, for_user.to_string())); |
| 193 | } |
| 194 | } |
| 195 | Err(e) => { |
| 196 | return Err(e); |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | Ok(()) |
| 201 | } |
| 202 | |
| 203 | /// Check that the account is valid |
| 204 | pub fn validate_account(&mut self) -> PamResult<()> { |
| 205 | let mut flags = 0; |
| 206 | flags |= self.silent_flag(); |
| 207 | flags |= self.disallow_null_auth_token_flag(); |
| 208 | |
| 209 | // SAFETY: `self.pamh` contains a correct handle (obtained from `pam_start`) |
| 210 | pam_err(unsafe { pam_acct_mgmt(self.pamh, flags) }) |
| 211 | } |
| 212 | |
| 213 | /// Attempt to validate the account, if that fails because the authentication |
| 214 | /// token is outdated, then an update of the authentication token is requested. |
| 215 | pub fn validate_account_or_change_auth_token(&mut self) -> PamResult<()> { |
| 216 | let check_val = self.validate_account(); |
| 217 | match check_val { |
| 218 | Ok(()) => Ok(()), |
| 219 | Err(PamError::Pam(PamErrorType::NewAuthTokenRequired)) => { |
| 220 | self.change_auth_token(true)?; |
| 221 | Ok(()) |
| 222 | } |
| 223 | Err(e) => Err(e), |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | /// Set the user that will be authenticated. |
| 228 | pub fn set_user(&mut self, user: &str) -> PamResult<()> { |
| 229 | let c_user = CString::new(user)?; |
| 230 | // SAFETY: `self.pamh` contains a correct handle (obtained from `pam_start`); furthermore, |
| 231 | // `c_user.as_ptr()` will point to a correct null-terminated string. |
| 232 | pam_err(unsafe { pam_set_item(self.pamh, PAM_USER as _, c_user.as_ptr() as *const c_void) }) |
| 233 | } |
| 234 | |
| 235 | /// Get the user that is currently active in the PAM handle |
| 236 | pub fn get_user(&mut self) -> PamResult<String> { |
| 237 | let mut data = std::ptr::null(); |
| 238 | // SAFETY: `self.pamh` contains a correct handle (obtained from `pam_start`) |
| 239 | pam_err(unsafe { pam_get_item(self.pamh, PAM_USER as _, &mut data) })?; |
| 240 | |
| 241 | // safety check to make sure that we were not passed a null pointer by PAM, |
| 242 | // or that in fact PAM did not write to `data` at all. |
| 243 | if data.is_null() { |
| 244 | return Err(PamError::IoError(io::Error::new( |
| 245 | io::ErrorKind::InvalidData, |
| 246 | "PAM didn't return username", |
| 247 | ))); |
| 248 | } |
| 249 | |
| 250 | // SAFETY: the contract for `pam_get_item` ensures that if `data` was touched by |
| 251 | // `pam_get_item`, it will point to a valid null-terminated string. |
| 252 | let cstr = unsafe { CStr::from_ptr(data as *const c_char) }; |
| 253 | |
| 254 | Ok(cstr.to_str()?.to_owned()) |
| 255 | } |
| 256 | |
| 257 | /// Set the TTY path for the current TTY that this PAM session started from. |
| 258 | pub fn set_tty<P: AsRef<OsStr>>(&mut self, tty_path: P) -> PamResult<()> { |
| 259 | let data = CString::new(tty_path.as_ref().as_bytes())?; |
| 260 | // SAFETY: `self.pamh` contains a correct handle (obtained from `pam_start`); furthermore, |
| 261 | // `data.as_ptr()` will point to a correct null-terminated string. |
| 262 | pam_err(unsafe { pam_set_item(self.pamh, PAM_TTY as _, data.as_ptr() as *const c_void) }) |
| 263 | } |
| 264 | |
| 265 | // Set the user that requested the actions in this PAM instance. |
| 266 | pub fn set_requesting_user(&mut self, user: &str) -> PamResult<()> { |
| 267 | let data = CString::new(user.as_bytes())?; |
| 268 | // SAFETY: `self.pamh` contains a correct handle (obtained from `pam_start`); furthermore, |
| 269 | // `data.as_ptr()` will point to a correct null-terminated string. |
| 270 | pam_err(unsafe { pam_set_item(self.pamh, PAM_RUSER as _, data.as_ptr() as *const c_void) }) |
| 271 | } |
| 272 | |
| 273 | /// Re-initialize the credentials stored in PAM |
| 274 | pub fn credentials_reinitialize(&mut self) -> PamResult<()> { |
| 275 | self.credentials(PAM_REINITIALIZE_CRED as c_int) |
| 276 | } |
| 277 | |
| 278 | /// Updates to the credentials stored in PAM |
| 279 | fn credentials(&mut self, action: c_int) -> PamResult<()> { |
| 280 | let mut flags = action; |
| 281 | flags |= self.silent_flag(); |
| 282 | |
| 283 | // SAFETY: `self.pamh` contains a correct handle (obtained from `pam_start`). |
| 284 | pam_err(unsafe { pam_setcred(self.pamh, flags) }) |
| 285 | } |
| 286 | |
| 287 | /// Ask the user to change the authentication token (password). |
| 288 | /// |
| 289 | /// If `expired_only` is set to true, only expired authentication tokens |
| 290 | /// will be asked to be replaced, otherwise a replacement will always be |
| 291 | /// requested. |
| 292 | pub fn change_auth_token(&mut self, expired_only: bool) -> PamResult<()> { |
| 293 | let mut flags = 0; |
| 294 | flags |= self.silent_flag(); |
| 295 | if expired_only { |
| 296 | flags |= PAM_CHANGE_EXPIRED_AUTHTOK as c_int; |
| 297 | } |
| 298 | // SAFETY: `self.pamh` contains a correct handle (obtained from `pam_start`). |
| 299 | pam_err(unsafe { pam_chauthtok(self.pamh, flags) }) |
| 300 | } |
| 301 | |
| 302 | /// Start a user session for the authenticated user. |
| 303 | pub fn open_session(&mut self) -> PamResult<()> { |
| 304 | assert!(!self.session_started); |
| 305 | |
| 306 | // SAFETY: `self.pamh` contains a correct handle (obtained from `pam_start`). |
| 307 | pam_err(unsafe { pam_open_session(self.pamh, self.silent_flag()) })?; |
| 308 | self.session_started = true; |
| 309 | Ok(()) |
| 310 | } |
| 311 | |
| 312 | /// End the user session. |
| 313 | pub fn close_session(&mut self) { |
| 314 | // closing the pam session is best effort, if any error occurs we cannot |
| 315 | // do anything with it |
| 316 | if self.session_started { |
| 317 | // SAFETY: `self.pamh` contains a correct handle (obtained from `pam_start`). |
| 318 | let _ = pam_err(unsafe { pam_close_session(self.pamh, self.silent_flag()) }); |
| 319 | self.session_started = false; |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | /// Get a full listing of the current PAM environment |
| 324 | pub fn env(&mut self) -> PamResult<Vec<(OsString, OsString)>> { |
| 325 | let mut res = Vec::new(); |
| 326 | // SAFETY: `self.pamh` contains a correct handle (obtained from `pam_start`). |
| 327 | // The man page for pam_getenvlist states that: |
| 328 | // The format of the memory is a malloc()'d array of char pointers, the last element |
| 329 | // of which is set to NULL. Each of the non-NULL entries in this array point to a |
| 330 | // NUL terminated and malloc()'d char string of the form: "name=value". |
| 331 | // |
| 332 | // The pam_getenvlist function returns NULL on failure. |
| 333 | let envs = unsafe { pam_getenvlist(self.pamh) }; |
| 334 | if envs.is_null() { |
| 335 | return Err(PamError::EnvListFailure); |
| 336 | } |
| 337 | let mut curr_env = envs; |
| 338 | // SAFETY: the loop invariant is as follows: |
| 339 | // - `curr_env` itself is always a valid pointer to an array of valid (possibly NULL) pointers |
| 340 | // - if `curr_env` points to a pointer that is not-null, that data is a c-string allocated by malloc() |
| 341 | // - `curr_env` points to NULL if and only if it is the final element in the array |
| 342 | while let Some(curr_str) = NonNull::new(unsafe { curr_env.read() }) { |
| 343 | let data = { |
| 344 | // SAFETY: `curr_str` points to a valid null-terminated string per the above |
| 345 | let cstr = unsafe { CStr::from_ptr(curr_str.as_ptr()) }; |
| 346 | let bytes = cstr.to_bytes(); |
| 347 | if let Some(pos) = bytes.iter().position(|b| *b == b'=') { |
| 348 | let key = OsStr::from_bytes(&bytes[..pos]).to_owned(); |
| 349 | let value = OsStr::from_bytes(&bytes[pos + 1..]).to_owned(); |
| 350 | Some((key, value)) |
| 351 | } else { |
| 352 | None |
| 353 | } |
| 354 | }; |
| 355 | if let Some((k, v)) = data { |
| 356 | res.push((k, v)); |
| 357 | } |
| 358 | |
| 359 | // SAFETY: curr_str was obtained via libc::malloc() so we are responsible for freeing it. |
| 360 | // At this point, curr_str is also the only remaining pointer/reference to that allocated data |
| 361 | // (the data was copied above), so it can be deallocated without risk of use-after-free errors. |
| 362 | unsafe { libc::free(curr_str.as_ptr().cast()) }; |
| 363 | // SAFETY: curr_env was not NULL, so it was not the last element in the list and so PAM |
| 364 | // ensures that the next offset also is a valid pointer, and points to valid data. |
| 365 | curr_env = unsafe { curr_env.offset(1) }; |
| 366 | } |
| 367 | |
| 368 | // SAFETY: `envs` itself was obtained by malloc(), so we are responsible for freeing it. |
| 369 | unsafe { libc::free(envs.cast()) }; |
| 370 | |
| 371 | Ok(res) |
| 372 | } |
| 373 | |
| 374 | /// Check if anything panicked since the last call. |
| 375 | pub fn has_panicked(&self) -> bool { |
| 376 | // SAFETY: self.data_ptr was created by Box::into_raw |
| 377 | unsafe { (*self.data_ptr).panicked } |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | impl Drop for PamContext { |
| 382 | fn drop(&mut self) { |
| 383 | // data_ptr's pointee is de-allocated in this scope |
| 384 | // SAFETY: self.data_ptr was created by Box::into_raw |
| 385 | let _data = unsafe { Box::from_raw(self.data_ptr) }; |
| 386 | self.close_session(); |
| 387 | |
| 388 | // It looks like PAM_DATA_SILENT is important to set for our sudo context, but |
| 389 | // it is unclear what it really does and does not do, other than the vague |
| 390 | // documentation description to 'not take the call to seriously' |
| 391 | // Also see https://github.com/systemd/systemd/issues/22318 |
| 392 | // SAFETY: `self.pamh` contains a correct handle (obtained from `pam_start`) |
| 393 | unsafe { |
| 394 | pam_end( |
| 395 | self.pamh, |
| 396 | self.last_pam_status.unwrap_or(PAM_SUCCESS as c_int) | PAM_DATA_SILENT as c_int, |
| 397 | ) |
| 398 | }; |
| 399 | } |
| 400 | } |