# HG changeset patch # User Paul Fisher # Date 1749368920 14400 # Node ID 002adfb98c5c219c426086d22230c801018ace91 # Parent 351bdc13005e8fd9b2988f2cb85f40faead47d6f Rename files, reorder structs, remove annoying BorrowedBinaryData type. This is basically a cleanup change. Also it adds tests. - Renames the files with Questions and Answers to question and answer. - Reorders the structs in those files to put the important ones first. - Removes the BorrowedBinaryData type. It was a bad idea all along. Instead, we just use (&[u8], u8). - Adds some tests because I just can't help myself. diff -r 351bdc13005e -r 002adfb98c5c src/conv.rs --- a/src/conv.rs Sun Jun 08 01:03:46 2025 -0400 +++ b/src/conv.rs Sun Jun 08 03:48:40 2025 -0400 @@ -3,10 +3,11 @@ // Temporarily allowed until we get the actual conversation functions hooked up. #![allow(dead_code)] -use crate::constants::Result; -use crate::ErrorCode; +use crate::constants::{ErrorCode, Result}; use secure_string::SecureString; use std::cell::Cell; +use std::fmt; +use std::result::Result as StdResult; /// The types of message and request that can be sent to a user. /// @@ -68,8 +69,16 @@ } impl<'a> $name<'a> { + #[doc = concat!("Creates a `", stringify!($t), "` to be sent to the user.")] + pub fn new(question: $qt) -> Self { + Self { + q: question, + a: Cell::new(Err(ErrorCode::ConversationError)), + } + } + /// Converts this Q&A into a [`Message`] for the [`Conversation`]. - pub fn message(&self) -> Message { + pub fn message(&self) -> Message<'_> { $val(self) } @@ -96,18 +105,14 @@ self.a.into_inner() } } - }; -} -macro_rules! ask { - ($t:ident) => { - impl<'a> $t<'a> { - #[doc = concat!("Creates a `", stringify!($t), "` to be sent to the user.")] - pub fn new(question: &'a str) -> Self { - Self { - q: question, - a: Cell::new(Err(ErrorCode::ConversationError)), - } + // shout out to stackoverflow user ballpointben for this lazy impl: + // https://stackoverflow.com/a/78871280/39808 + impl fmt::Debug for $name<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> StdResult<(), fmt::Error> { + #[derive(Debug)] + struct $name<'a> { q: $qt } + fmt::Debug::fmt(&$name { q: self.q }, f) } } }; @@ -120,7 +125,6 @@ "" "In other words, a password entry prompt." ); -ask!(MaskedQAndA); q_and_a!( QAndA<'a, Q=&'a str, A=String>, @@ -131,7 +135,6 @@ "When the user types, their input will be shown to them." "It can be used for things like usernames." ); -ask!(QAndA); q_and_a!( RadioQAndA<'a, Q=&'a str, A=String>, @@ -142,10 +145,9 @@ "questions, but nowhere in the documentation is it specified" "what the format of the answer will be, or how this should be shown." ); -ask!(RadioQAndA); q_and_a!( - BinaryQAndA<'a, Q=BorrowedBinaryData<'a>, A=BinaryData>, + BinaryQAndA<'a, Q=(&'a [u8], u8), A=BinaryData>, Message::BinaryPrompt, "Asks for binary data. (Linux-PAM extension)" "" @@ -156,65 +158,16 @@ "The `data_type` tag is a value that is simply passed through" "to the application. PAM does not define any meaning for it." ); -impl<'a> BinaryQAndA<'a> { - /// Creates a prompt for the given binary data. - /// - /// The `data_type` is a tag you can use for communication between - /// the module and the application. Its meaning is undefined by PAM. - pub fn new(data: &'a [u8], data_type: u8) -> Self { - BorrowedBinaryData { data, data_type }.into() - } -} - -impl<'a> From> for BinaryQAndA<'a> { - fn from(q: BorrowedBinaryData<'a>) -> Self { - Self { - q, - a: Cell::new(Err(ErrorCode::ConversationError)), - } - } -} - -impl<'a> From<&'a BinaryData> for BinaryQAndA<'a> { - fn from(src: &'a BinaryData) -> Self { - BorrowedBinaryData::from(src).into() - } -} - -/// A version of [`BinaryData`] where the `data` is borrowed. -#[derive(Copy, Clone, Debug, Default)] -pub struct BorrowedBinaryData<'a> { - data: &'a [u8], - data_type: u8, -} - -impl<'a> BorrowedBinaryData<'a> { - /// Creates a new BinaryQuestion as a view over the given data. - pub fn new(data: &'a [u8], data_type: u8) -> Self { - Self { data, data_type } - } - - /// Gets the data of this question. - pub fn data(&self) -> &[u8] { - self.data - } - - /// Gets the "type" of this data. - pub fn data_type(&self) -> u8 { - self.data_type - } -} - -impl<'a> From<&'a BinaryData> for BorrowedBinaryData<'a> { - fn from(value: &'a BinaryData) -> Self { - Self::new(&value.data, value.data_type) - } -} /// Owned binary data. /// -/// For borrowed data, see [`BorrowedBinaryData`]. -/// You can take ownership of the stored data with `.into::>()`. +/// You can take ownership of the stored data by destructuring it: +/// +/// ``` +/// # use nonstick::BinaryData; +/// # let binary_data = BinaryData::new(vec![99, 88, 77], 66); +/// let (data, data_type) = binary_data.into(); +/// ``` #[derive(Debug, Default, PartialEq)] pub struct BinaryData { data: Vec, @@ -223,28 +176,32 @@ impl BinaryData { /// Creates a `BinaryData` with the given contents and type. - pub fn new(data: Vec, data_type: u8) -> Self { - Self { data, data_type } + pub fn new(data: impl Into>, data_type: u8) -> Self { + Self { data: data.into(), data_type } } - /// A borrowed view of the data here. - pub fn data(&self) -> &[u8] { - &self.data - } - /// The type of the data stored in this. - pub fn data_type(&self) -> u8 { - self.data_type +} + +impl From for (Vec, u8) { + fn from(value: BinaryData) -> Self { + (value.data, value.data_type) } } -impl<'a> From> for BinaryData { - fn from(value: BorrowedBinaryData) -> Self { +impl From<(&'_[u8], u8)> for BinaryData { + fn from((data, data_type): (&'_[u8], u8)) -> Self { Self { - data: value.data.to_vec(), - data_type: value.data_type, + data: data.to_vec(), + data_type, } } } +impl<'a> From<&'a BinaryData> for (&'a[u8], u8) { + fn from(value: &'a BinaryData) -> Self { + (&value.data, value.data_type) + } +} + impl From for Vec { /// Takes ownership of the data stored herein. fn from(value: BinaryData) -> Self { @@ -261,15 +218,6 @@ "should still call [`set_answer`][`QAndA::set_answer`] to verify that" "the message has been displayed (or actively discarded)." ); -impl<'a> InfoMsg<'a> { - /// Creates an informational message to send to the user. - pub fn new(message: &'a str) -> Self { - Self { - q: message, - a: Cell::new(Err(ErrorCode::ConversationError)), - } - } -} q_and_a!( ErrorMsg<'a, Q = &'a str, A = ()>, @@ -279,17 +227,7 @@ "While this does not have an answer, [`Conversation`] implementations" "should still call [`set_answer`][`QAndA::set_answer`] to verify that" "the message has been displayed (or actively discarded)." - ); -impl<'a> ErrorMsg<'a> { - /// Creates an error message to send to the user. - pub fn new(message: &'a str) -> Self { - Self { - q: message, - a: Cell::new(Err(ErrorCode::ConversationError)), - } - } -} /// A channel for PAM modules to request information from the user. /// @@ -315,10 +253,12 @@ /// Conversation: /// /// ``` -/// use nonstick::conv::{Conversation, Message, conversation_func}; +/// use nonstick::conv::{conversation_func, Conversation, Message}; /// mod some_library { /// # use nonstick::Conversation; -/// pub fn get_auth_data(conv: &mut impl Conversation) { /* ... */ } +/// pub fn get_auth_data(conv: &mut impl Conversation) { +/// /* ... */ +/// } /// } /// /// fn my_terminal_prompt(messages: &[Message]) { @@ -364,15 +304,16 @@ /// or to use a `SimpleConversation` as a `Conversation`: /// /// ``` +/// use nonstick::{Conversation, SimpleConversation}; /// use secure_string::SecureString; -/// use nonstick::{Conversation, SimpleConversation}; /// # use nonstick::{BinaryData, Result}; /// mod some_library { /// # use nonstick::Conversation; -/// pub fn get_auth_data(conv: &mut impl Conversation) { /* ... */ } +/// pub fn get_auth_data(conv: &mut impl Conversation) { /* ... */ +/// } /// } /// -/// struct MySimpleConvo { /* ... */ } +/// struct MySimpleConvo {/* ... */} /// # impl MySimpleConvo { fn new() -> Self { Self{} } } /// /// impl SimpleConversation for MySimpleConvo { @@ -397,7 +338,7 @@ /// # todo!() /// # } /// # -/// # fn binary_prompt(&mut self, data: &[u8], data_type: u8) -> Result { +/// # fn binary_prompt(&mut self, (data, data_type): (&[u8], u8)) -> Result { /// # todo!() /// # } /// } @@ -413,7 +354,7 @@ /// The wrapper takes each message received in [`Conversation::communicate`] /// and passes them one-by-one to the appropriate method, /// then collects responses to return. - fn as_conversation(&mut self) -> Demux + fn as_conversation(&mut self) -> Demux<'_, Self> where Self: Sized, { @@ -432,18 +373,18 @@ /// Sends an informational message to the user. fn info_msg(&mut self, message: &str); /// Requests binary data from the user (a Linux-PAM extension). - fn binary_prompt(&mut self, data: &[u8], data_type: u8) -> Result; + fn binary_prompt(&mut self, data_and_type: (&[u8], u8)) -> Result; } macro_rules! conv_fn { - ($fn_name:ident($($param:ident: $pt:ty),+) -> $resp_type:ty { $msg:ty }) => { + ($fn_name:ident($($param:tt: $pt:ty),+) -> $resp_type:ty { $msg:ty }) => { fn $fn_name(&mut self, $($param: $pt),*) -> Result<$resp_type> { let prompt = <$msg>::new($($param),*); self.communicate(&[prompt.message()]); prompt.answer() } }; - ($fn_name:ident($($param:ident: $pt:ty),+) { $msg:ty }) => { + ($fn_name:ident($($param:tt: $pt:ty),+) { $msg:ty }) => { fn $fn_name(&mut self, $($param: $pt),*) { self.communicate(&[<$msg>::new($($param),*).message()]); } @@ -456,7 +397,7 @@ conv_fn!(radio_prompt(message: &str) -> String { RadioQAndA }); conv_fn!(error_msg(message: &str) { ErrorMsg }); conv_fn!(info_msg(message: &str) { InfoMsg }); - conv_fn!(binary_prompt(data: &[u8], data_type: u8) -> BinaryData { BinaryQAndA }); + conv_fn!(binary_prompt((data, data_type): (&[u8], u8)) -> BinaryData { BinaryQAndA }); } /// A [`Conversation`] which asks the questions one at a time. @@ -485,7 +426,7 @@ } Message::BinaryPrompt(prompt) => { let q = prompt.question(); - prompt.set_answer(self.0.binary_prompt(q.data, q.data_type)) + prompt.set_answer(self.0.binary_prompt(q)) } } } @@ -495,8 +436,8 @@ #[cfg(test)] mod tests { use super::{ - BinaryQAndA, Conversation, ErrorMsg, InfoMsg, MaskedQAndA, Message, QAndA, - RadioQAndA, Result, SecureString, SimpleConversation, + BinaryQAndA, Conversation, ErrorMsg, InfoMsg, MaskedQAndA, Message, QAndA, RadioQAndA, + Result, SecureString, SimpleConversation, }; use crate::constants::ErrorCode; use crate::BinaryData; @@ -533,9 +474,8 @@ self.info_ran = true; assert_eq!("did you know", message); } - fn binary_prompt(&mut self, data: &[u8], data_type: u8) -> Result { - assert_eq!(&[10, 9, 8], data); - assert_eq!(66, data_type); + fn binary_prompt(&mut self, data_and_type: (&[u8], u8)) -> Result { + assert_eq!((&[10, 9, 8][..], 66), data_and_type); Ok(BinaryData::new(vec![5, 5, 5], 5)) } } @@ -573,7 +513,7 @@ let mut conv = tester.as_conversation(); let radio = RadioQAndA::new("channel?"); - let bin = BinaryQAndA::new(&[10, 9, 8], 66); + let bin = BinaryQAndA::new((&[10, 9, 8], 66)); conv.communicate(&[radio.message(), bin.message()]); assert_eq!("zero", radio.answer().unwrap()); @@ -605,8 +545,7 @@ ask.set_answer(Ok("open sesame".into())) } Message::BinaryPrompt(prompt) => { - assert_eq!(&[1, 2, 3], prompt.question().data); - assert_eq!(69, prompt.question().data_type); + assert_eq!((&[1, 2, 3][..], 69), prompt.question()); prompt.set_answer(Ok(BinaryData::new(vec![3, 2, 1], 42))) } Message::RadioPrompt(ask) => { @@ -636,7 +575,7 @@ assert_eq!("yes", tester.radio_prompt("radio?").unwrap()); assert_eq!( BinaryData::new(vec![3, 2, 1], 42), - tester.binary_prompt(&[1, 2, 3], 69).unwrap(), + tester.binary_prompt((&[1, 2, 3], 69)).unwrap(), ) } assert_eq!( diff -r 351bdc13005e -r 002adfb98c5c src/handle.rs --- a/src/handle.rs Sun Jun 08 01:03:46 2025 -0400 +++ b/src/handle.rs Sun Jun 08 03:48:40 2025 -0400 @@ -209,18 +209,18 @@ trait_item!( set = set_authtok_item, item = "PAM_AUTHTOK", - see = PamModuleHandle::authtok_item, - "Sets the user's authentication token (e.g., password)." + see = PamModuleOnly::authtok_item, + "Gets the user's authentication token (e.g., password)." "" "This is usually set automatically when " - "[`get_authtok`](PamModuleHandle::get_authtok) is called, " + "[`get_authtok`](PamModuleOnly::get_authtok) is called, " "but can be manually set." ); trait_item!( set = set_old_authtok_item, item = "PAM_OLDAUTHTOK", - see = PamModuleHandle::old_authtok_item, + see = PamModuleOnly::old_authtok_item, "Sets the user's \"old authentication token\" when changing passwords." "" "This is usually set automatically by PAM." @@ -308,7 +308,7 @@ trait_item!( get = old_authtok_item, item = "PAM_OLDAUTHTOK", - see = PamHandle::set_old_authtok_item, + see = PamShared::set_old_authtok_item, "Gets the user's old authentication token when changing passwords." "" "This should only ever be called by *password-change* PAM modules." diff -r 351bdc13005e -r 002adfb98c5c src/libpam/answer.rs --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/libpam/answer.rs Sun Jun 08 03:48:40 2025 -0400 @@ -0,0 +1,333 @@ +//! Types used to communicate data from the application to the module. + +use crate::libpam::conversation::OwnedMessage; +use crate::libpam::memory; +use crate::libpam::memory::{CBinaryData, Immovable}; +use crate::{ErrorCode, Result}; +use std::ffi::{c_int, c_void, CStr}; +use std::ops::{Deref, DerefMut}; +use std::{iter, mem, ptr, slice}; + +/// The corridor via which the answer to Messages navigate through PAM. +#[derive(Debug)] +pub struct Answers { + base: *mut Answer, + count: usize, +} + +impl Answers { + /// Builds an Answers out of the given answered Message Q&As. + pub fn build(value: Vec) -> Result { + let mut outputs = Self { + base: memory::calloc(value.len()), + count: value.len(), + }; + // Even if we fail during this process, we still end up freeing + // all allocated answer memory. + for (input, output) in iter::zip(value, outputs.iter_mut()) { + match input { + OwnedMessage::MaskedPrompt(p) => TextAnswer::fill(output, p.answer()?.unsecure())?, + OwnedMessage::Prompt(p) => TextAnswer::fill(output, &(p.answer()?))?, + OwnedMessage::BinaryPrompt(p) => BinaryAnswer::fill(output, (&p.answer()?).into())?, + OwnedMessage::Error(p) => TextAnswer::fill(output, p.answer().map(|_| "")?)?, + OwnedMessage::Info(p) => TextAnswer::fill(output, p.answer().map(|_| "")?)?, + OwnedMessage::RadioPrompt(p) => TextAnswer::fill(output, &(p.answer()?))?, + } + } + Ok(outputs) + } + + /// Converts this into a `*Answer` for passing to PAM. + /// + /// This object is consumed and the `Answer` pointer now owns its data. + /// It can be recreated with [`Self::from_c_heap`]. + pub fn into_ptr(self) -> *mut Answer { + let ret = self.base; + mem::forget(self); + ret + } + + /// Takes ownership of a list of answers allocated on the C heap. + /// + /// # Safety + /// + /// It's up to you to make sure you pass a valid pointer, + /// like one that you got from PAM, or maybe [`Self::into_ptr`]. + pub unsafe fn from_c_heap(base: *mut Answer, count: usize) -> Self { + Answers { base, count } + } +} + +impl Deref for Answers { + type Target = [Answer]; + fn deref(&self) -> &Self::Target { + // SAFETY: This is the memory we manage ourselves. + unsafe { slice::from_raw_parts(self.base, self.count) } + } +} + +impl DerefMut for Answers { + fn deref_mut(&mut self) -> &mut Self::Target { + // SAFETY: This is the memory we manage ourselves. + unsafe { slice::from_raw_parts_mut(self.base, self.count) } + } +} + +impl Drop for Answers { + fn drop(&mut self) { + // SAFETY: We allocated this ourselves, or it was provided to us by PAM. + unsafe { + for answer in self.iter_mut() { + answer.free_contents() + } + memory::free(self.base) + } + } +} + +#[repr(transparent)] +#[derive(Debug)] +pub struct TextAnswer(Answer); + +impl TextAnswer { + /// Interprets the provided `Answer` as a text answer. + /// + /// # Safety + /// + /// It's up to you to provide an answer that is a `TextAnswer`. + pub unsafe fn upcast(from: &mut Answer) -> &mut Self { + // SAFETY: We're provided a valid reference. + &mut *(from as *mut Answer).cast::() + } + + /// Converts the `Answer` to a `TextAnswer` with the given text. + fn fill(dest: &mut Answer, text: &str) -> Result<()> { + let allocated = memory::malloc_str(text)?; + dest.free_contents(); + dest.data = allocated.cast(); + Ok(()) + } + + /// Gets the string stored in this answer. + pub fn contents(&self) -> Result<&str> { + if self.0.data.is_null() { + Ok("") + } else { + // SAFETY: This data is either passed from PAM (so we are forced + // to trust it) or was created by us in TextAnswerInner::alloc. + // In either case, it's going to be a valid null-terminated string. + unsafe { CStr::from_ptr(self.0.data.cast()) } + .to_str() + .map_err(|_| ErrorCode::ConversationError) + } + } + + /// Zeroes out the answer data, frees it, and points our data to `null`. + /// + /// When this `TextAnswer` is part of an [`Answers`], + /// this is optional (since that will perform the `free`), + /// but it will clear potentially sensitive data. + pub fn free_contents(&mut self) { + // SAFETY: We own this data and know it's valid. + // If it's null, this is a no-op. + // After we're done, it will be null. + unsafe { + memory::zero_c_string(self.0.data.cast()); + memory::free(self.0.data); + self.0.data = ptr::null_mut() + } + } +} + +/// A [`Answer`] with [`CBinaryData`] in it. +#[repr(transparent)] +#[derive(Debug)] +pub struct BinaryAnswer(Answer); + +impl BinaryAnswer { + /// Interprets the provided [`Answer`] as a binary answer. + /// + /// # Safety + /// + /// It's up to you to provide an answer that is a `BinaryAnswer`. + pub unsafe fn upcast(from: &mut Answer) -> &mut Self { + // SAFETY: We're provided a valid reference. + &mut *(from as *mut Answer).cast::() + } + + /// Fills in a [`Answer`] with the provided binary data. + /// + /// The `data_type` is a tag you can use for whatever. + /// It is passed through PAM unchanged. + /// + /// The referenced data is copied to the C heap. + /// We do not take ownership of the original data. + pub fn fill(dest: &mut Answer, data_and_type: (&[u8], u8)) -> Result<()> { + let allocated = CBinaryData::alloc(data_and_type)?; + dest.free_contents(); + dest.data = allocated.cast(); + Ok(()) + } + + /// Gets the binary data in this answer. + pub fn data(&self) -> Option<&CBinaryData> { + // SAFETY: We either got this data from PAM or allocated it ourselves. + // Either way, we trust that it is either valid data or null. + unsafe { self.0.data.cast::().as_ref() } + } + + /// Zeroes out the answer data, frees it, and points our data to `null`. + /// + /// When this `TextAnswer` is part of an [`Answers`], + /// this is optional (since that will perform the `free`), + /// but it will clear potentially sensitive data. + pub fn zero_contents(&mut self) { + // SAFETY: We know that our data pointer is either valid or null. + // Once we're done, it's null and the answer is safe. + unsafe { + let data_ref = self.0.data.cast::().as_mut(); + if let Some(d) = data_ref { + d.zero_contents() + } + memory::free(self.0.data); + self.0.data = ptr::null_mut() + } + } +} + +/// Generic version of answer data. +/// +/// This has the same structure as [`BinaryAnswer`] +/// and [`TextAnswer`]. +#[repr(C)] +#[derive(Debug)] +pub struct Answer { + /// Pointer to the data returned in an answer. + /// For most answers, this will be a [`CStr`], but for answers to + /// [`MessageStyle::BinaryPrompt`]s, this will be [`CBinaryData`] + /// (a Linux-PAM extension). + data: *mut c_void, + /// Unused. + return_code: c_int, + _marker: Immovable, +} + +impl Answer { + /// Frees the contents of this answer. + /// + /// After this is done, this answer's `data` will be `null`, + /// which is a valid (empty) state. + fn free_contents(&mut self) { + // SAFETY: We have either an owned valid pointer, or null. + // We can free our owned pointer, and `free(null)` is a no-op. + unsafe { + memory::free(self.data); + self.data = ptr::null_mut(); + } + } +} + +#[cfg(test)] +mod tests { + use super::{Answer, Answers, BinaryAnswer, TextAnswer}; + use crate::conv::{BinaryQAndA, ErrorMsg, InfoMsg, MaskedQAndA, QAndA, RadioQAndA}; + use crate::libpam::conversation::OwnedMessage; + use crate::BinaryData; + use crate::libpam::memory; + + #[test] + fn test_round_trip() { + let binary_msg = { + let qa = BinaryQAndA::new((&[][..], 0)); + qa.set_answer(Ok(BinaryData::new(vec![1, 2, 3], 99))); + OwnedMessage::BinaryPrompt(qa) + }; + + macro_rules! answered { + ($typ:ty, $msg:path, $data:expr) => {{ + let qa = <$typ>::new(""); + qa.set_answer(Ok($data)); + $msg(qa) + }}; + } + + let answers = vec![ + binary_msg, + answered!(QAndA, OwnedMessage::Prompt, "whats going on".to_owned()), + answered!(MaskedQAndA, OwnedMessage::MaskedPrompt, "well then".into()), + answered!(ErrorMsg, OwnedMessage::Error, ()), + answered!(InfoMsg, OwnedMessage::Info, ()), + answered!( + RadioQAndA, + OwnedMessage::RadioPrompt, + "beep boop".to_owned() + ), + ]; + let n = answers.len(); + let sent = Answers::build(answers).unwrap(); + let heap_answers = sent.into_ptr(); + let mut received = unsafe { Answers::from_c_heap(heap_answers, n) }; + + let assert_text = |want, raw| { + let up = unsafe { TextAnswer::upcast(raw) }; + assert_eq!(want, up.contents().unwrap()); + up.free_contents(); + assert_eq!("", up.contents().unwrap()); + }; + let assert_bin = |want, raw| { + let up = unsafe { BinaryAnswer::upcast(raw) }; + assert_eq!(BinaryData::from(want), up.data().into()); + up.zero_contents(); + assert_eq!(BinaryData::default(), up.data().into()); + }; + if let [zero, one, two, three, four, five] = &mut received[..] { + assert_bin((&[1, 2, 3][..], 99), zero); + assert_text("whats going on", one); + assert_text("well then", two); + assert_text("", three); + assert_text("", four); + assert_text("beep boop", five); + } else { + panic!("received wrong size {len}!", len = received.len()) + } + } + + #[test] + fn test_text_answer() { + let answer_ptr: *mut Answer = memory::calloc(1); + let answer = unsafe {&mut *answer_ptr}; + TextAnswer::fill(answer, "hello").unwrap(); + let zeroth_text = unsafe { TextAnswer::upcast(answer) }; + let data = zeroth_text.contents().expect("valid"); + assert_eq!("hello", data); + zeroth_text.free_contents(); + zeroth_text.free_contents(); + TextAnswer::fill(answer, "hell\0").expect_err("should error; contains nul"); + unsafe { memory::free(answer_ptr) } + } + + #[test] + fn test_binary_answer() { + let answer_ptr: *mut Answer = memory::calloc(1); + let answer = unsafe { &mut *answer_ptr }; + let real_data = BinaryData::new(vec![1, 2, 3, 4, 5, 6, 7, 8], 9); + BinaryAnswer::fill(answer, (&real_data).into()).expect("alloc should succeed"); + let bin_answer = unsafe { BinaryAnswer::upcast(answer) }; + assert_eq!(real_data, bin_answer.data().into()); + answer.free_contents(); + answer.free_contents(); + unsafe { memory::free(answer_ptr) } + } + + #[test] + #[ignore] + fn test_binary_answer_too_big() { + let big_data: Vec = vec![0xFFu8; 10_000_000_000]; + let answer_ptr: *mut Answer = memory::calloc(1); + let answer = unsafe {&mut*answer_ptr}; + BinaryAnswer::fill(answer, (&big_data, 100)) + .expect_err("this is too big!"); + answer.free_contents(); + unsafe { memory::free(answer) } + } +} diff -r 351bdc13005e -r 002adfb98c5c src/libpam/conversation.rs --- a/src/libpam/conversation.rs Sun Jun 08 01:03:46 2025 -0400 +++ b/src/libpam/conversation.rs Sun Jun 08 03:48:40 2025 -0400 @@ -1,10 +1,9 @@ use crate::conv::{ - BinaryQAndA, Conversation, ErrorMsg, InfoMsg, MaskedQAndA, Message, QAndA, - RadioQAndA, + BinaryQAndA, Conversation, ErrorMsg, InfoMsg, MaskedQAndA, Message, QAndA, RadioQAndA, }; +use crate::libpam::answer::{Answer, Answers, BinaryAnswer, TextAnswer}; use crate::libpam::memory::Immovable; -use crate::libpam::message::{Indirect, Questions}; -use crate::libpam::response::{Answer, Answers, BinaryAnswer, TextAnswer}; +use crate::libpam::question::{Indirect, Questions}; use crate::ErrorCode; use crate::Result; use std::ffi::c_int; @@ -76,7 +75,7 @@ // Build our owned list of Q&As from the questions we've been asked let messages: Vec = indirect .iter(count as usize) - .map(OwnedMessage::try_from) + .map(TryInto::try_into) .collect::>() .map_err(|_| ErrorCode::ConversationError)?; // Borrow all those Q&As and ask them @@ -95,16 +94,13 @@ impl Conversation for LibPamConversation<'_> { fn communicate(&mut self, messages: &[Message]) { let internal = || { - let mut msgs_to_send = Questions::alloc(messages.len()); - for (dst, src) in iter::zip(msgs_to_send.iter_mut(), messages.iter()) { - dst.fill(src).map_err(|_| ErrorCode::ConversationError)? - } + let questions = Questions::new(messages)?; let mut response_pointer = std::ptr::null_mut(); // SAFETY: We're calling into PAM with valid everything. let result = unsafe { (self.callback)( messages.len() as c_int, - msgs_to_send.indirect(), + questions.indirect(), &mut response_pointer, self.appdata, ) @@ -128,6 +124,7 @@ } /// Like [`Message`], but this time we own the contents. +#[derive(Debug)] pub enum OwnedMessage<'a> { MaskedPrompt(MaskedQAndA<'a>), Prompt(QAndA<'a>), @@ -157,9 +154,11 @@ /// You are responsible for ensuring that the src-dst pair matches. unsafe fn convert(msg: &Message, resp: &mut Answer) { macro_rules! fill_text { - ($dst:ident, $src:ident) => {{let text_resp = unsafe {TextAnswer::upcast($src)}; - $dst.set_answer(text_resp.contents().map(Into::into));}} -} + ($dst:ident, $src:ident) => {{ + let text_resp = unsafe { TextAnswer::upcast($src) }; + $dst.set_answer(text_resp.contents().map(Into::into)); + }}; + } match *msg { Message::MaskedPrompt(qa) => fill_text!(qa, resp), Message::Prompt(qa) => fill_text!(qa, resp), diff -r 351bdc13005e -r 002adfb98c5c src/libpam/handle.rs --- a/src/libpam/handle.rs Sun Jun 08 01:03:46 2025 -0400 +++ b/src/libpam/handle.rs Sun Jun 08 03:48:40 2025 -0400 @@ -54,7 +54,7 @@ } /// Gets the `PAM_CONV` item from the handle. - fn conversation_item(&mut self) -> Result<&mut LibPamConversation> { + fn conversation_item(&mut self) -> Result<&mut LibPamConversation<'_>> { let output: *mut LibPamConversation = ptr::null_mut(); let result = unsafe { super::pam_get_item( diff -r 351bdc13005e -r 002adfb98c5c src/libpam/memory.rs --- a/src/libpam/memory.rs Sun Jun 08 01:03:46 2025 -0400 +++ b/src/libpam/memory.rs Sun Jun 08 03:48:40 2025 -0400 @@ -1,12 +1,28 @@ //! Things for dealing with memory. -use crate::conv::BorrowedBinaryData; use crate::Result; use crate::{BinaryData, ErrorCode}; -use std::ffi::{c_char, c_void, CStr, CString}; +use std::ffi::{c_char, CStr, CString}; use std::marker::{PhantomData, PhantomPinned}; use std::{ptr, slice}; +/// Allocates `count` elements to hold `T`. +#[inline] +pub fn calloc(count: usize) -> *mut T { + // SAFETY: it's always safe to allocate! Leaking memory is fun! + unsafe { libc::calloc(count, size_of::()) }.cast() +} + +/// Wrapper for [`libc::free`] to make debugging calls/frees easier. +/// +/// # Safety +/// +/// If you double-free, it's all your fault. +#[inline] +pub unsafe fn free(p: *mut T) { + libc::free(p.cast()) +} + /// Makes whatever it's in not [`Send`], [`Sync`], or [`Unpin`]. #[repr(C)] #[derive(Debug)] @@ -62,7 +78,7 @@ /// Allocates a string with the given contents on the C heap. /// -/// This is like [`CString::new`](std::ffi::CString::new), but: +/// This is like [`CString::new`], but: /// /// - it allocates data on the C heap with [`libc::malloc`]. /// - it doesn't take ownership of the data passed in. @@ -71,11 +87,12 @@ if data.contains(&0) { return Err(ErrorCode::ConversationError); } + let data_alloc: *mut c_char = calloc(data.len() + 1); + // SAFETY: we just allocated this and we have enough room. unsafe { - let data_alloc = libc::calloc(data.len() + 1, 1); - libc::memcpy(data_alloc, data.as_ptr().cast(), data.len()); - Ok(data_alloc.cast()) + libc::memcpy(data_alloc.cast(), data.as_ptr().cast(), data.len()); } + Ok(data_alloc) } /// Writes zeroes over the contents of a C string. @@ -85,9 +102,9 @@ /// # Safety /// /// It's up to you to provide a valid C string. -pub unsafe fn zero_c_string(cstr: *mut c_void) { +pub unsafe fn zero_c_string(cstr: *mut c_char) { if !cstr.is_null() { - libc::memset(cstr, 0, libc::strlen(cstr.cast())); + libc::memset(cstr.cast(), 0, libc::strlen(cstr.cast())); } } @@ -110,20 +127,20 @@ impl CBinaryData { /// Copies the given data to a new BinaryData on the heap. - pub fn alloc(source: &[u8], data_type: u8) -> Result<*mut CBinaryData> { + pub fn alloc((data, data_type): (&[u8], u8)) -> Result<*mut CBinaryData> { let buffer_size = - u32::try_from(source.len() + 5).map_err(|_| ErrorCode::ConversationError)?; + u32::try_from(data.len() + 5).map_err(|_| ErrorCode::ConversationError)?; // SAFETY: We're only allocating here. - let data = unsafe { - let dest_buffer: *mut CBinaryData = libc::malloc(buffer_size as usize).cast(); - let data = &mut *dest_buffer; - data.total_length = buffer_size.to_be_bytes(); - data.data_type = data_type; - let dest = data.data.as_mut_ptr(); - libc::memcpy(dest.cast(), source.as_ptr().cast(), source.len()); + let dest = unsafe { + let dest_buffer: *mut CBinaryData = calloc::(buffer_size as usize).cast(); + let dest = &mut *dest_buffer; + dest.total_length = buffer_size.to_be_bytes(); + dest.data_type = data_type; + let dest = dest.data.as_mut_ptr(); + libc::memcpy(dest.cast(), data.as_ptr().cast(), data.len()); dest_buffer }; - Ok(data) + Ok(dest) } fn length(&self) -> usize { @@ -141,39 +158,42 @@ } } -impl<'a> From<&'a CBinaryData> for BorrowedBinaryData<'a> { +impl<'a> From<&'a CBinaryData> for (&'a[u8], u8) { fn from(value: &'a CBinaryData) -> Self { - BorrowedBinaryData::new( - unsafe { slice::from_raw_parts(value.data.as_ptr(), value.length()) }, - value.data_type, - ) + (unsafe { slice::from_raw_parts(value.data.as_ptr(), value.length()) }, + value.data_type ) } } impl From> for BinaryData { fn from(value: Option<&CBinaryData>) -> Self { - value.map(BorrowedBinaryData::from).map(Into::into).unwrap_or_default() + // This is a dumb trick but I like it because it is simply the presence + // of `.map(|(x, y)| (x, y))` in the middle of this that gives + // type inference the hint it needs to make this work. + value + .map(Into::into) + .map(|(data, data_type)| (data, data_type)) + .map(Into::into) + .unwrap_or_default() } } #[cfg(test)] mod tests { - use super::{copy_pam_string, malloc_str, option_cstr, prompt_ptr, zero_c_string}; - use crate::ErrorCode; - use std::ffi::CString; + use super::{free, ErrorCode, CString, copy_pam_string, malloc_str, option_cstr, prompt_ptr, zero_c_string}; #[test] fn test_strings() { let str = malloc_str("hello there").unwrap(); malloc_str("hell\0 there").unwrap_err(); unsafe { - let copied = copy_pam_string(str.cast()).unwrap(); + let copied = copy_pam_string(str).unwrap(); assert_eq!("hello there", copied); - zero_c_string(str.cast()); + zero_c_string(str); let idx_three = str.add(3).as_mut().unwrap(); *idx_three = 0x80u8 as i8; - let zeroed = copy_pam_string(str.cast()).unwrap(); + let zeroed = copy_pam_string(str).unwrap(); assert!(zeroed.is_empty()); - libc::free(str.cast()); + free(str); } } diff -r 351bdc13005e -r 002adfb98c5c src/libpam/message.rs --- a/src/libpam/message.rs Sun Jun 08 01:03:46 2025 -0400 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,348 +0,0 @@ -//! Data and types dealing with PAM messages. - -use crate::constants::InvalidEnum; -use crate::libpam::conversation::OwnedMessage; -use crate::libpam::memory; -use crate::libpam::memory::{CBinaryData, Immovable}; -use crate::ErrorCode; -use crate::Result; -use num_derive::FromPrimitive; -use num_traits::FromPrimitive; -use std::ffi::{c_int, c_void, CStr}; -use std::result::Result as StdResult; -use std::{ptr, slice}; -use crate::conv::{BorrowedBinaryData, ErrorMsg, InfoMsg, MaskedQAndA, Message, QAndA, RadioQAndA}; - -/// The C enum values for messages shown to the user. -#[derive(Debug, PartialEq, FromPrimitive)] -pub enum Style { - /// Requests information from the user; will be masked when typing. - PromptEchoOff = 1, - /// Requests information from the user; will not be masked. - PromptEchoOn = 2, - /// An error message. - ErrorMsg = 3, - /// An informational message. - TextInfo = 4, - /// Yes/No/Maybe conditionals. A Linux-PAM extension. - RadioType = 5, - /// For server–client non-human interaction. - /// - /// NOT part of the X/Open PAM specification. - /// A Linux-PAM extension. - BinaryPrompt = 7, -} - -impl TryFrom for Style { - type Error = InvalidEnum; - fn try_from(value: c_int) -> StdResult { - Self::from_i32(value).ok_or(value.into()) - } -} - -impl From