Skip to content

Commit

Permalink
Add function name to errors and logs
Browse files Browse the repository at this point in the history
Adding the name of the function that lead to a backend error to the log
messages it generates and to the error returned to the client.

Signed-off-by: Ionut Mihalcea <[email protected]>
  • Loading branch information
ionut-arm committed Nov 28, 2023
1 parent 5739579 commit 77d046a
Show file tree
Hide file tree
Showing 16 changed files with 103 additions and 74 deletions.
11 changes: 9 additions & 2 deletions cryptoki/src/context/general_purpose.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::error::{Result, Rv};
use cryptoki_sys::{CK_C_INITIALIZE_ARGS, CK_INFO};
use paste::paste;
use std::convert::TryFrom;
use std::fmt::Display;

// See public docs on stub in parent mod.rs
#[inline(always)]
Expand All @@ -18,7 +19,7 @@ pub(super) fn initialize(ctx: &Pkcs11, init_args: CInitializeArgs) -> Result<()>
Rv::from(get_pkcs11!(ctx, C_Initialize)(
init_args_ptr as *mut CK_C_INITIALIZE_ARGS as *mut ::std::ffi::c_void,
))
.into_result()
.into_result(Function::Initialize)
}
}

Expand All @@ -27,7 +28,7 @@ pub(super) fn initialize(ctx: &Pkcs11, init_args: CInitializeArgs) -> Result<()>
pub(super) fn get_library_info(ctx: &Pkcs11) -> Result<Info> {
let mut info = CK_INFO::default();
unsafe {
Rv::from(get_pkcs11!(ctx, C_GetInfo)(&mut info)).into_result()?;
Rv::from(get_pkcs11!(ctx, C_GetInfo)(&mut info)).into_result(Function::GetInfo)?;
Info::try_from(info)
}
}
Expand Down Expand Up @@ -117,6 +118,12 @@ pub enum Function {
WaitForSlotEvent,
}

impl Display for Function {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Function::{:?}", self)
}
}

#[inline(always)]
pub(super) fn is_fn_supported(ctx: &Pkcs11, function: Function) -> bool {
match function {
Expand Down
5 changes: 3 additions & 2 deletions cryptoki/src/context/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ impl Pkcs11Impl {
.ok_or(Error::NullFunctionPointer)?(
ptr::null_mut()
))
.into_result()
.into_result(Function::Finalize)
}
}
}
Expand Down Expand Up @@ -91,7 +91,8 @@ impl Pkcs11 {
cryptoki_sys::Pkcs11::new(filename.as_ref()).map_err(Error::LibraryLoading)?;
let mut list = mem::MaybeUninit::uninit();

Rv::from(pkcs11_lib.C_GetFunctionList(list.as_mut_ptr())).into_result()?;
Rv::from(pkcs11_lib.C_GetFunctionList(list.as_mut_ptr()))
.into_result(Function::GetFunctionList)?;

let list_ptr = *list.as_ptr();

Expand Down
4 changes: 3 additions & 1 deletion cryptoki/src/context/session_management.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ use crate::session::Session;
use crate::slot::Slot;
use std::convert::TryInto;

use super::Function;

impl Pkcs11 {
#[inline(always)]
fn open_session(&self, slot_id: Slot, read_write: bool) -> Result<Session> {
Expand All @@ -29,7 +31,7 @@ impl Pkcs11 {
None,
&mut session_handle,
))
.into_result()?;
.into_result(Function::OpenSession)?;
}

Ok(Session::new(session_handle, self.clone()))
Expand Down
22 changes: 12 additions & 10 deletions cryptoki/src/context/slot_token_management.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,16 @@ use std::convert::{TryFrom, TryInto};

use crate::error::RvError::BufferTooSmall;

use super::Function;

impl Pkcs11 {
#[inline(always)]
fn get_slots(&self, with_token: CK_BBOOL) -> Result<Vec<Slot>> {
let mut slot_count = 0;
let rval = unsafe {
get_pkcs11!(self, C_GetSlotList)(with_token, std::ptr::null_mut(), &mut slot_count)
};
Rv::from(rval).into_result()?;
Rv::from(rval).into_result(Function::GetSlotList)?;

let mut slots;
loop {
Expand All @@ -41,7 +43,7 @@ impl Pkcs11 {
// and we want to loop again with a resized buffer.
if !matches!(Rv::from(rval), Rv::Error(BufferTooSmall)) {
// Account for other possible error types
Rv::from(rval).into_result()?;
Rv::from(rval).into_result(Function::GetSlotList)?;
// Otherwise, we have a valid list to process
break;
}
Expand Down Expand Up @@ -92,7 +94,7 @@ impl Pkcs11 {
pin.expose_secret().len().try_into()?,
label.as_ptr() as *mut u8,
))
.into_result()
.into_result(Function::InitToken)
}
}

Expand All @@ -104,7 +106,7 @@ impl Pkcs11 {
slot.try_into()?,
&mut slot_info,
))
.into_result()?;
.into_result(Function::GetSlotInfo)?;
Ok(SlotInfo::from(slot_info))
}
}
Expand All @@ -117,7 +119,7 @@ impl Pkcs11 {
slot.try_into()?,
&mut token_info,
))
.into_result()?;
.into_result(Function::GetTokenInfo)?;
TokenInfo::try_from(token_info)
}
}
Expand All @@ -132,7 +134,7 @@ impl Pkcs11 {
std::ptr::null_mut(),
&mut mechanism_count,
))
.into_result()?;
.into_result(Function::GetMechanismList)?;
}

let mut mechanisms = vec![0; mechanism_count.try_into()?];
Expand All @@ -143,7 +145,7 @@ impl Pkcs11 {
mechanisms.as_mut_ptr(),
&mut mechanism_count,
))
.into_result()?;
.into_result(Function::GetMechanismList)?;
}

// Truncate mechanisms if count decreased.
Expand All @@ -164,7 +166,7 @@ impl Pkcs11 {
type_.into(),
&mut mechanism_info,
))
.into_result()?;
.into_result(Function::GetMechanismInfo)?;
Ok(MechanismInfo::from(mechanism_info))
}
}
Expand All @@ -174,7 +176,7 @@ impl Pkcs11 {
let mut slot: CK_SLOT_ID = 0;
let wait_for_slot_event = get_pkcs11!(self, C_WaitForSlotEvent);
let rv = wait_for_slot_event(flags, &mut slot, std::ptr::null_mut());
Rv::from(rv).into_result()?;
Rv::from(rv).into_result(Function::WaitForSlotEvent)?;
Ok(Slot::new(slot))
}
}
Expand All @@ -187,7 +189,7 @@ impl Pkcs11 {
/// Get the latest slot event (insertion or removal of a token)
pub fn get_slot_event(&self) -> Result<Option<Slot>> {
match self.wait_for_slot_event_impl(CKF_DONT_BLOCK) {
Err(Error::Pkcs11(RvError::NoEvent)) => Ok(None),
Err(Error::Pkcs11(RvError::NoEvent, Function::WaitForSlotEvent)) => Ok(None),
Ok(slot) => Ok(Some(slot)),
Err(x) => Err(x),
}
Expand Down
14 changes: 5 additions & 9 deletions cryptoki/src/error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ pub use rv_error::*;

use std::fmt;

use crate::context::Function;

#[derive(Debug)]
/// Main error type
pub enum Error {
Expand All @@ -18,7 +20,7 @@ pub enum Error {
LibraryLoading(libloading::Error),

/// All PKCS#11 functions that return non-zero translate to this error.
Pkcs11(RvError),
Pkcs11(RvError, Function),

/// This error marks a feature that is not yet supported by the PKCS11 Rust abstraction layer.
NotSupported,
Expand Down Expand Up @@ -55,7 +57,7 @@ impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::LibraryLoading(e) => write!(f, "libloading error ({e})"),
Error::Pkcs11(e) => write!(f, "PKCS11 error: {e}"),
Error::Pkcs11(e, funct) => write!(f, "{funct}: PKCS11 error: {e}"),
Error::NotSupported => write!(f, "Feature not supported"),
Error::TryFromInt(e) => write!(f, "Conversion between integers failed ({e})"),
Error::TryFromSlice(e) => write!(f, "Error converting slice to array ({e})"),
Expand All @@ -79,7 +81,7 @@ impl std::error::Error for Error {
Error::ParseInt(e) => Some(e),
Error::Utf8(e) => Some(e),
Error::NulError(e) => Some(e),
Error::Pkcs11(_)
Error::Pkcs11(_, _)
| Error::NotSupported
| Error::NullFunctionPointer
| Error::PinNotSet
Expand Down Expand Up @@ -131,11 +133,5 @@ impl From<std::convert::Infallible> for Error {
}
}

impl From<RvError> for Error {
fn from(rv_error: RvError) -> Self {
Error::Pkcs11(rv_error)
}
}

/// Main Result type
pub type Result<T> = core::result::Result<T, Error>;
6 changes: 4 additions & 2 deletions cryptoki/src/error/rv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// SPDX-License-Identifier: Apache-2.0
//! Function types

use crate::context::Function;

use super::{Error, Result, RvError};
use cryptoki_sys::*;
use log::error;
Expand Down Expand Up @@ -128,10 +130,10 @@ impl From<CK_RV> for Rv {

impl Rv {
/// Convert the return value into a standard Result type
pub fn into_result(self) -> Result<()> {
pub fn into_result(self, function: Function) -> Result<()> {
match self {
Rv::Ok => Ok(()),
Rv::Error(rv_error) => Err(Error::Pkcs11(rv_error)),
Rv::Error(rv_error) => Err(Error::Pkcs11(rv_error, function)),
}
}
}
7 changes: 4 additions & 3 deletions cryptoki/src/session/decryption.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
//! Decrypting data

use crate::context::Function;
use crate::error::{Result, Rv};
use crate::mechanism::Mechanism;
use crate::object::ObjectHandle;
Expand All @@ -26,7 +27,7 @@ impl Session {
&mut mechanism as CK_MECHANISM_PTR,
key.handle(),
))
.into_result()?;
.into_result(Function::DecryptInit)?;
}

// Get the output buffer length
Expand All @@ -39,7 +40,7 @@ impl Session {
std::ptr::null_mut(),
&mut data_len,
))
.into_result()?;
.into_result(Function::Decrypt)?;
}

let mut data = vec![0; data_len.try_into()?];
Expand All @@ -52,7 +53,7 @@ impl Session {
data.as_mut_ptr(),
&mut data_len,
))
.into_result()?;
.into_result(Function::Decrypt)?;
}

data.resize(data_len.try_into()?, 0);
Expand Down
7 changes: 4 additions & 3 deletions cryptoki/src/session/digesting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
//! Digesting functions

use crate::context::Function;
use crate::error::{Result, Rv};
use crate::mechanism::Mechanism;
use crate::session::Session;
Expand All @@ -19,7 +20,7 @@ impl Session {
self.handle(),
&mut mechanism as CK_MECHANISM_PTR,
))
.into_result()?;
.into_result(Function::DigestInit)?;
}

// Get the output buffer length
Expand All @@ -31,7 +32,7 @@ impl Session {
std::ptr::null_mut(),
&mut digest_len,
))
.into_result()?;
.into_result(Function::Digest)?;
}

let mut digest = vec![0; digest_len.try_into()?];
Expand All @@ -44,7 +45,7 @@ impl Session {
digest.as_mut_ptr(),
&mut digest_len,
))
.into_result()?;
.into_result(Function::Digest)?;
}

digest.resize(digest_len.try_into()?, 0);
Expand Down
7 changes: 4 additions & 3 deletions cryptoki/src/session/encryption.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
//! Encrypting data

use crate::context::Function;
use crate::error::{Result, Rv};
use crate::mechanism::Mechanism;
use crate::object::ObjectHandle;
Expand All @@ -26,7 +27,7 @@ impl Session {
&mut mechanism as CK_MECHANISM_PTR,
key.handle(),
))
.into_result()?;
.into_result(Function::EncryptInit)?;
}

// Get the output buffer length
Expand All @@ -38,7 +39,7 @@ impl Session {
std::ptr::null_mut(),
&mut encrypted_data_len,
))
.into_result()?;
.into_result(Function::Encrypt)?;
}

let mut encrypted_data = vec![0; encrypted_data_len.try_into()?];
Expand All @@ -51,7 +52,7 @@ impl Session {
encrypted_data.as_mut_ptr(),
&mut encrypted_data_len,
))
.into_result()?;
.into_result(Function::Encrypt)?;
}

encrypted_data.resize(encrypted_data_len.try_into()?, 0);
Expand Down
Loading

0 comments on commit 77d046a

Please sign in to comment.