Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions cryptoki/src/context/general_purpose.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use cryptoki_sys::{CK_C_INITIALIZE_ARGS, CK_INFO};
use paste::paste;
use std::convert::TryFrom;
use std::fmt::Display;
use std::ptr;

// See public docs on stub in parent mod.rs
#[inline(always)]
Expand All @@ -23,6 +24,14 @@ pub(super) fn initialize(ctx: &Pkcs11, init_args: CInitializeArgs) -> Result<()>
}
}

// See public docs on stub in parent mod.rs
#[inline(always)]
pub(super) fn finalize(ctx: Pkcs11) -> Result<()> {
unsafe {
Rv::from(get_pkcs11!(ctx, C_Finalize)(ptr::null_mut())).into_result(Function::Finalize)
}
}

// See public docs on stub in parent mod.rs
#[inline(always)]
pub(super) fn get_library_info(ctx: &Pkcs11) -> Result<Info> {
Expand Down
69 changes: 12 additions & 57 deletions cryptoki/src/context/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,9 @@ pub use locking::*;

use crate::error::{Error, Result, Rv};

use log::error;
use std::fmt;
use std::path::Path;
use std::ptr;
use std::sync::Arc;
use std::sync::RwLock;

/// Enum for various function lists
/// Each following is super-set of the previous one with overlapping start so we store them
Expand Down Expand Up @@ -75,35 +72,12 @@ impl Pkcs11Impl {
FunctionList::V3_2(l) => l,
}
}

// Private finalize call
#[inline(always)]
fn finalize(&self) -> Result<()> {
unsafe {
Rv::from(self
.get_function_list()
.C_Finalize
.ok_or(Error::NullFunctionPointer)?(
ptr::null_mut()
))
.into_result(Function::Finalize)
}
}
}

impl Drop for Pkcs11Impl {
fn drop(&mut self) {
if let Err(err) = self.finalize() {
error!("Failed to finalize: {err}");
}
}
}

/// Main PKCS11 context. Should usually be unique per application.
#[derive(Clone, Debug)]
#[derive(Debug)]
pub struct Pkcs11 {
pub(crate) impl_: Arc<Pkcs11Impl>,
initialized: Arc<RwLock<bool>>,
pub(crate) impl_: Pkcs11Impl,
}

impl Pkcs11 {
Expand Down Expand Up @@ -154,21 +128,19 @@ impl Pkcs11 {
let list32_ptr: *mut cryptoki_sys::CK_FUNCTION_LIST_3_2 =
ifce.pFunctionList as *mut cryptoki_sys::CK_FUNCTION_LIST_3_2;
return Ok(Pkcs11 {
impl_: Arc::new(Pkcs11Impl {
impl_: Pkcs11Impl {
_pkcs11_lib: pkcs11_lib,
function_list: FunctionList::V3_2(*list32_ptr),
}),
initialized: Arc::new(RwLock::new(false)),
},
});
}
let list30_ptr: *mut cryptoki_sys::CK_FUNCTION_LIST_3_0 =
ifce.pFunctionList as *mut cryptoki_sys::CK_FUNCTION_LIST_3_0;
return Ok(Pkcs11 {
impl_: Arc::new(Pkcs11Impl {
impl_: Pkcs11Impl {
_pkcs11_lib: pkcs11_lib,
function_list: FunctionList::V3_0(v30tov32(*list30_ptr)),
}),
initialized: Arc::new(RwLock::new(false)),
},
});
}
/* fall back to the 2.* API */
Expand All @@ -180,39 +152,22 @@ impl Pkcs11 {
.into_result(Function::GetFunctionList)?;

Ok(Pkcs11 {
impl_: Arc::new(Pkcs11Impl {
impl_: Pkcs11Impl {
_pkcs11_lib: pkcs11_lib,
function_list: FunctionList::V2(v2tov3(*list_ptr)),
}),
initialized: Arc::new(RwLock::new(false)),
},
})
}

/// Initialize the PKCS11 library
pub fn initialize(&self, init_args: CInitializeArgs) -> Result<()> {
let mut init_lock = self
.initialized
.as_ref()
.write()
.expect("lock not to be poisoned");
if *init_lock {
Err(Error::AlreadyInitialized)?
}
initialize(self, init_args).map(|_| *init_lock = true)
}

/// Check whether the PKCS11 library has been initialized
pub fn is_initialized(&self) -> bool {
*self
.initialized
.as_ref()
.read()
.expect("lock not to be poisoned")
initialize(self, init_args)
}

/// Finalize the PKCS11 library. Indicates that the application no longer needs to use PKCS11.
/// The library is also automatically finalized on drop.
pub fn finalize(self) {}
pub fn finalize(self) -> Result<()> {
finalize(self)
}

/// Returns the information about the library
pub fn get_library_info(&self) -> Result<Info> {
Expand Down
8 changes: 4 additions & 4 deletions cryptoki/src/context/session_management.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use super::Function;

impl Pkcs11 {
#[inline(always)]
fn open_session(&self, slot_id: Slot, read_write: bool) -> Result<Session> {
fn open_session(&self, slot_id: Slot, read_write: bool) -> Result<Session<'_>> {
let mut session_handle = 0;

let flags = if read_write {
Expand All @@ -33,7 +33,7 @@ impl Pkcs11 {
.into_result(Function::OpenSession)?;
}

Ok(Session::new(session_handle, self.clone()))
Ok(Session::new(session_handle, self))
}

/// Open a new Read-Only session
Expand All @@ -60,14 +60,14 @@ impl Pkcs11 {
/// let session = client.open_ro_session(slot)?;
/// # let _ = session; Ok(()) }
/// ```
pub fn open_ro_session(&self, slot_id: Slot) -> Result<Session> {
pub fn open_ro_session(&self, slot_id: Slot) -> Result<Session<'_>> {
self.open_session(slot_id, false)
}

/// Open a new Read/Write session
///
/// Note: No callback is set when opening the session.
pub fn open_rw_session(&self, slot_id: Slot) -> Result<Session> {
pub fn open_rw_session(&self, slot_id: Slot) -> Result<Session<'_>> {
self.open_session(slot_id, true)
}
}
7 changes: 1 addition & 6 deletions cryptoki/src/error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,6 @@ pub enum Error {

/// The PIN was not set before logging in.
PinNotSet,

/// The PKCS11 library has already been initialized
AlreadyInitialized,
}

impl fmt::Display for Error {
Expand All @@ -67,7 +64,6 @@ impl fmt::Display for Error {
Error::NullFunctionPointer => write!(f, "Calling a NULL function pointer"),
Error::InvalidValue => write!(f, "The value is not one of the expected options"),
Error::PinNotSet => write!(f, "Pin has not been set before trying to log in"),
Error::AlreadyInitialized => write!(f, "PKCS11 library has already been initialized"),
}
}
}
Expand All @@ -85,8 +81,7 @@ impl std::error::Error for Error {
| Error::NotSupported
| Error::NullFunctionPointer
| Error::PinNotSet
| Error::InvalidValue
| Error::AlreadyInitialized => None,
| Error::InvalidValue => None,
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion cryptoki/src/session/decryption.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::session::Session;
use cryptoki_sys::*;
use std::convert::TryInto;

impl Session {
impl Session<'_> {
/// Single-part decryption operation
pub fn decrypt(
&self,
Expand Down
2 changes: 1 addition & 1 deletion cryptoki/src/session/digesting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::session::Session;
use cryptoki_sys::*;
use std::convert::TryInto;

impl Session {
impl Session<'_> {
/// Single-part digesting operation
pub fn digest(&self, m: &Mechanism, data: &[u8]) -> Result<Vec<u8>> {
let mut mechanism: CK_MECHANISM = m.into();
Expand Down
2 changes: 1 addition & 1 deletion cryptoki/src/session/encapsulation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::session::Session;
use cryptoki_sys::*;
use std::convert::TryInto;

impl Session {
impl Session<'_> {
/// Encapsulate key
pub fn encapsulate_key(
&self,
Expand Down
2 changes: 1 addition & 1 deletion cryptoki/src/session/encryption.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::session::Session;
use cryptoki_sys::*;
use std::convert::TryInto;

impl Session {
impl Session<'_> {
/// Single-part encryption operation
pub fn encrypt(
&self,
Expand Down
2 changes: 1 addition & 1 deletion cryptoki/src/session/key_management.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::session::Session;
use cryptoki_sys::{CK_ATTRIBUTE, CK_MECHANISM, CK_MECHANISM_PTR};
use std::convert::TryInto;

impl Session {
impl Session<'_> {
/// Generate a secret key
pub fn generate_key(
&self,
Expand Down
2 changes: 1 addition & 1 deletion cryptoki/src/session/message_decryption.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::session::Session;
use cryptoki_sys::*;
use std::convert::TryInto;

impl Session {
impl Session<'_> {
/// Prepare a session for one or more Message-based decryption using the same mechanism and key
pub fn message_decrypt_init(&self, mechanism: &Mechanism, key: ObjectHandle) -> Result<()> {
let mut mechanism: CK_MECHANISM = mechanism.into();
Expand Down
2 changes: 1 addition & 1 deletion cryptoki/src/session/message_encryption.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::session::Session;
use cryptoki_sys::*;
use std::convert::TryInto;

impl Session {
impl Session<'_> {
/// Prepare a session for one or more Message-based encryption using the same mechanism and key
pub fn message_encrypt_init(&self, mechanism: &Mechanism, key: ObjectHandle) -> Result<()> {
let mut mechanism: CK_MECHANISM = mechanism.into();
Expand Down
27 changes: 13 additions & 14 deletions cryptoki/src/session/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use crate::context::Pkcs11;

use crate::error::Result;
use cryptoki_sys::*;
use std::fmt::Formatter;
use std::marker::PhantomData;
Expand Down Expand Up @@ -34,37 +35,33 @@ pub use validation::ValidationFlagsType;
/// threads. A Session needs to be created in its own thread or to be passed by ownership to
/// another thread.
#[derive(Debug)]
pub struct Session {
pub struct Session<'a> {
handle: CK_SESSION_HANDLE,
client: Pkcs11,
client: &'a Pkcs11,
// This is not used but to prevent Session to automatically implement Send and Sync
_guard: PhantomData<*mut u32>,
}

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

impl std::fmt::LowerHex for Session {
impl<'a> std::fmt::LowerHex for Session<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{:08x}", self.handle)
}
}

impl std::fmt::UpperHex for Session {
impl<'a> std::fmt::UpperHex for Session<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{:08X}", self.handle)
}
}

// Session does not implement Sync to prevent the same Session instance to be used from multiple
// threads.
unsafe impl Send for Session {}

impl Session {
pub(crate) fn new(handle: CK_SESSION_HANDLE, client: Pkcs11) -> Self {
impl<'a> Session<'a> {
pub(crate) fn new(handle: CK_SESSION_HANDLE, client: &'a Pkcs11) -> Self {
Session {
handle,
client,
Expand All @@ -73,18 +70,20 @@ impl Session {
}
}

impl Session {
impl<'a> Session<'a> {
/// Close a session
/// This will be called on drop as well.
pub fn close(self) {}
pub fn close(self) -> Result<()> {
self.close_inner()
}

/// Get the raw handle of the session.
pub fn handle(&self) -> CK_SESSION_HANDLE {
self.handle
}

pub(crate) fn client(&self) -> &Pkcs11 {
&self.client
self.client
}
}

Expand Down
4 changes: 2 additions & 2 deletions cryptoki/src/session/object_management.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ const MAX_OBJECT_COUNT: NonZeroUsize = unsafe { NonZeroUsize::new_unchecked(10)
/// ```
#[derive(Debug)]
pub struct ObjectHandleIterator<'a> {
session: &'a Session,
session: &'a Session<'a>,
object_count: usize,
index: usize,
cache: Vec<CK_OBJECT_HANDLE>,
Expand Down Expand Up @@ -207,7 +207,7 @@ impl Drop for ObjectHandleIterator<'_> {
}
}

impl Session {
impl Session<'_> {
/// Iterate over session objects matching a template.
///
/// # Arguments
Expand Down
2 changes: 1 addition & 1 deletion cryptoki/src/session/random.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::error::{Result, Rv};
use crate::session::Session;
use std::convert::TryInto;

impl Session {
impl Session<'_> {
/// Generates a random number and sticks it in a slice
///
/// # Arguments
Expand Down
Loading
Loading