Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Info flags refactor #68

Merged
merged 36 commits into from
Jan 27, 2022
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
3241c1b
Add a missing flag value used by TokenInfo
vkkoskie Nov 11, 2021
5951c48
Add two missing MechanismInfo flags
vkkoskie Nov 11, 2021
59fc60d
Remove unused SlotInfo traits
vkkoskie Nov 6, 2021
0fcd611
Convert SlotInfo contents once
vkkoskie Nov 6, 2021
8e5db26
Replace SlotInfo::new() with From impl
vkkoskie Nov 6, 2021
937d904
Merge get_all_slots and get_all_slots_with_token
vkkoskie Nov 6, 2021
e4436e2
Fix race condition in get_slots
vkkoskie Nov 6, 2021
10928a1
Expose SlotInfo flags individually
vkkoskie Nov 6, 2021
26925ab
Privatize SlotFlags; remove usused methods
vkkoskie Nov 6, 2021
6e6a2e9
Reimplement generic flags, then use in SlotInfo
vkkoskie Nov 10, 2021
9956187
Update SlotInfo docs
vkkoskie Nov 10, 2021
a573088
Refactor TokenInfo Flags
vkkoskie Nov 11, 2021
54cb98c
Hide conversions from sys crate in public docs
vkkoskie Nov 11, 2021
bee02b9
Refactor MechanismInfo Flags
vkkoskie Nov 12, 2021
0ae3adb
Move info types
vkkoskie Nov 12, 2021
aab33b7
Tidy info/flag docs
vkkoskie Nov 12, 2021
5bb40c6
Add Version constructor
vkkoskie Nov 12, 2021
88134f0
Add unit tests for info+flags debug content
vkkoskie Nov 12, 2021
de46362
Remove Display trait from Flag types
vkkoskie Nov 12, 2021
1b7f520
Tidy imports
vkkoskie Nov 12, 2021
0650deb
Remove some stray comment errors
vkkoskie Nov 17, 2021
5dfddf8
Add UtcTime implementation
vkkoskie Nov 18, 2021
46a2691
Make UtcTime conversion fallible
vkkoskie Nov 19, 2021
261d934
Refactor SessionInfo
vkkoskie Dec 3, 2021
67e7589
Replace SessionFlags with bool to open session
vkkoskie Dec 3, 2021
e221cf6
Remove unused SessionFlags type
vkkoskie Dec 4, 2021
992bfbf
Refactor SessionState
vkkoskie Dec 4, 2021
d4917a8
Remove InitializeFlags
vkkoskie Dec 4, 2021
1cbad05
Replace Display for UtcTime with named function
vkkoskie Dec 4, 2021
7ffa711
Replace custom CkFlags impl with bitflags crate
vkkoskie Dec 4, 2021
6dacb62
Refactor general Info struct
vkkoskie Dec 4, 2021
f18c73e
Replace nested Options with Limit newtype
vkkoskie Jan 13, 2022
40810ee
Add comment to explain test condition
vkkoskie Jan 13, 2022
7a0ad30
Move Option variants to single scope
vkkoskie Jan 14, 2022
aae8de0
Reduce visibility of Version constructor
vkkoskie Jan 14, 2022
b15eecd
Minor fix/enhance of a few comments
vkkoskie Jan 25, 2022
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
3 changes: 3 additions & 0 deletions cryptoki-sys/pkcs11.h
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,7 @@ struct ck_token_info
#define CKF_SO_PIN_FINAL_TRY (1UL << 21)
#define CKF_SO_PIN_LOCKED (1UL << 22)
#define CKF_SO_PIN_TO_BE_CHANGED (1UL << 23)
#define CKF_ERROR_STATE (1UL << 24)

#define CK_UNAVAILABLE_INFORMATION ((unsigned long)-1L)
#define CK_EFFECTIVELY_INFINITE (0UL)
Expand Down Expand Up @@ -1044,6 +1045,8 @@ struct ck_aes_cbc_encrypt_data_params {
#define CKF_EXTENSION ((unsigned long) (1UL << 31))

#define CKF_EC_F_P (1UL << 20)
#define CKF_EC_F_2M (1UL << 21)
#define CKF_EC_ECPARAMETERS (1UL << 22)
#define CKF_EC_NAMEDCURVE (1UL << 23)
#define CKF_EC_UNCOMPRESS (1UL << 24)
#define CKF_EC_COMPRESS (1UL << 25)
Expand Down
3 changes: 3 additions & 0 deletions cryptoki-sys/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ pub const CKF_SO_PIN_COUNT_LOW: CK_FLAGS = 0x00100000;
pub const CKF_SO_PIN_FINAL_TRY: CK_FLAGS = 0x00200000;
pub const CKF_SO_PIN_LOCKED: CK_FLAGS = 0x00400000;
pub const CKF_SO_PIN_TO_BE_CHANGED: CK_FLAGS = 0x00800000;
pub const CKF_ERROR_STATE: CK_FLAGS = 0x01000000;
pub const CK_UNAVAILABLE_INFORMATION: CK_ULONG = !0;
pub const CK_EFFECTIVELY_INFINITE: CK_ULONG = 0;
pub const CK_INVALID_HANDLE: CK_ULONG = 0;
Expand Down Expand Up @@ -689,6 +690,8 @@ pub const CKF_UNWRAP: CK_FLAGS = 0x00040000;
pub const CKF_DERIVE: CK_FLAGS = 0x00080000;
pub const CKF_EXTENSION: CK_FLAGS = 0x80000000;
pub const CKF_EC_F_P: CK_FLAGS = 0x00100000;
pub const CKF_EC_F_2M: CK_FLAGS = 0x00200000;
pub const CKF_EC_ECPARAMETERS: CK_FLAGS = 0x00400000;
pub const CKF_EC_NAMEDCURVE: CK_FLAGS = 0x00800000;
pub const CKF_EC_UNCOMPRESS: CK_FLAGS = 0x01000000;
pub const CKF_EC_COMPRESS: CK_FLAGS = 0x02000000;
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 @@ -20,6 +20,7 @@ mod locking;
mod session_management;
mod slot_token_management;

use cryptoki_sys::{CK_FALSE, CK_TRUE};
pub use flags::*;
pub use info::*;
pub use locking::*;
Expand Down Expand Up @@ -117,7 +118,7 @@ impl Pkcs11 {

/// Get all slots available with a token
pub fn get_slots_with_token(&self) -> Result<Vec<Slot>> {
slot_token_management::get_slots_with_token(self)
slot_token_management::get_slots(self, CK_TRUE)
}

/// Get all slots available with a token
Expand All @@ -127,7 +128,7 @@ impl Pkcs11 {

/// Get all slots
pub fn get_all_slots(&self) -> Result<Vec<Slot>> {
slot_token_management::get_all_slots(self)
slot_token_management::get_slots(self, CK_FALSE)
}

/// Initialize a token
Expand Down
99 changes: 33 additions & 66 deletions cryptoki/src/context/slot_token_management.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,40 +7,40 @@ use crate::error::{Result, Rv};
use crate::label_from_str;
use crate::mechanism::{MechanismInfo, MechanismType};
use crate::slot::{Slot, SlotInfo, TokenInfo};
use cryptoki_sys::{CK_MECHANISM_INFO, CK_SLOT_INFO, CK_TOKEN_INFO};
use std::convert::TryInto;
use cryptoki_sys::{CK_BBOOL, CK_MECHANISM_INFO, CK_SLOT_INFO, CK_TOKEN_INFO};
use std::convert::{TryFrom, TryInto};

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

// See public docs on stub in parent mod.rs
#[inline(always)]
pub(super) fn get_slots_with_token(ctx: &Pkcs11) -> Result<Vec<Slot>> {
pub(super) fn get_slots(ctx: &Pkcs11, with_token: CK_BBOOL) -> Result<Vec<Slot>> {
let mut slot_count = 0;

unsafe {
Rv::from(get_pkcs11!(ctx, C_GetSlotList)(
cryptoki_sys::CK_TRUE,
std::ptr::null_mut(),
&mut slot_count,
))
.into_result()?;
}

let mut slots = vec![0; slot_count.try_into()?];

unsafe {
Rv::from(get_pkcs11!(ctx, C_GetSlotList)(
cryptoki_sys::CK_TRUE,
slots.as_mut_ptr(),
&mut slot_count,
))
.into_result()?;
let rval = unsafe {
get_pkcs11!(ctx, C_GetSlotList)(with_token, std::ptr::null_mut(), &mut slot_count)
};
Rv::from(rval).into_result()?;

let mut slots;
loop {
slots = vec![0; slot_count as usize];
let rval = unsafe {
get_pkcs11!(ctx, C_GetSlotList)(with_token, slots.as_mut_ptr(), &mut slot_count)
};
// Account for a race condition between the call to get the
// slot_count and the last call in which the number of slots grew.
// In this case, slot_count will have been updated to the larger amount
// 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()?;
// Otherwise, we have a valid list to process
break;
}
}

let mut slots: Vec<Slot> = slots.into_iter().map(Slot::new).collect();

// This should always truncate slots.
slots.resize(slot_count.try_into()?, Slot::new(0));

Ok(slots)
// Account for the same race condition, but with a shrinking slot_count
slots.truncate(slot_count as usize);
Ok(slots.into_iter().map(Slot::new).collect())
}

// See public docs on stub in parent mod.rs
Expand All @@ -52,7 +52,7 @@ pub(super) fn get_slots_with_initialized_token(ctx: &Pkcs11) -> Result<Vec<Slot>
.into_iter()
.filter_map(|slot| match ctx.get_token_info(slot) {
Ok(token_info) => {
if token_info.flags().token_initialized() {
if token_info.token_initialized() {
Some(Ok(slot))
} else {
None
Expand All @@ -63,39 +63,6 @@ pub(super) fn get_slots_with_initialized_token(ctx: &Pkcs11) -> Result<Vec<Slot>
.collect()
}

// See public docs on stub in parent mod.rs
#[inline(always)]
pub(super) fn get_all_slots(ctx: &Pkcs11) -> Result<Vec<Slot>> {
let mut slot_count = 0;

unsafe {
Rv::from(get_pkcs11!(ctx, C_GetSlotList)(
cryptoki_sys::CK_FALSE,
std::ptr::null_mut(),
&mut slot_count,
))
.into_result()?;
}

let mut slots = vec![0; slot_count.try_into()?];

unsafe {
Rv::from(get_pkcs11!(ctx, C_GetSlotList)(
cryptoki_sys::CK_FALSE,
slots.as_mut_ptr(),
&mut slot_count,
))
.into_result()?;
}

let mut slots: Vec<Slot> = slots.into_iter().map(Slot::new).collect();

// This should always truncate slots.
slots.resize(slot_count.try_into()?, Slot::new(0));

Ok(slots)
}

// See public docs on stub in parent mod.rs
#[inline(always)]
pub(super) fn init_token(ctx: &Pkcs11, slot: Slot, pin: &str, label: &str) -> Result<()> {
Expand All @@ -121,7 +88,7 @@ pub(super) fn get_slot_info(ctx: &Pkcs11, slot: Slot) -> Result<SlotInfo> {
&mut slot_info,
))
.into_result()?;
Ok(SlotInfo::new(slot_info))
Ok(SlotInfo::from(slot_info))
}
}

Expand All @@ -135,7 +102,7 @@ pub(super) fn get_token_info(ctx: &Pkcs11, slot: Slot) -> Result<TokenInfo> {
&mut token_info,
))
.into_result()?;
Ok(TokenInfo::new(token_info))
TokenInfo::try_from(token_info)
}
}

Expand Down Expand Up @@ -188,6 +155,6 @@ pub(super) fn get_mechanism_info(
&mut mechanism_info,
))
.into_result()?;
Ok(MechanismInfo::new(mechanism_info))
Ok(MechanismInfo::from(mechanism_info))
}
}
22 changes: 22 additions & 0 deletions cryptoki/src/error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ pub enum Error {
/// Error when converting a slice to an array
TryFromSlice(std::array::TryFromSliceError),

/// Error when converting a numerical str to an integral value
ParseInt(core::num::ParseIntError),

/// Error converting into a type assuming valid UTF-8
Utf8(std::str::Utf8Error),

/// Error with nul characters in Strings
NulError(std::ffi::NulError),

Expand All @@ -50,6 +56,8 @@ impl fmt::Display for Error {
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),
Error::ParseInt(e) => write!(f, "Error parsing string as integer ({})", e),
Error::Utf8(e) => write!(f, "Invalid UTF-8 ({})", e),
Error::NulError(e) => write!(f, "An interior nul byte was found ({})", e),
Error::NullFunctionPointer => write!(f, "Calling a NULL function pointer"),
Error::InvalidValue => write!(f, "The value is not one of the expected options"),
Expand All @@ -64,6 +72,8 @@ impl std::error::Error for Error {
Error::LibraryLoading(e) => Some(e),
Error::TryFromInt(e) => Some(e),
Error::TryFromSlice(e) => Some(e),
Error::ParseInt(e) => Some(e),
Error::Utf8(e) => Some(e),
Error::NulError(e) => Some(e),
Error::Pkcs11(_)
| Error::NotSupported
Expand Down Expand Up @@ -92,6 +102,18 @@ impl From<std::array::TryFromSliceError> for Error {
}
}

impl From<core::num::ParseIntError> for Error {
fn from(err: core::num::ParseIntError) -> Error {
Error::ParseInt(err)
}
}

impl From<std::str::Utf8Error> for Error {
fn from(err: std::str::Utf8Error) -> Error {
Error::Utf8(err)
}
}

impl From<std::ffi::NulError> for Error {
fn from(err: std::ffi::NulError) -> Error {
Error::NulError(err)
Expand Down
Loading