view src/module.rs @ 59:3f4a77aa88be

Fix string copyting and improve error situation. This change is too big and includes several things: - Fix copying strings from PAM by fixing const and mut on pam funcs. - Improve error enums by simplifying conversions and removing unnecessary and ambiguous "success" variants. - Make a bunch of casts nicer. - Assorted other cleanup.
author Paul Fisher <paul@pfish.zone>
date Wed, 21 May 2025 00:27:18 -0400
parents daa2cde64601
children 05cc2c27334f
line wrap: on
line source

//! Functions for use in pam modules.

use crate::constants::{ErrorCode, Flags, PamResult};
use crate::items::{Item, ItemType};
use libc::c_char;
use secure_string::SecureString;
use std::ffi::{c_int, CStr, CString};

/// Opaque type, used as a pointer when making pam API calls.
///
/// A module is invoked via an external function such as `pam_sm_authenticate`.
/// Such a call provides a pam handle pointer.  The same pointer should be given
/// as an argument when making API calls.
#[repr(C)]
pub struct PamHandle {
    _data: [u8; 0],
}

#[link(name = "pam")]
extern "C" {
    fn pam_get_data(
        pamh: *const PamHandle,
        module_data_name: *const c_char,
        data: &mut *const libc::c_void,
    ) -> c_int;

    fn pam_set_data(
        pamh: *const PamHandle,
        module_data_name: *const c_char,
        data: *const libc::c_void,
        cleanup: extern "C" fn(
            pamh: *const PamHandle,
            data: *mut libc::c_void,
            error_status: c_int,
        ),
    ) -> c_int;

    fn pam_get_item(
        pamh: *const PamHandle,
        item_type: c_int,
        item: &mut *const libc::c_void,
    ) -> c_int;

    fn pam_set_item(pamh: *mut PamHandle, item_type: c_int, item: *const libc::c_void) -> c_int;

    fn pam_get_user(
        pamh: *const PamHandle,
        user: &mut *const c_char,
        prompt: *const c_char,
    ) -> c_int;

    fn pam_get_authtok(
        pamh: *const PamHandle,
        item_type: c_int,
        data: &mut *const c_char,
        prompt: *const c_char,
    ) -> c_int;

}

/// Function called at the end of a PAM session that is called to clean up
/// a value previously provided to PAM in a `pam_set_data` call.
///
/// You should never call this yourself.
extern "C" fn cleanup<T>(_: *const PamHandle, c_data: *mut libc::c_void, _: c_int) {
    unsafe {
        let _data: Box<T> = Box::from_raw(c_data.cast());
    }
}

impl PamHandle {
    /// Gets some value, identified by `key`, that has been set by the module
    /// previously.
    ///
    /// See the [`pam_get_data` manual page](
    /// https://www.man7.org/linux/man-pages/man3/pam_get_data.3.html).
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying PAM function call fails.
    ///
    /// # Safety
    ///
    /// The data stored under the provided key must be of type `T` otherwise the
    /// behaviour of this function is undefined.
    ///
    /// The data, if present, is owned by the current PAM conversation.
    pub unsafe fn get_data<T>(&self, key: &str) -> PamResult<Option<&T>> {
        let c_key = CString::new(key).map_err(|_| ErrorCode::ConversationError)?;
        let mut ptr: *const libc::c_void = std::ptr::null();
        ErrorCode::result_from(pam_get_data(self, c_key.as_ptr(), &mut ptr))?;
        match ptr.is_null() {
            true => Ok(None),
            false => {
                let typed_ptr = ptr.cast();
                Ok(Some(&*typed_ptr))
            }
        }
    }

    /// Stores a value that can be retrieved later with `get_data`.
    /// The conversation takes ownership of the data.
    ///
    /// See the [`pam_set_data` manual page](
    /// https://www.man7.org/linux/man-pages/man3/pam_set_data.3.html).
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying PAM function call fails.
    pub fn set_data<T>(&mut self, key: &str, data: Box<T>) -> PamResult<()> {
        let c_key = CString::new(key).map_err(|_| ErrorCode::ConversationError)?;
        let ret = unsafe {
            pam_set_data(
                self,
                c_key.as_ptr(),
                Box::into_raw(data).cast(),
                cleanup::<T>,
            )
        };
        ErrorCode::result_from(ret)
    }

    /// Retrieves a value that has been set, possibly by the pam client.
    /// This is particularly useful for getting a `PamConv` reference.
    ///
    /// These items are *references to PAM memory*
    /// which are *owned by the conversation*.
    ///
    /// See the [`pam_get_item` manual page](
    /// https://www.man7.org/linux/man-pages/man3/pam_get_item.3.html).
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying PAM function call fails.
    pub fn get_item<T: crate::items::Item>(&self) -> PamResult<Option<T>> {
        let mut ptr: *const libc::c_void = std::ptr::null();
        let out = unsafe {
            let ret = pam_get_item(self, T::type_id().into(), &mut ptr);
            ErrorCode::result_from(ret)?;
            let typed_ptr: *const T::Raw = ptr.cast();
            match typed_ptr.is_null() {
                true => None,
                false => Some(T::from_raw(typed_ptr)),
            }
        };
        Ok(out)
    }

    /// Sets an item in the pam context. It can be retrieved using `get_item`.
    ///
    /// See the [`pam_set_item` manual page](
    /// https://www.man7.org/linux/man-pages/man3/pam_set_item.3.html).
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying PAM function call fails.
    pub fn set_item<T: Item>(&mut self, item: T) -> PamResult<()> {
        let ret = unsafe { pam_set_item(self, T::type_id().into(), item.into_raw().cast()) };
        ErrorCode::result_from(ret)
    }

    /// Retrieves the name of the user who is authenticating or logging in.
    ///
    /// This is really a specialization of `get_item`.
    ///
    /// See the [`pam_get_user` manual page](
    /// https://www.man7.org/linux/man-pages/man3/pam_get_user.3.html).
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying PAM function call fails.
    pub fn get_user(&self, prompt: Option<&str>) -> PamResult<String> {
        let prompt = option_cstr(prompt)?;
        let mut output: *const c_char = std::ptr::null_mut();
        let ret = unsafe { pam_get_user(self, &mut output, prompt_ptr(prompt.as_ref())) };
        ErrorCode::result_from(ret)?;
        copy_pam_string(output)
    }

    /// Retrieves the authentication token from the user.
    ///
    /// This is really a specialization of `get_item`.
    ///
    /// See the [`pam_get_authtok` manual page](
    /// https://www.man7.org/linux/man-pages/man3/pam_get_authtok.3.html).
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying PAM function call fails.
    pub fn get_authtok(&self, prompt: Option<&str>) -> PamResult<SecureString> {
        let prompt = option_cstr(prompt)?;
        let mut output: *const c_char = std::ptr::null_mut();
        let res = unsafe {
            pam_get_authtok(
                self,
                ItemType::AuthTok.into(),
                &mut output,
                prompt_ptr(prompt.as_ref()),
            )
        };
        ErrorCode::result_from(res)?;
        copy_pam_string(output).map(SecureString::from)
    }
}

/// Safely converts a `&str` option to a `CString` option.
fn option_cstr(prompt: Option<&str>) -> PamResult<Option<CString>> {
    prompt
        .map(CString::new)
        .transpose()
        .map_err(|_| ErrorCode::ConversationError)
}

/// The pointer to the prompt CString, or null if absent.
pub(crate) fn prompt_ptr(prompt: Option<&CString>) -> *const c_char {
    match prompt {
        Some(c_str) => c_str.as_ptr(),
        None => std::ptr::null(),
    }
}

/// Creates an owned copy of a string that is returned from a
/// <code>pam_get_<var>whatever</var></code> function.
pub(crate) fn copy_pam_string(result_ptr: *const c_char) -> PamResult<String> {
    // We really shouldn't get a null pointer back here, but if we do, return nothing.
    if result_ptr.is_null() {
        return Ok(String::new());
    }
    let bytes = unsafe { CStr::from_ptr(result_ptr) };
    bytes
        .to_str()
        .map(String::from)
        .map_err(|_| ErrorCode::ConversationError)
}

/// Provides functions that are invoked by the entrypoints generated by the
/// [`pam_hooks!` macro](../macro.pam_hooks.html).
///
/// All hooks are ignored by PAM dispatch by default given the default return value of `PAM_IGNORE`.
/// Override any functions that you want to handle with your module. See [PAM’s root manual page](
/// https://www.man7.org/linux/man-pages/man3/pam.3.html).
#[allow(unused_variables)]
pub trait PamHooks {
    /// This function performs the task of establishing whether the user is permitted to gain access at
    /// this time. It should be understood that the user has previously been validated by an
    /// authentication module. This function checks for other things. Such things might be: the time of
    /// day or the date, the terminal line, remote hostname, etc. This function may also determine
    /// things like the expiration on passwords, and respond that the user change it before continuing.
    fn acct_mgmt(handle: &mut PamHandle, args: Vec<&CStr>, flags: Flags) -> PamResult<()> {
        Err(ErrorCode::Ignore)
    }

    /// This function performs the task of authenticating the user.
    fn sm_authenticate(handle: &mut PamHandle, args: Vec<&CStr>, flags: Flags) -> PamResult<()> {
        Err(ErrorCode::Ignore)
    }

    /// This function is used to (re-)set the authentication token of the user.
    ///
    /// The PAM library calls this function twice in succession. The first time with
    /// `PAM_PRELIM_CHECK` and then, if the module does not return `PAM_TRY_AGAIN`, subsequently with
    /// `PAM_UPDATE_AUTHTOK`. It is only on the second call that the authorization token is
    /// (possibly) changed.
    fn sm_chauthtok(handle: &mut PamHandle, args: Vec<&CStr>, flags: Flags) -> PamResult<()> {
        Err(ErrorCode::Ignore)
    }

    /// This function is called to terminate a session.
    fn sm_close_session(handle: &mut PamHandle, args: Vec<&CStr>, flags: Flags) -> PamResult<()> {
        Err(ErrorCode::Ignore)
    }

    /// This function is called to commence a session.
    fn sm_open_session(handle: &mut PamHandle, args: Vec<&CStr>, flags: Flags) -> PamResult<()> {
        Err(ErrorCode::Ignore)
    }

    /// This function performs the task of altering the credentials of the user with respect to the
    /// corresponding authorization scheme. Generally, an authentication module may have access to more
    /// information about a user than their authentication token. This function is used to make such
    /// information available to the application. It should only be called after the user has been
    /// authenticated but before a session has been established.
    fn sm_setcred(handle: &mut PamHandle, args: Vec<&CStr>, flags: Flags) -> PamResult<()> {
        Err(ErrorCode::Ignore)
    }
}