Skip to main content

libpam_sys_helpers/
lib.rs

1//! This package contains helpers to deal with memory management and
2//! annoying type stuff in `libpam-sys` (and LibPAM in general).
3
4use std::error::Error;
5use std::marker::{PhantomData, PhantomPinned};
6use std::mem::ManuallyDrop;
7use std::ptr::NonNull;
8use std::{any, fmt, mem, ptr, slice};
9
10// Memory management
11
12/// A pointer-to-pointer-to-message container for PAM's conversation callback.
13///
14/// The PAM conversation callback requires a pointer to a pointer of
15/// `pam_message`s. Linux-PAM handles this differently than all other
16/// PAM implementations (including the X/SSO PAM standard).
17///
18/// X/SSO appears to specify a pointer-to-pointer-to-array:
19///
20/// ```text
21///           points to  ┌────────────┐       ╔═ Message[] ═╗
22/// messages ┄┄┄┄┄┄┄┄┄┄> │ *messages ┄┼┄┄┄┄┄> ║ style       ║
23///                      └────────────┘       ║ data ┄┄┄┄┄┄┄╫┄┄> ...
24///                                           ╟─────────────╢
25///                                           ║ style       ║
26///                                           ║ data ┄┄┄┄┄┄┄╫┄┄> ...
27///                                           ╟─────────────╢
28///                                           ║ ...         ║
29/// ```
30///
31/// whereas Linux-PAM uses an `**argv`-style pointer-to-array-of-pointers:
32///
33/// ```text
34///           points to  ┌──────────────┐      ╔═ Message ═╗
35/// messages ┄┄┄┄┄┄┄┄┄┄> │ messages[0] ┄┼┄┄┄┄> ║ style     ║
36///                      │ messages[1] ┄┼┄┄┄╮  ║ data ┄┄┄┄┄╫┄┄> ...
37///                      │ ...          │   ┆  ╚═══════════╝
38///                                         ┆
39///                                         ┆    ╔═ Message ═╗
40///                                         ╰┄┄> ║ style     ║
41///                                              ║ data ┄┄┄┄┄╫┄┄> ...
42///                                              ╚═══════════╝
43/// ```
44///
45/// Because the `messages` remain owned by the application which calls into PAM,
46/// we can solve this with One Simple Trick: make the intermediate list point
47/// into the same array:
48///
49/// ```text
50///           points to  ┌──────────────┐      ╔═ Message[] ═╗
51/// messages ┄┄┄┄┄┄┄┄┄┄> │ messages[0] ┄┼┄┄┄┄> ║ style       ║
52///                      │ messages[1] ┄┼┄┄╮   ║ data ┄┄┄┄┄┄┄╫┄┄> ...
53///                      │ ...          │  ┆   ╟─────────────╢
54///                                        ╰┄> ║ style       ║
55///                                            ║ data ┄┄┄┄┄┄┄╫┄┄> ...
56///                                            ╟─────────────╢
57///                                            ║ ...         ║
58/// ```
59#[derive(Debug)]
60pub struct PtrPtrVec<T> {
61    data: Vec<T>,
62    pointers: Vec<*const T>,
63}
64
65// Since this is a wrapper around a Vec with no dangerous functionality*,
66// this can be Send and Sync provided the original Vec is.
67//
68// * It will only become unsafe when the user dereferences a pointer or sends it
69// to an unsafe function.
70unsafe impl<T> Send for PtrPtrVec<T> where Vec<T>: Send {}
71unsafe impl<T> Sync for PtrPtrVec<T> where Vec<T>: Sync {}
72
73impl<T> PtrPtrVec<T> {
74    /// Takes ownership of the given Vec and creates a vec of pointers to it.
75    pub fn new(data: Vec<T>) -> Self {
76        let start = data.as_ptr();
77        // We do this slightly tricky little dance to satisfy Miri:
78        //
79        // A pointer extracted from a reference can only legally access
80        // that reference's memory. This means that if we say:
81        //     pointers[0] = &data[0] as *const T;
82        // we can't traverse through pointers[0] to reach data[1],
83        // we can only use pointers[1].
84        //
85        // However, if we use the start-of-vec pointer from the `data` vector,
86        // its "provenance"* is valid for the entire array (even if the address
87        // of the pointer is the same). This avoids some behavior which is
88        // technically undefined. While the CPU sees no difference between
89        // those two pointers, the compiler is allowed to make optimizations
90        // based on that provenance (even if, in this case, it isn't likely
91        // to do so).
92        //
93        //       data.as_ptr() points here, and is valid for the whole Vec.
94        //       ┃
95        //       ┠─────────────────╮
96        //       ┌─────┬─────┬─────┐
97        //  data │ [0] │ [1] │ [2] │
98        //       └─────┴─────┴─────┘
99        //       ┠─────╯     ┊
100        //       ┃     ┊     ┊
101        //       (&data[0] as *const T) points to the same place, but is valid
102        //       only for that 0th element.
103        //             ┊     ┊
104        //             ┠─────╯
105        //             ┃
106        //             (&data[1] as *const T) points here, and is only valid
107        //             for that element.
108        //
109        // We only have to do this for pointers[0] because only that pointer
110        // is used for accessing elements other than data[0] (in XSSO).
111        //
112        // * "provenance" is kind of like if every pointer in your program
113        // remembered where it came from and, based on that, it had an implied
114        // memory range it was valid for, separate from its address.
115        // https://doc.rust-lang.org/std/ptr/#provenance
116        // (It took a long time for me to understand this.)
117        let mut pointers = Vec::with_capacity(data.len());
118        // Ensure the 0th pointer has provenance from the entire vec
119        // (even though it's numerically identical to &data[0] as *const T).
120        pointers.push(start);
121        // The 1st and everything thereafter only need to have the provenance
122        // of their own memory.
123        pointers.extend(data[1..].iter().map(|r| r as *const T));
124        Self { data, pointers }
125    }
126
127    /// Gives you back your Vec.
128    pub fn into_inner(self) -> Vec<T> {
129        self.data
130    }
131
132    /// Gets a pointer-to-pointer suitable for passing into the Conversation.
133    pub fn as_ptr<Dest>(&self) -> *const *const Dest {
134        Self::assert_size::<Dest>();
135        self.pointers.as_ptr().cast::<*const Dest>()
136    }
137
138    /// Iterates over a Linux-PAM–style pointer-to-array-of-pointers.
139    ///
140    /// # Safety
141    ///
142    /// `ptr_ptr` must be a valid pointer to an array of pointers,
143    /// there must be at least `count` valid pointers in the array,
144    /// and each pointer in that array must point to a valid `T`.
145    #[deprecated = "use [`Self::iter_over`] instead, unless you really need this specific version"]
146    #[allow(dead_code)]
147    pub unsafe fn iter_over_linux<'a, Src>(
148        ptr_ptr: *const *const Src,
149        count: usize,
150    ) -> impl Iterator<Item = &'a T>
151    where
152        T: 'a,
153    {
154        Self::assert_size::<Src>();
155        slice::from_raw_parts(ptr_ptr.cast::<&T>(), count)
156            .iter()
157            .copied()
158    }
159
160    /// Iterates over an X/SSO–style pointer-to-pointer-to-array.
161    ///
162    /// # Safety
163    ///
164    /// You must pass a valid pointer to a valid pointer to an array,
165    /// there must be at least `count` elements in the array,
166    /// and each value in that array must be a valid `T`.
167    #[deprecated = "use [`Self::iter_over`] instead, unless you really need this specific version"]
168    #[allow(dead_code)]
169    pub unsafe fn iter_over_xsso<'a, Src>(
170        ptr_ptr: *const *const Src,
171        count: usize,
172    ) -> impl Iterator<Item = &'a T>
173    where
174        T: 'a,
175    {
176        Self::assert_size::<Src>();
177        slice::from_raw_parts(*ptr_ptr.cast(), count).iter()
178    }
179
180    /// Iterates over a PAM message list appropriate to your system's impl.
181    ///
182    /// This selects the correct pointer/array structure to use for a message
183    /// that was given to you by your system.
184    ///
185    /// # Safety
186    ///
187    /// `ptr_ptr` must point to a valid message list, there must be at least
188    /// `count` messages in the list, and all messages must be a valid `Src`.
189    #[allow(deprecated)]
190    pub unsafe fn iter_over<'a, Src>(
191        ptr_ptr: *const *const Src,
192        count: usize,
193    ) -> impl Iterator<Item = &'a T>
194    where
195        T: 'a,
196    {
197        #[cfg(pam_impl = "LinuxPam")]
198        return Self::iter_over_linux(ptr_ptr, count);
199        #[cfg(not(pam_impl = "LinuxPam"))]
200        return Self::iter_over_xsso(ptr_ptr, count);
201    }
202
203    fn assert_size<That>() {
204        assert_eq!(
205            mem::size_of::<T>(),
206            mem::size_of::<That>(),
207            "type {t} is not the size of {that}",
208            t = any::type_name::<T>(),
209            that = any::type_name::<That>(),
210        );
211    }
212}
213
214/// Error returned when attempting to allocate a buffer that is too big.
215///
216/// This is specifically used in [`OwnedBinaryPayload`] when you try to allocate
217/// a message larger than 2<sup>32</sup> bytes.
218#[derive(Debug, PartialEq)]
219pub struct TooBigError {
220    pub size: usize,
221    pub max: usize,
222}
223
224impl Error for TooBigError {}
225
226impl fmt::Display for TooBigError {
227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228        write!(
229            f,
230            "can't allocate a message of {size} bytes (max {max})",
231            size = self.size,
232            max = self.max
233        )
234    }
235}
236
237/// A trait wrapping memory management.
238///
239/// This is intended to allow you to bring your own allocator for
240/// [`OwnedBinaryPayload`]s.
241///
242/// For an implementation example, see the implementation of this trait
243/// for [`Vec`].
244#[allow(clippy::wrong_self_convention)]
245pub trait Buffer {
246    /// Allocates a buffer of `len` elements, filled with the default.
247    fn allocate(len: usize) -> Self;
248
249    fn as_ptr(this: &Self) -> *const u8;
250
251    /// Returns a slice view of `size` elements of the given memory.
252    ///
253    /// # Safety
254    ///
255    /// The caller must not request more elements than are allocated.
256    unsafe fn as_mut_slice(this: &mut Self, len: usize) -> &mut [u8];
257
258    /// Consumes this ownership and returns a pointer to the start of the arena.
259    fn into_ptr(this: Self) -> NonNull<u8>;
260
261    /// "Adopts" the memory at the given pointer, taking it under management.
262    ///
263    /// Running the operation:
264    ///
265    /// ```
266    /// # use libpam_sys_helpers::Buffer;
267    /// # fn test<T: Default, OwnerType: Buffer>(bytes: usize) {
268    /// let owner = OwnerType::allocate(bytes);
269    /// let ptr = OwnerType::into_ptr(owner);
270    /// let owner = unsafe { OwnerType::from_ptr(ptr, bytes) };
271    /// # }
272    /// ```
273    ///
274    /// must be a no-op.
275    ///
276    /// # Safety
277    ///
278    /// The pointer must be valid, and the caller must provide the exact size
279    /// of the given arena.
280    unsafe fn from_ptr(ptr: NonNull<u8>, bytes: usize) -> Self;
281}
282
283impl Buffer for Vec<u8> {
284    fn allocate(bytes: usize) -> Self {
285        vec![0; bytes]
286    }
287
288    fn as_ptr(this: &Self) -> *const u8 {
289        Vec::as_ptr(this)
290    }
291
292    unsafe fn as_mut_slice(this: &mut Self, bytes: usize) -> &mut [u8] {
293        &mut this[..bytes]
294    }
295
296    fn into_ptr(this: Self) -> NonNull<u8> {
297        let mut me = ManuallyDrop::new(this);
298        // SAFETY: a Vec is guaranteed to have a nonzero pointer.
299        unsafe { NonNull::new_unchecked(me.as_mut_ptr()) }
300    }
301
302    unsafe fn from_ptr(ptr: NonNull<u8>, bytes: usize) -> Self {
303        Vec::from_raw_parts(ptr.as_ptr(), bytes, bytes)
304    }
305}
306
307/// The structure of the "binary message" payload for the `PAM_BINARY_PROMPT`
308/// extension from Linux-PAM.
309pub struct BinaryPayload {
310    /// The total byte size of the message, including this header,
311    /// as u32 in network byte order (big endian).
312    pub total_bytes_u32be: [u8; 4],
313    /// A tag used to provide some kind of hint as to what the data is.
314    /// Its meaning is undefined.
315    pub data_type: u8,
316    /// Where the data itself would start, used as a marker to make this
317    /// not [`Unpin`] (since it is effectively an intrusive data structure
318    /// pointing to immediately after itself).
319    pub _marker: PhantomData<PhantomPinned>,
320}
321
322impl BinaryPayload {
323    /// The most data it's possible to put into a [`BinaryPayload`].
324    pub const MAX_SIZE: usize = (u32::MAX - 5) as usize;
325
326    /// Fills in the provided buffer with the given data.
327    ///
328    /// This uses [`copy_from_slice`](slice::copy_from_slice) internally,
329    /// so `buf` must be exactly 5 bytes longer than `data`, or this function
330    /// will panic.
331    pub fn fill(buf: &mut [u8], data: &[u8], data_type: u8) {
332        let ptr: *mut Self = buf.as_mut_ptr().cast();
333        // SAFETY: We're given a slice, which always has a nonzero pointer.
334        let me = unsafe { ptr.as_mut().unwrap_unchecked() };
335        me.total_bytes_u32be = u32::to_be_bytes(buf.len() as u32);
336        me.data_type = data_type;
337        buf[5..].copy_from_slice(data)
338    }
339
340    /// The total storage needed for the message, including header.
341    ///
342    /// # Safety
343    ///
344    /// The pointer must point to a valid `BinaryPayload`.
345    pub unsafe fn total_bytes(this: *const Self) -> usize {
346        let header = this.as_ref().unwrap_unchecked();
347        u32::from_be_bytes(header.total_bytes_u32be) as usize
348    }
349
350    /// Gets the total byte buffer of the BinaryMessage stored at the pointer.
351    ///
352    /// The returned data slice is borrowed from where the pointer points to.
353    ///
354    /// # Safety
355    ///
356    /// - The pointer must point to a valid `BinaryPayload`.
357    /// - The borrowed data must not outlive the pointer's validity.
358    pub unsafe fn buffer_of<'a>(ptr: *const Self) -> &'a [u8] {
359        slice::from_raw_parts(ptr.cast(), Self::total_bytes(ptr).max(5))
360    }
361
362    /// Gets the contents of the BinaryMessage stored at the given pointer.
363    ///
364    /// The returned data slice is borrowed from where the pointer points to.
365    /// This is a cheap operation and doesn't do *any* copying.
366    ///
367    /// We don't take a `&self` reference here because accessing beyond
368    /// the range of the `Self` data (i.e., beyond the 5 bytes of `self`)
369    /// is undefined behavior. Instead, you have to pass a raw pointer
370    /// directly to the data.
371    ///
372    /// # Safety
373    ///
374    /// - The pointer must point to a valid `BinaryPayload`.
375    /// - The borrowed data must not outlive the pointer's validity.
376    pub unsafe fn contents<'a>(ptr: *const Self) -> (&'a [u8], u8) {
377        let header: &Self = ptr.as_ref().unwrap_unchecked();
378        (&Self::buffer_of(ptr)[5..], header.data_type)
379    }
380
381    /// Zeroes out the data of this payload.
382    ///
383    /// # Safety
384    ///
385    /// - The pointer must point to a valid `BinaryPayload`.
386    /// - The binary payload must not be used in the future,
387    ///   since its length metadata is gone and so its buffer is unknown.
388    pub unsafe fn zero(ptr: *mut Self) {
389        let size = Self::total_bytes(ptr);
390        let ptr: *mut u8 = ptr.cast();
391        for x in 0..size {
392            ptr::write_volatile(ptr.byte_add(x), mem::zeroed())
393        }
394    }
395}
396
397/// A binary message owned by some storage.
398///
399/// This is an owned, memory-managed version of [`BinaryPayload`].
400/// The `O` type manages the memory where the payload lives.
401/// [`Vec<u8>`] is one such manager and can be used when ownership
402/// of the data does not need to transit through PAM.
403#[derive(Debug)]
404pub struct OwnedBinaryPayload<Owner: Buffer>(Owner);
405
406impl<O: Buffer> OwnedBinaryPayload<O> {
407    /// Allocates a new OwnedBinaryPayload.
408    ///
409    /// This will return a [`TooBigError`] if you try to allocate too much
410    /// (more than [`BinaryPayload::MAX_SIZE`]).
411    pub fn new(data: &[u8], type_: u8) -> Result<Self, TooBigError> {
412        let total_len: u32 = (data.len() + 5).try_into().map_err(|_| TooBigError {
413            size: data.len(),
414            max: BinaryPayload::MAX_SIZE,
415        })?;
416        let total_len = total_len as usize;
417        let mut buf = O::allocate(total_len);
418        // SAFETY: We just allocated this exact size.
419        BinaryPayload::fill(
420            unsafe { Buffer::as_mut_slice(&mut buf, total_len) },
421            data,
422            type_,
423        );
424        Ok(Self(buf))
425    }
426
427    /// The contents of the buffer.
428    pub fn contents(&self) -> (&[u8], u8) {
429        unsafe { BinaryPayload::contents(self.as_ptr()) }
430    }
431
432    /// The total bytes needed to store this, including the header.
433    pub fn total_bytes(&self) -> usize {
434        unsafe { BinaryPayload::buffer_of(Buffer::as_ptr(&self.0).cast()).len() }
435    }
436
437    /// Unwraps this into the raw storage backing it.
438    pub fn into_inner(self) -> O {
439        self.0
440    }
441
442    /// Gets a const pointer to the start of the message's buffer.
443    pub fn as_ptr(&self) -> *const BinaryPayload {
444        Buffer::as_ptr(&self.0).cast()
445    }
446
447    /// Consumes ownership of this message and converts it to a raw pointer
448    /// to the start of the message.
449    ///
450    /// To clean this up, you should eventually pass it into [`Self::from_ptr`]
451    /// with the same `O` ownership type.
452    pub fn into_ptr(self) -> NonNull<BinaryPayload> {
453        Buffer::into_ptr(self.0).cast()
454    }
455
456    /// Takes ownership of the given pointer.
457    ///
458    /// # Safety
459    ///
460    /// You must provide a valid pointer, allocated by (or equivalent to one
461    /// allocated by) [`Self::new`]. For instance, passing a pointer allocated
462    /// by `malloc` to `OwnedBinaryPayload::<Vec<u8>>::from_ptr` is not allowed.
463    pub unsafe fn from_ptr(ptr: NonNull<BinaryPayload>) -> Self {
464        Self(O::from_ptr(
465            ptr.cast(),
466            BinaryPayload::total_bytes(ptr.as_ptr()),
467        ))
468    }
469}
470
471#[cfg(test)]
472mod tests {
473    use super::*;
474    use std::ptr;
475
476    type VecPayload = OwnedBinaryPayload<Vec<u8>>;
477
478    #[test]
479    fn test_binary_payload() {
480        let simple_message = &[0u8, 0, 0, 16, 0xff, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
481        let empty = &[0u8; 5];
482
483        assert_eq!((&[0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10][..], 0xff), unsafe {
484            BinaryPayload::contents(simple_message.as_ptr().cast())
485        });
486        assert_eq!((&[][..], 0x00), unsafe {
487            BinaryPayload::contents(empty.as_ptr().cast())
488        });
489    }
490
491    #[test]
492    fn test_owned_binary_payload() {
493        let (data, typ) = (
494            &[0, 1, 1, 8, 9, 9, 9, 8, 8, 1, 9, 9, 9, 1, 1, 9, 7, 2, 5, 3][..],
495            112,
496        );
497        let payload = VecPayload::new(data, typ).unwrap();
498        assert_eq!((data, typ), payload.contents());
499        let ptr = payload.into_ptr();
500        let payload = unsafe { VecPayload::from_ptr(ptr) };
501        assert_eq!((data, typ), payload.contents());
502    }
503
504    #[test]
505    #[ignore]
506    fn test_owned_too_big() {
507        let data = vec![0xFFu8; 0x1_0000_0001];
508        assert_eq!(
509            TooBigError {
510                max: 0xffff_fffa,
511                size: 0x1_0000_0001
512            },
513            VecPayload::new(&data, 5).unwrap_err()
514        )
515    }
516
517    #[cfg(debug_assertions)]
518    #[test]
519    #[should_panic]
520    fn test_new_wrong_size() {
521        let bad_vec = vec![0; 19];
522        let msg = PtrPtrVec::new(bad_vec);
523        let _ = msg.as_ptr::<u64>();
524    }
525
526    #[allow(deprecated)]
527    #[test]
528    #[should_panic]
529    fn test_iter_xsso_wrong_size() {
530        unsafe {
531            let _ = PtrPtrVec::<u8>::iter_over_xsso::<f64>(ptr::null(), 1);
532        }
533    }
534
535    #[allow(deprecated)]
536    #[test]
537    #[should_panic]
538    fn test_iter_linux_wrong_size() {
539        unsafe {
540            let _ = PtrPtrVec::<u128>::iter_over_linux::<()>(ptr::null(), 1);
541        }
542    }
543
544    #[allow(deprecated)]
545    #[test]
546    fn test_right_size() {
547        let good_vec = vec![(1u64, 2u64), (3, 4), (5, 6)];
548        let ptr = good_vec.as_ptr();
549        let msg = PtrPtrVec::new(good_vec);
550        let msg_ref: *const *const (i64, i64) = msg.as_ptr();
551        assert_eq!(unsafe { *msg_ref }, ptr.cast());
552
553        let linux_result: Vec<(i64, i64)> = unsafe { PtrPtrVec::iter_over_linux(msg_ref, 3) }
554            .cloned()
555            .collect();
556        let xsso_result: Vec<(i64, i64)> = unsafe { PtrPtrVec::iter_over_xsso(msg_ref, 3) }
557            .cloned()
558            .collect();
559        assert_eq!(vec![(1, 2), (3, 4), (5, 6)], linux_result);
560        assert_eq!(vec![(1, 2), (3, 4), (5, 6)], xsso_result);
561        drop(msg)
562    }
563
564    #[allow(deprecated)]
565    #[test]
566    fn test_iter_ptr_ptr() {
567        // These boxes are larger than a single pointer because we want to
568        // make sure they're not accidentally allocated adjacently
569        // in such a way that it's compatible with X/SSO.
570        //
571        // a pointer to (&str, i32) can be treated as a pointer to (&str).
572        #[repr(C)]
573        struct Pair(&'static str, i32);
574        let boxes = vec![
575            Box::new(Pair("a", 1)),
576            Box::new(Pair("b", 2)),
577            Box::new(Pair("c", 3)),
578            Box::new(Pair("D", 4)),
579        ];
580        let ptr: *const *const &str = boxes.as_ptr().cast();
581        let got: Vec<&str> = unsafe { PtrPtrVec::iter_over_linux(ptr, 4) }
582            .cloned()
583            .collect();
584        assert_eq!(vec!["a", "b", "c", "D"], got);
585
586        // On the other hand, we explicitly want these to be adjacent.
587        let nums = [-1i8, 2, 3];
588        let ptr = nums.as_ptr();
589        let got: Vec<u8> = unsafe { PtrPtrVec::iter_over_xsso(&ptr, 3) }
590            .cloned()
591            .collect();
592        assert_eq!(vec![255, 2, 3], got);
593    }
594}