changeset 106:49d9e2b5c189

An irresponsible mix of implementing libpam-sys and other stuff.
author Paul Fisher <paul@pfish.zone>
date Thu, 26 Jun 2025 22:41:28 -0400
parents 13b4d2a19674
children 49c6633f6fd2
files Cargo.toml libpam-sys/Cargo.toml libpam-sys/README.md libpam-sys/build.rs libpam-sys/src/constants.rs libpam-sys/src/helpers.rs libpam-sys/src/lib.rs src/_doc.rs src/lib.rs src/libpam/environ.rs src/libpam/memory.rs src/libpam/question.rs
diffstat 12 files changed, 748 insertions(+), 7 deletions(-) [+]
line wrap: on
line diff
--- a/Cargo.toml	Thu Jun 26 00:48:51 2025 -0400
+++ b/Cargo.toml	Thu Jun 26 22:41:28 2025 -0400
@@ -1,5 +1,5 @@
 [workspace]
-members = ["testharness"]
+members = ["libpam-sys", "testharness"]
 resolver = "2"
 
 [workspace.package]
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libpam-sys/Cargo.toml	Thu Jun 26 22:41:28 2025 -0400
@@ -0,0 +1,19 @@
+[package]
+name = "libpam-sys"
+description = "Low-level bindings for PAM (Pluggable Authentication Modules)"
+links = "pam"
+version.workspace = true
+authors.workspace = true
+repository.workspace = true
+edition.workspace = true
+rust-version.workspace = true
+
+[features]
+default = ["basic-ext"]
+use-system-headers = []
+basic-ext = []
+linux-pam-ext = []
+openpam-ext = []
+
+[build-dependencies]
+bindgen = "0.69.5"
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libpam-sys/README.md	Thu Jun 26 22:41:28 2025 -0400
@@ -0,0 +1,35 @@
+# libpam-sys
+
+This crate provides low-level access to PAM.
+
+## Options
+
+With no features at all enabled, only the functions specified by the [X/SSO PAM specification][xsso] are available.
+
+- `extras` (enabled by default): Common extensions to PAM, shared by both OpenPAM and Linux-PAM.
+  This includes, most notably, `pam_get_authtok`.
+  *Illumos does not provide this.*
+- `illumos-ext`: Extensions provided only by Illumos.
+- `linux-pam-ext`: Extensions provided only by Linux-PAM.
+- `openpam-ext`: Extensions provided by OpenPAM.
+- `use-system-headers`: Source constants from your PAM system headers.
+
+## References
+
+- [X/SSO PAM specification][xsso]: This 1997 document laid out the original specification for PAM.
+- [Linux-PAM repository][linux-pam]: The Linux-PAM implementation, used by most (all?) Linux distributions. Contains many extensions.
+  - [Linux-PAM man page][man7]: Root man page for Linux-PAM, with links to additional PAM man pages.
+  - [Linux-PAM guides][linux-guides]: Documentation for developers using PAM and sysadmins.
+- [OpenPAM repository][openpam]: The OpenPAM implementation, used by many BSD varieties. This hews very close to the spec.
+  - [OpenPAM man page][manbsd]: NetBSD's root man page for OpenPAM.
+- [Illumos PAM repository][illumos-pam]: Illumos's implementation of PAM. Even more basic than OpenPAM.
+  - [Illumos PAM man page][manillumos]: Illumos's root man page for its PAM implementation.
+
+[xsso]: https://pubs.opengroup.org/onlinepubs/8329799/toc.htm
+[linux-pam]: https://github.com/linux-pam/linux-pam
+[man7]: https://www.man7.org/linux/man-pages/man8/pam.8.html
+[linux-guides]: https://www.chiark.greenend.org.uk/doc/libpam-doc/html/
+[openpam]: https://git.des.dev/OpenPAM/OpenPAM
+[manbsd]: https://man.netbsd.org/pam.8
+[illumos-pam]: https://code.illumos.org/plugins/gitiles/illumos-gate/+/refs/heads/master/usr/src/lib/libpam/
+[manillumos]: https://illumos.org/man/3PAM/pam
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libpam-sys/build.rs	Thu Jun 26 22:41:28 2025 -0400
@@ -0,0 +1,143 @@
+use bindgen::MacroTypeVariation;
+use std::error::Error;
+use std::fmt::{Debug, Display, Formatter};
+use std::path::PathBuf;
+use std::{env, fs};
+
+enum PamImpl {
+    Illumos,
+    LinuxPam,
+    OpenPam,
+}
+
+#[derive(Debug)]
+struct InvalidEnum(String);
+
+impl Display for InvalidEnum {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        write!(f, "invalid PAM impl {:?}", self.0)
+    }
+}
+
+impl Error for InvalidEnum {}
+
+impl TryFrom<&str> for PamImpl {
+    type Error = InvalidEnum;
+    fn try_from(value: &str) -> Result<Self, Self::Error> {
+        Ok(match value {
+            "illumos" => Self::Illumos,
+            "linux-pam" => Self::LinuxPam,
+            "openpam" => Self::OpenPam,
+            other => return Err(InvalidEnum(other.to_owned())),
+        })
+    }
+}
+
+impl Debug for PamImpl {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        Debug::fmt(
+            match self {
+                Self::Illumos => "illumos",
+                Self::LinuxPam => "linux-pam",
+                Self::OpenPam => "openpam",
+            },
+            f,
+        )
+    }
+}
+
+fn main() {
+    println!("cargo:rustc-link-lib=pam");
+    let out_file = PathBuf::from(env::var("OUT_DIR").unwrap()).join("constants.rs");
+    let pam_impl = do_detection();
+
+    if cfg!(feature = "use-system-headers") {
+        let builder = bindgen::Builder::default()
+            .parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
+            .blocklist_function(".*")
+            .blocklist_type(".*")
+            .allowlist_var(".*")
+            .default_macro_constant_type(MacroTypeVariation::Unsigned);
+
+        let builder = match pam_impl {
+            PamImpl::Illumos => builder.header_contents(
+                "illumos.h",
+                "\
+                        #include <security/pam_appl.h>
+                        #include <security/pam_modules.h>
+                    ",
+            ),
+            PamImpl::LinuxPam => builder.header_contents(
+                "linux-pam.h",
+                "\
+                        #include <security/_pam_types.h>
+                        #include <security/pam_appl.h>
+                        #include <security/pam_ext.h>
+                        #include <security/pam_modules.h>
+                    ",
+            ),
+            PamImpl::OpenPam => builder.header_contents(
+                "openpam.h",
+                "\
+                        #include <security/pam_types.h>
+                        #include <security/openpam.h>
+                        #include <security/pam_appl.h>
+                        #include <security/pam_constants.h>
+                    ",
+            ),
+        };
+        let bindings = builder.generate().unwrap();
+        bindings.write_to_file(out_file).unwrap();
+    } else {
+        // Just write empty data to the file to avoid conditional compilation
+        // shenanigans.
+        fs::write(out_file, "").unwrap();
+    }
+}
+
+fn do_detection() -> PamImpl {
+    println!(r#"cargo:rustc-check-cfg=cfg(pam_impl, values("illumos", "linux-pam", "openpam"))"#);
+    let pam_impl = _detect_internal();
+    println!("cargo:rustc-cfg=pam_impl={pam_impl:?}");
+    pam_impl
+}
+
+fn _detect_internal() -> PamImpl {
+    if let Some(pam_impl) = option_env!("LIBPAMSYS_PAM_IMPL") {
+        pam_impl.try_into().unwrap()
+    } else if cfg!(feature = "use-system-headers") {
+        // Detect which impl it is from system headers.
+        if header_exists("security/_pam_types.h") {
+            PamImpl::LinuxPam
+        } else if header_exists("security/openpam.h") {
+            PamImpl::OpenPam
+        } else if header_exists("security/pam_appl.h") {
+            PamImpl::Illumos
+        } else {
+            panic!("could not detect PAM implementation")
+        }
+    } else {
+        // Otherwise, guess what PAM impl we're using based on the OS.
+        if cfg!(target_os = "linux") {
+            PamImpl::LinuxPam
+        } else if cfg!(any(
+            target_os = "macos",
+            target_os = "freebsd",
+            target_os = "netbsd",
+            target_os = "dragonfly",
+            target_os = "openbsd"
+        )) {
+            PamImpl::OpenPam
+        } else {
+            PamImpl::Illumos
+        }
+    }
+}
+
+fn header_exists(header: &str) -> bool {
+    bindgen::Builder::default()
+        .blocklist_item(".*")
+        .header_contents("header.h", &format!("#include <{header}>"))
+        .generate()
+        .is_ok()
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libpam-sys/src/constants.rs	Thu Jun 26 22:41:28 2025 -0400
@@ -0,0 +1,241 @@
+//! All the constants.
+#![allow(dead_code)]
+
+/// Macro to make defining a bunch of constants way easier.
+macro_rules! define {
+        ($(#[$attr:meta])* $($name:ident = $value:expr);+$(;)?) => {
+            define!(
+                @meta { $(#[$attr])* }
+                $(pub const $name: u32 = $value;)+
+            );
+        };
+        (@meta $m:tt $($i:item)+) => { define!(@expand $($m $i)+); };
+        (@expand $({ $(#[$m:meta])* } $i:item)+) => {$($(#[$m])* $i)+};
+    }
+
+#[cfg(feature = "use-system-headers")]
+pub use system_headers::*;
+
+#[cfg(not(feature = "use-system-headers"))]
+pub use export::*;
+
+mod export {
+    // There are a few truly universal constants.
+    // They are defined here directly.
+    pub const PAM_SUCCESS: u32 = 0;
+
+    define!(
+        /// An item type.
+        PAM_SERVICE = 1;
+        PAM_USER = 2;
+        PAM_TTY = 3;
+        PAM_RHOST = 4;
+        PAM_CONV = 5;
+        PAM_AUTHTOK = 6;
+        PAM_OLDAUTHTOK = 7;
+        PAM_RUSER = 8;
+    );
+
+    define!(
+        /// A message style.
+        PAM_PROMPT_ECHO_OFF = 1;
+        PAM_PROMPT_ECHO_ON = 2;
+        PAM_ERROR_MSG = 3;
+        PAM_TEXT_INFO = 4;
+    );
+
+    define!(
+        /// Maximum size of PAM conversation elements (suggested).
+        PAM_MAX_NUM_MSG = 32;
+        PAM_MAX_MSG_SIZE = 512;
+        PAM_MAX_RESP_SIZE = 512;
+    );
+
+    #[cfg(pam_impl = "linux-pam")]
+    pub use super::linux_pam::*;
+
+    #[cfg(not(pam_impl = "linux-pam"))]
+    pub use super::shared::*;
+
+    #[cfg(pam_impl = "illumos")]
+    pub use super::illumos::*;
+
+    #[cfg(pam_impl = "openpam")]
+    pub use super::openpam::*;
+}
+
+/// Constants extracted from PAM header files.
+mod system_headers {
+    include!(concat!(env!("OUT_DIR"), "/constants.rs"));
+}
+
+/// Constants used by Linux-PAM.
+mod linux_pam {
+    define!(
+        /// An error code.
+        PAM_OPEN_ERR = 1;
+        PAM_SYMBOL_ERR = 2;
+        PAM_SERVICE_ERR = 3;
+        PAM_SYSTEM_ERR = 4;
+        PAM_BUF_ERR = 5;
+        PAM_PERM_DENIED = 6;
+        PAM_AUTH_ERR = 7;
+        PAM_CRED_INSUFFICIENT = 8;
+        PAM_AUTHINFO_UNAVAIL = 9;
+        PAM_USER_UNKNOWN = 10;
+        PAM_MAXTRIES = 11;
+        PAM_NEW_AUTHTOK_REQD = 12;
+        PAM_ACCT_EXPIRED = 13;
+        PAM_SESSION_ERR = 14;
+        PAM_CRED_UNAVAIL = 15;
+        PAM_CRED_EXPIRED = 16;
+        PAM_CRED_ERR = 17;
+        PAM_NO_MODULE_DATA = 18;
+        PAM_CONV_ERR = 19;
+        PAM_AUTHTOK_ERR = 20;
+        PAM_AUTHTOK_RECOVERY_ERR = 21;
+        PAM_AUTHTOK_LOCK_BUSY = 22;
+        PAM_AUTHTOK_DISABLE_AGING = 23;
+        PAM_TRY_AGAIN = 24;
+        PAM_IGNORE = 25;
+        PAM_ABORT = 26;
+        PAM_AUTHTOK_EXPIRED = 27;
+        PAM_MODULE_UNKNOWN = 28;
+        PAM_BAD_ITEM = 29;
+        PAM_CONV_AGAIN = 30;
+        PAM_INCOMPLETE = 31;
+        _PAM_RETURN_VALUES = 32;
+    );
+
+    define!(
+        /// A flag value.
+        PAM_SILENT = 0x8000;
+        PAM_DISALLOW_NULL_AUTHTOK = 0x0001;
+        PAM_ESTABLISH_CRED = 0x0002;
+        PAM_DELETE_CRED = 0x0004;
+        PAM_REINITIALIZE_CRED = 0x0008;
+
+        PAM_CHANGE_EXPIRED_AUTHTOK = 0x0020;
+    );
+
+    define!(
+        PAM_USER_PROMPT = 9;
+        PAM_FAIL_DELAY = 10;
+        PAM_XDISPLAY = 11;
+        PAM_XAUTHDATA = 12;
+        PAM_AUTHTOKTYPE = 13;
+    );
+
+    /// To suppress messages in the item cleanup function.
+    pub const PAM_DATA_SILENT: u32 = 0x40000000;
+
+    // Message styles
+    define!(
+        /// A message style.
+        PAM_RADIO_TYPE = 5;
+        PAM_BINARY_PROMPT = 7;
+    );
+}
+
+/// Constants shared between Illumos and OpenPAM.
+mod shared {
+    define!(
+        /// An error code.
+        PAM_OPEN_ERR = 1;
+        PAM_SYMBOL_ERR = 2;
+        PAM_SERVICE_ERR = 3;
+        PAM_SYSTEM_ERR = 4;
+        PAM_BUF_ERR = 5;
+        PAM_CONV_ERR = 6;
+        PAM_PERM_DENIED = 7;
+        PAM_MAXTRIES = 8;
+        PAM_AUTH_ERR = 9;
+        PAM_NEW_AUTHTOK_REQD = 10;
+        PAM_CRED_INSUFFICIENT = 11;
+        PAM_AUTHINFO_UNAVAIL = 12;
+        PAM_USER_UNKNOWN = 13;
+        PAM_CRED_UNAVAIL = 14;
+        PAM_CRED_EXPIRED = 15;
+        PAM_CRED_ERR = 16;
+        PAM_ACCT_EXPIRED = 17;
+        PAM_AUTHTOK_EXPIRED = 18;
+        PAM_SESSION_ERR = 19;
+        PAM_AUTHTOK_ERR = 20;
+        PAM_AUTHTOK_RECOVERY_ERR = 21;
+        PAM_AUTHTOK_LOCK_BUSY = 22;
+        PAM_AUTHTOK_DISABLE_AGING = 23;
+        PAM_NO_MODULE_DATA = 24;
+        PAM_IGNORE = 25;
+        PAM_ABORT = 26;
+        PAM_TRY_AGAIN = 27;
+    );
+
+    define!(
+        /// An item type.
+        PAM_USER_PROMPT = 9;
+        PAM_REPOSITORY = 10;
+    );
+
+    /// A general flag for PAM operations.
+    pub const PAM_SILENT: u32 = 0x80000000;
+
+    /// The password must be non-null.
+    pub const PAM_DISALLOW_NULL_AUTHTOK: u32 = 0b1;
+
+    define!(
+        /// A flag for `pam_setcred`.
+        PAM_ESTABLISH_CRED = 0b0001;
+        PAM_DELETE_CRED = 0b0010;
+        PAM_REINITIALIZE_CRED = 0b0100;
+        PAM_REFRESH_CRED = 0b1000;
+    );
+
+    define!(
+        /// A flag for `pam_chauthtok`.
+        PAM_PRELIM_CHECK = 0b0001;
+        PAM_UPDATE_AUTHTOK = 0b0010;
+        PAM_CHANGE_EXPIRED_AUTHTOK = 0b0100;
+    );
+}
+
+/// Constants exclusive to Illumos.
+mod illumos {
+    /// The total number of PAM error codes.
+    pub const PAM_TOTAL_ERRNUM: u32 = 28;
+
+    define!(
+        /// An item type.
+        PAM_RESOURCE = 11;
+        PAM_AUSER = 12;
+    );
+
+    /// A flag for `pam_chauthtok`.
+    pub const PAM_NO_AUTHTOK_CHECK: u32 = 0b1000;
+}
+
+/// Constants exclusive to OpenPAM.
+mod openpam {
+    define!(
+        /// An error code.
+        PAM_MODULE_UNKNOWN = 28;
+        PAM_DOMAIN_UNKNOWN = 29;
+        PAM_BAD_HANDLE = 30;
+        PAM_BAD_ITEM = 31;
+        PAM_BAD_FEATURE = 32;
+        PAM_BAD_CONSTANT = 33;
+    );
+    /// The total number of PAM error codes.
+    pub const PAM_NUM_ERRORS: i32 = 34;
+
+    define!(
+        /// An item type.
+        PAM_AUTHTOK_PROMPT = 11;
+        PAM_OLDAUTHTOK_PROMPT = 12;
+        PAM_HOST = 13;
+    );
+    /// The total number of PAM items.
+    pub const PAM_NUM_ITEMS: u32 = 14;
+}
+
+#[cfg(test)]
+mod test {}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libpam-sys/src/helpers.rs	Thu Jun 26 22:41:28 2025 -0400
@@ -0,0 +1,281 @@
+//! This module contains a few non-required helpers to deal with some of the
+//! more annoying memory-twiddling in the PAM API.
+//!
+//! Using these is optional but you might find it useful.
+use std::error::Error;
+use std::marker::{PhantomData, PhantomPinned};
+use std::mem::ManuallyDrop;
+use std::ptr::NonNull;
+use std::{fmt, slice};
+
+/// Error returned when attempting to allocate a buffer that is too big.
+///
+/// This is specifically used in [`OwnedBinaryPayload`] when you try to allocate
+/// a message larger than 2<sup>32</sup> bytes.
+#[derive(Debug, PartialEq)]
+pub struct TooBigError {
+    pub size: usize,
+    pub max: usize,
+}
+
+impl Error for TooBigError {}
+
+impl fmt::Display for TooBigError {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        write!(
+            f,
+            "can't allocate a message of {size} bytes (max {max})",
+            size = self.size,
+            max = self.max
+        )
+    }
+}
+
+/// A trait wrapping memory management.
+///
+/// This is intended to allow you to bring your own allocator for
+/// [`OwnedBinaryPayload`]s.
+///
+/// For an implementation example, see the implementation of this trait
+/// for [`Vec`].
+pub trait Buffer<T: Default> {
+    /// Allocates a buffer of `len` elements, filled with the default.
+    fn allocate(len: usize) -> Self;
+
+    fn as_ptr(&self) -> *const T;
+
+    /// Returns a slice view of `size` elements of the given memory.
+    ///
+    /// # Safety
+    ///
+    /// The caller must not request more elements than are allocated.
+    unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [T];
+
+    /// Consumes this ownership and returns a pointer to the start of the arena.
+    fn into_ptr(self) -> NonNull<T>;
+
+    /// "Adopts" the memory at the given pointer, taking it under management.
+    ///
+    /// Running the operation:
+    ///
+    /// ```
+    /// # use libpam_sys::helpers::Buffer;
+    /// # fn test<T: Default, OwnerType: Buffer<T>>(bytes: usize) {
+    /// let owner = OwnerType::allocate(bytes);
+    /// let ptr = owner.into_ptr();
+    /// let owner = unsafe { OwnerType::from_ptr(ptr, bytes) };
+    /// # }
+    /// ```
+    ///
+    /// must be a no-op.
+    ///
+    /// # Safety
+    ///
+    /// The pointer must be valid, and the caller must provide the exact size
+    /// of the given arena.
+    unsafe fn from_ptr(ptr: NonNull<T>, bytes: usize) -> Self;
+}
+
+impl<T: Default> Buffer<T> for Vec<T> {
+    fn allocate(bytes: usize) -> Self {
+        (0..bytes).map(|_| Default::default()).collect()
+    }
+
+    fn as_ptr(&self) -> *const T {
+        Vec::as_ptr(self)
+    }
+
+    unsafe fn as_mut_slice(&mut self, bytes: usize) -> &mut [T] {
+        debug_assert!(bytes <= self.len());
+        Vec::as_mut(self)
+    }
+
+    fn into_ptr(self) -> NonNull<T> {
+        let mut me = ManuallyDrop::new(self);
+        // SAFETY: a Vec is guaranteed to have a nonzero pointer.
+        unsafe { NonNull::new_unchecked(me.as_mut_ptr()) }
+    }
+
+    unsafe fn from_ptr(ptr: NonNull<T>, bytes: usize) -> Self {
+        Vec::from_raw_parts(ptr.as_ptr(), bytes, bytes)
+    }
+}
+
+/// A binary message owned by some storage.
+///
+/// This is an owned, memory-managed version of [`BinaryPayload`].
+/// The `O` type manages the memory where the payload lives.
+/// [`Vec<u8>`] is one such manager and can be used when ownership
+/// of the data does not need to transit through PAM.
+#[derive(Debug)]
+pub struct OwnedBinaryPayload<Owner: Buffer<u8>>(Owner);
+
+impl<O: Buffer<u8>> OwnedBinaryPayload<O> {
+    /// Allocates a new OwnedBinaryPayload.
+    ///
+    /// This will return a [`TooBigError`] if you try to allocate too much
+    /// (more than [`BinaryPayload::MAX_SIZE`]).
+    pub fn new(data_type: u8, data: &[u8]) -> Result<Self, TooBigError> {
+        let total_len: u32 = (data.len() + 5).try_into().map_err(|_| TooBigError {
+            size: data.len(),
+            max: BinaryPayload::MAX_SIZE,
+        })?;
+        let total_len = total_len as usize;
+        let mut buf = O::allocate(total_len);
+        // SAFETY: We just allocated this exact size.
+        BinaryPayload::fill(unsafe { &mut buf.as_mut_slice(total_len) }, data_type, data);
+        Ok(Self(buf))
+    }
+
+    /// The contents of the buffer.
+    pub fn contents(&self) -> (u8, &[u8]) {
+        unsafe { BinaryPayload::contents(self.as_ptr()) }
+    }
+
+    /// The total bytes needed to store this, including the header.
+    pub fn total_bytes(&self) -> usize {
+        unsafe {
+            self.0
+                .as_ptr()
+                .cast::<BinaryPayload>()
+                .as_ref()
+                .unwrap_unchecked()
+                .total_bytes()
+        }
+    }
+
+    /// Unwraps this into the raw storage backing it.
+    pub fn into_inner(self) -> O {
+        self.0
+    }
+
+    /// Gets a const pointer to the start of the message's buffer.
+    pub fn as_ptr(&self) -> *const BinaryPayload {
+        self.0.as_ptr().cast()
+    }
+
+    /// Consumes ownership of this message and converts it to a raw pointer
+    /// to the start of the message.
+    ///
+    /// To clean this up, you should eventually pass it into [`Self::from_ptr`]
+    /// with the same `O` ownership type.
+    pub fn into_ptr(self) -> NonNull<BinaryPayload> {
+        self.0.into_ptr().cast()
+    }
+
+    /// Takes ownership of the given pointer.
+    ///
+    /// # Safety
+    ///
+    /// You must provide a valid pointer, allocated by (or equivalent to one
+    /// allocated by) [`Self::new`]. For instance, passing a pointer allocated
+    /// by `malloc` to `OwnedBinaryPayload::<Vec<u8>>::from_ptr` is not allowed.
+    pub unsafe fn from_ptr(ptr: NonNull<BinaryPayload>) -> Self {
+        Self(O::from_ptr(ptr.cast(), ptr.as_ref().total_bytes() as usize))
+    }
+}
+
+/// The structure of the "binary message" payload for the `PAM_BINARY_PROMPT`
+/// extension from Linux-PAM.
+pub struct BinaryPayload {
+    /// The total length of the message, including this header,
+    /// as a u32 in network byte order (big endian).
+    total_length: [u8; 4],
+    /// A tag used to provide some kind of hint as to what the data is.
+    /// This is not defined by PAM.
+    data_type: u8,
+    /// Where the data itself would start, used as a marker to make this
+    /// not [`Unpin`] (since it is effectively an intrusive data structure
+    /// pointing to immediately after itself).
+    _marker: PhantomData<PhantomPinned>,
+}
+
+impl BinaryPayload {
+    /// The most data it's possible to put into a [`BinaryPayload`].
+    pub const MAX_SIZE: usize = (u32::MAX - 5) as usize;
+
+    /// Fills in the provided buffer with the given data.
+    ///
+    /// This uses [`copy_from_slice`](slice::copy_from_slice) internally,
+    /// so `buf` must be exactly 5 bytes longer than `data`, or this function
+    /// will panic.
+    pub fn fill(buf: &mut [u8], data_type: u8, data: &[u8]) {
+        let ptr: *mut Self = buf.as_mut_ptr().cast();
+        // SAFETY: We're given a slice, which always has a nonzero pointer.
+        let me = unsafe { ptr.as_mut().unwrap_unchecked() };
+        me.total_length = u32::to_be_bytes(buf.len() as u32);
+        me.data_type = data_type;
+        buf[5..].copy_from_slice(data)
+    }
+
+    /// The size of the message contained in the buffer.
+    fn len(&self) -> usize {
+        self.total_bytes().saturating_sub(5)
+    }
+
+    /// The total storage needed for the message, including header.
+    pub fn total_bytes(&self) -> usize {
+        u32::from_be_bytes(self.total_length) as usize
+    }
+
+    /// Gets the contents of the BinaryMessage starting at the given location.
+    ///
+    /// # Safety
+    ///
+    /// You must pass in a valid pointer, and ensure that the pointer passed in
+    /// outlives your borrow lifetime `'a`.
+    unsafe fn contents<'a>(ptr: *const Self) -> (u8, &'a [u8]) {
+        let header: &Self = ptr.as_ref().unwrap_unchecked();
+        let typ = header.data_type;
+        (
+            typ,
+            slice::from_raw_parts(ptr.cast::<u8>().offset(5), header.len()),
+        )
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    type VecPayload = OwnedBinaryPayload<Vec<u8>>;
+
+    #[test]
+    fn test_binary_payload() {
+        let simple_message = &[0u8, 0, 0, 16, 0xff, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
+        let empty = &[0u8; 5];
+
+        assert_eq!((0xff, &[0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10][..]), unsafe {
+            BinaryPayload::contents(simple_message.as_ptr().cast())
+        });
+        assert_eq!((0x00, &[][..]), unsafe {
+            BinaryPayload::contents(empty.as_ptr().cast())
+        });
+    }
+
+    #[test]
+    fn test_owned_binary_payload() {
+        let (typ, data) = (
+            112,
+            &[0, 1, 1, 8, 9, 9, 9, 8, 8, 1, 9, 9, 9, 1, 1, 9, 7, 2, 5, 3][..],
+        );
+        let payload = VecPayload::new(typ, data).unwrap();
+        assert_eq!((typ, data), payload.contents());
+        let ptr = payload.into_ptr();
+        let payload = unsafe { VecPayload::from_ptr(ptr) };
+        assert_eq!((typ, data), payload.contents());
+    }
+
+    #[test]
+    #[ignore]
+    fn test_owned_too_big() {
+        let data = vec![0xFFu8; 0x1_0000_0001];
+        assert_eq!(
+            TooBigError {
+                max: 0xffff_fffa,
+                size: 0x1_0000_0001
+            },
+            VecPayload::new(5, &data).unwrap_err()
+        )
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libpam-sys/src/lib.rs	Thu Jun 26 22:41:28 2025 -0400
@@ -0,0 +1,22 @@
+#![doc = include_str!("../README.md")]
+//!
+//! ## Version info
+//!
+//! This documentation was built with the following configuration:
+//!
+#![cfg_attr(pam_impl = "illumos", doc = "- PAM implementation: Illumos")]
+#![cfg_attr(pam_impl = "linux-pam", doc = "- PAM implementation: Linux-PAM")]
+#![cfg_attr(pam_impl = "openpam", doc = "- PAM implementation: OpenPAM")]
+//!
+#![cfg_attr(feature = "basic-ext", doc = "- Includes common extensions")]
+#![cfg_attr(feature = "linux-pam-ext", doc = "- Includes Linux-PAM extensions")]
+#![cfg_attr(feature = "openpam-ext", doc = "- Includes OpenPAM extensions")]
+#![cfg_attr(
+    feature = "use-system-headers",
+    doc = "- Built with system header files"
+)]
+mod constants;
+pub mod helpers;
+
+#[doc(inline)]
+pub use constants::*;
--- a/src/_doc.rs	Thu Jun 26 00:48:51 2025 -0400
+++ b/src/_doc.rs	Thu Jun 26 22:41:28 2025 -0400
@@ -149,7 +149,7 @@
 /// ///
 /// #[doc = _xsso!(pam_set_item)]
 /// # fn link_one() {}
-/// 
+///
 /// /// This docstring will link to [`some_page`][xsso].
 /// /// I can also link to [the table of contents][spec_toc].
 /// ///
--- a/src/lib.rs	Thu Jun 26 00:48:51 2025 -0400
+++ b/src/lib.rs	Thu Jun 26 22:41:28 2025 -0400
@@ -31,11 +31,11 @@
 
 pub mod handle;
 
+mod _doc;
 mod environ;
 #[cfg(feature = "link")]
 mod libpam;
 pub mod logging;
-mod _doc;
 
 #[cfg(feature = "link")]
 #[doc(inline)]
--- a/src/libpam/environ.rs	Thu Jun 26 00:48:51 2025 -0400
+++ b/src/libpam/environ.rs	Thu Jun 26 22:41:28 2025 -0400
@@ -33,7 +33,7 @@
         if old.is_none() && value.is_none() {
             // pam_putenv returns an error if we try to remove a non-existent
             // environment variable, so just avoid that entirely.
-            return Ok(None)
+            return Ok(None);
         }
         let total_len = key.len() + value.map(OsStr::len).unwrap_or_default() + 2;
         let mut result = Vec::with_capacity(total_len);
--- a/src/libpam/memory.rs	Thu Jun 26 00:48:51 2025 -0400
+++ b/src/libpam/memory.rs	Thu Jun 26 22:41:28 2025 -0400
@@ -2,16 +2,16 @@
 
 use crate::Result;
 use crate::{BinaryData, ErrorCode};
+use memoffset::offset_of;
 use std::error::Error;
 use std::ffi::{c_char, CStr, CString};
 use std::fmt::{Display, Formatter, Result as FmtResult};
 use std::marker::{PhantomData, PhantomPinned};
-use std::mem::{ManuallyDrop};
+use std::mem::ManuallyDrop;
 use std::ops::{Deref, DerefMut};
 use std::ptr::NonNull;
 use std::result::Result as StdResult;
 use std::{mem, ptr, slice};
-use memoffset::offset_of;
 
 /// Raised from `calloc` when you have no memory!
 #[derive(Debug)]
--- a/src/libpam/question.rs	Thu Jun 26 00:48:51 2025 -0400
+++ b/src/libpam/question.rs	Thu Jun 26 22:41:28 2025 -0400
@@ -1,6 +1,5 @@
 //! Data and types dealing with PAM messages.
 
-use std::cell::Cell;
 #[cfg(feature = "linux-pam-extensions")]
 use crate::conv::{BinaryQAndA, RadioQAndA};
 use crate::conv::{ErrorMsg, InfoMsg, MaskedQAndA, Message, QAndA};
@@ -11,6 +10,7 @@
 use crate::ErrorCode;
 use crate::Result;
 use num_enum::{IntoPrimitive, TryFromPrimitive};
+use std::cell::Cell;
 use std::ffi::{c_void, CStr};
 use std::pin::Pin;
 use std::{ptr, slice};