Skip to content

Commit f429b59

Browse files
Add initialize flags and pReserved to CInitializeArgs
Signed-off-by: Alexandru Placinta <placintaalexandru1@gmail.com>
1 parent 2702bba commit f429b59

File tree

7 files changed

+120
-39
lines changed

7 files changed

+120
-39
lines changed

cryptoki/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ You can find it in the `examples` folder and run it with `cargo run --example ge
3535
```rust
3636
# fn main() -> testresult::TestResult {
3737
use cryptoki::object::Attribute;
38-
use cryptoki::context::{CInitializeArgs, Pkcs11};
38+
use cryptoki::context::{CInitializeArgs, CInitializeFlags, Pkcs11};
3939
use cryptoki::session::UserType;
4040
use cryptoki::types::AuthPin;
4141
use cryptoki::mechanism::Mechanism;
@@ -47,7 +47,7 @@ let pkcs11 = Pkcs11::new(
4747
.unwrap_or_else(|_| "/usr/local/lib/softhsm/libsofthsm2.so".to_string()),
4848
)?;
4949

50-
pkcs11.initialize(CInitializeArgs::OsThreads)?;
50+
pkcs11.initialize(CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK))?;
5151

5252
let slot = pkcs11.get_slots_with_token()?[0];
5353

cryptoki/examples/generate_key_pair.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Copyright 2024 Contributors to the Parsec project.
22
// SPDX-License-Identifier: Apache-2.0
3-
use cryptoki::context::{CInitializeArgs, Pkcs11};
3+
use cryptoki::context::{CInitializeArgs, CInitializeFlags, Pkcs11};
44
use cryptoki::mechanism::Mechanism;
55
use cryptoki::object::Attribute;
66
use cryptoki::session::UserType;
@@ -19,7 +19,7 @@ fn main() -> testresult::TestResult {
1919
.unwrap_or_else(|_| "/usr/local/lib/softhsm/libsofthsm2.so".to_string()),
2020
)?;
2121

22-
pkcs11.initialize(CInitializeArgs::OsThreads)?;
22+
pkcs11.initialize(CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK))?;
2323

2424
let slot = pkcs11.get_slots_with_token()?[0];
2525

cryptoki/src/context/locking.rs

Lines changed: 95 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,34 +2,107 @@
22
// SPDX-License-Identifier: Apache-2.0
33
//! Locking related type
44
5-
use cryptoki_sys::{CKF_OS_LOCKING_OK, CK_FLAGS};
5+
use bitflags::bitflags;
6+
use cryptoki_sys::{self, CK_C_INITIALIZE_ARGS, CK_FLAGS};
67

7-
use std::ptr;
8+
use std::{
9+
os::raw::c_void,
10+
ptr::{self, NonNull},
11+
};
12+
13+
bitflags! {
14+
/// Flags to set for the initialize function
15+
#[derive(Debug, Clone, Copy)]
16+
pub struct CInitializeFlags: CK_FLAGS {
17+
/// The library can use the native OS library for locking or the custom
18+
const OS_LOCKING_OK = cryptoki_sys::CKF_OS_LOCKING_OK;
19+
/// The library may not create its own threads
20+
const LIBRARY_CANT_CREATE_OS_THREADS = cryptoki_sys::CKF_LIBRARY_CANT_CREATE_OS_THREADS;
21+
}
22+
}
823

924
/// Argument for the initialize function
10-
#[derive(Copy, Clone, Debug)]
11-
pub enum CInitializeArgs {
12-
/// The library can use the native OS library for locking
13-
OsThreads,
14-
// TODO: add variants for custom mutexes here and no multithreading, safety implications for
15-
// that.
25+
#[derive(Debug, Clone, Copy)]
26+
pub struct CInitializeArgs {
27+
flags: CInitializeFlags,
28+
p_reserved: Option<NonNull<c_void>>,
1629
}
1730

18-
impl From<CInitializeArgs> for cryptoki_sys::CK_C_INITIALIZE_ARGS {
31+
impl CInitializeArgs {
32+
/// Create a new `CInitializeArgs` with the given flags
33+
///
34+
/// # Examples
35+
/// ```
36+
/// use cryptoki::context::{CInitializeArgs, CInitializeFlags};
37+
///
38+
/// let args = CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK | CInitializeFlags::LIBRARY_CANT_CREATE_OS_THREADS);
39+
/// ```
40+
pub fn new(flags: CInitializeFlags) -> Self {
41+
Self {
42+
flags,
43+
p_reserved: None,
44+
}
45+
}
46+
47+
/// Create a new `CInitializeArgs` with the given flags and reserved pointer.
48+
///
49+
/// # Safety
50+
/// Considered unsafe due to the user's ability to pass any pointer: the
51+
/// caller must ensure that the provided pointer is valid and points
52+
/// to a struct that has the same ABI as the one required by cryptoki's
53+
/// `C_Initialize`
54+
///
55+
/// The user is responsible for managing the memory behind the pointer.
56+
///
57+
/// # Examples
58+
///```
59+
/// use cryptoki::context::{CInitializeArgs, CInitializeFlags};
60+
/// use std::{ptr::NonNull, os::raw::c_void};
61+
///
62+
/// let flags = CInitializeFlags::OS_LOCKING_OK;
63+
///
64+
/// // Create a box with the reserved data
65+
/// let boxed_data = Box::new(42);
66+
///
67+
/// // Obtain the raw pointer
68+
/// let ptr_reserved = NonNull::new(Box::into_raw(boxed_data) as *mut c_void)
69+
/// .expect("Failed to create NonNull pointer");
70+
///
71+
/// // SAFETY: since the data was allocated when boxed_data was created, this is safe
72+
/// let args = unsafe {
73+
/// CInitializeArgs::new_with_reserved(flags, ptr_reserved)
74+
/// };
75+
///
76+
/// // Reassemble back the bax to make sure the data is correctly cleaned
77+
/// // SAFETY: since ptr_reserved was built with valid data, this is safe
78+
/// let reserved_data = unsafe { Box::from_raw(ptr_reserved.as_ptr()) };
79+
/// ```
80+
pub const unsafe fn new_with_reserved(
81+
flags: CInitializeFlags,
82+
p_reserved: NonNull<c_void>,
83+
) -> Self {
84+
Self {
85+
flags,
86+
p_reserved: Some(p_reserved),
87+
}
88+
}
89+
}
90+
91+
impl From<CInitializeArgs> for CK_C_INITIALIZE_ARGS {
1992
fn from(c_initialize_args: CInitializeArgs) -> Self {
20-
let mut flags = CK_FLAGS::default();
21-
match c_initialize_args {
22-
CInitializeArgs::OsThreads => {
23-
flags |= CKF_OS_LOCKING_OK;
24-
Self {
25-
flags,
26-
CreateMutex: None,
27-
DestroyMutex: None,
28-
LockMutex: None,
29-
UnlockMutex: None,
30-
pReserved: ptr::null_mut(),
31-
}
32-
}
93+
let flags = c_initialize_args.flags.bits();
94+
let p_reserved = c_initialize_args
95+
.p_reserved
96+
.map(|non_null| non_null.as_ptr())
97+
.unwrap_or_else(ptr::null_mut);
98+
99+
Self {
100+
CreateMutex: None,
101+
DestroyMutex: None,
102+
LockMutex: None,
103+
UnlockMutex: None,
104+
flags,
105+
pReserved: p_reserved,
33106
}
34107
}
35108
}

cryptoki/src/context/session_management.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,14 @@ impl Pkcs11 {
4848
/// # fn main() -> testresult::TestResult {
4949
/// use cryptoki::session::Session;
5050
/// use cryptoki::context::Pkcs11;
51+
/// use cryptoki::context::{CInitializeArgs, CInitializeFlags};
52+
///
5153
///
5254
/// let mut client = Pkcs11::new(
5355
/// std::env::var("TEST_PKCS11_MODULE")
5456
/// .unwrap_or_else(|_| "/usr/local/lib/softhsm/libsofthsm2.so".to_string()),
5557
/// )?;
56-
/// client.initialize(cryptoki::context::CInitializeArgs::OsThreads)?;
58+
/// client.initialize(CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK))?;
5759
///
5860
/// // Use the first slot
5961
/// let slot = client.get_all_slots()?[0];

cryptoki/src/session/object_management.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ const MAX_OBJECT_COUNT: NonZeroUsize = unsafe { NonZeroUsize::new_unchecked(10)
2828
/// # Example
2929
///
3030
/// ```no_run
31-
/// use cryptoki::context::CInitializeArgs;
31+
/// use cryptoki::context::{CInitializeArgs, CInitializeFlags};
3232
/// use cryptoki::context::Pkcs11;
3333
/// use cryptoki::error::Error;
3434
/// use cryptoki::object::Attribute;
@@ -43,7 +43,7 @@ const MAX_OBJECT_COUNT: NonZeroUsize = unsafe { NonZeroUsize::new_unchecked(10)
4343
/// # .unwrap_or_else(|_| "/usr/local/lib/libsofthsm2.so".to_string()),
4444
/// # )?;
4545
/// #
46-
/// # pkcs11.initialize(CInitializeArgs::OsThreads)?;
46+
/// # pkcs11.initialize(CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK))?;
4747
/// # let slot = pkcs11.get_slots_with_token()?.remove(0);
4848
/// #
4949
/// # let session = pkcs11.open_ro_session(slot).unwrap();
@@ -278,14 +278,14 @@ impl Session {
278278
/// ```rust
279279
/// # fn main() -> testresult::TestResult {
280280
/// # use cryptoki::session::Session;
281-
/// # use cryptoki::context::Pkcs11;
281+
/// # use cryptoki::context::{Pkcs11, CInitializeArgs, CInitializeFlags};
282282
/// # use cryptoki::object::{Attribute, AttributeType, CertificateType, ObjectClass, ObjectHandle};
283283
/// #
284284
/// # let mut client = Pkcs11::new(
285285
/// # std::env::var("TEST_PKCS11_MODULE")
286286
/// # .unwrap_or_else(|_| "/usr/local/lib/softhsm/libsofthsm2.so".to_string()),
287287
/// # )?;
288-
/// # client.initialize(cryptoki::context::CInitializeArgs::OsThreads)?;
288+
/// # client.initialize(CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK))?;
289289
/// #
290290
/// # // Use the first slot
291291
/// # let slot = client.get_all_slots()?[0];
@@ -393,7 +393,7 @@ impl Session {
393393
///
394394
/// ```no_run
395395
/// use cryptoki::context::Pkcs11;
396-
/// use cryptoki::context::CInitializeArgs;
396+
/// use cryptoki::context::{CInitializeArgs, CInitializeFlags};
397397
/// use cryptoki::object::AttributeType;
398398
/// use cryptoki::session::UserType;
399399
/// use cryptoki::types::AuthPin;
@@ -406,7 +406,7 @@ impl Session {
406406
/// )
407407
/// .unwrap();
408408
///
409-
/// pkcs11.initialize(CInitializeArgs::OsThreads).unwrap();
409+
/// pkcs11.initialize(CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK)).unwrap();
410410
/// let slot = pkcs11.get_slots_with_token().unwrap().remove(0);
411411
///
412412
/// let session = pkcs11.open_ro_session(slot).unwrap();

cryptoki/tests/basic.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use crate::common::{
66
get_firmware_version, get_pkcs11, is_fips, is_kryoptic, is_softhsm, SO_PIN, USER_PIN,
77
};
88
use common::init_pins;
9-
use cryptoki::context::Function;
9+
use cryptoki::context::{CInitializeFlags, Function};
1010
use cryptoki::error::{Error, RvError};
1111
use cryptoki::mechanism::aead::{GcmMessageParams, GcmParams, GeneratorFunction};
1212
use cryptoki::mechanism::eddsa::{EddsaParams, EddsaSignatureScheme};
@@ -1782,14 +1782,16 @@ fn is_initialized_test() {
17821782
);
17831783

17841784
// initialize the library
1785-
pkcs11.initialize(CInitializeArgs::OsThreads).unwrap();
1785+
pkcs11
1786+
.initialize(CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK))
1787+
.unwrap();
17861788

17871789
assert!(
17881790
pkcs11.is_initialized(),
17891791
"Context was not marked as initialized"
17901792
);
17911793

1792-
match pkcs11.initialize(CInitializeArgs::OsThreads) {
1794+
match pkcs11.initialize(CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK)) {
17931795
Err(Error::AlreadyInitialized) => (),
17941796
Err(e) => panic!("Got unexpected error when initializing: {e}"),
17951797
Ok(()) => panic!("Initializing twice should not have been allowed"),
@@ -1813,7 +1815,9 @@ fn test_clone_initialize() {
18131815
!clone.is_initialized(),
18141816
"Before initialize() the clone should not be initialized"
18151817
);
1816-
pkcs11.initialize(CInitializeArgs::OsThreads).unwrap();
1818+
pkcs11
1819+
.initialize(CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK))
1820+
.unwrap();
18171821
assert!(
18181822
pkcs11.is_initialized(),
18191823
"After initialize() it should be initialized"

cryptoki/tests/common/mod.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Copyright 2021 Contributors to the Parsec project.
22
// SPDX-License-Identifier: Apache-2.0
3-
use cryptoki::context::{CInitializeArgs, Pkcs11};
3+
use cryptoki::context::{CInitializeArgs, CInitializeFlags, Pkcs11};
44
use cryptoki::object::{Attribute, ObjectClass};
55
use cryptoki::session::{Session, UserType};
66
use cryptoki::slot::Slot;
@@ -45,7 +45,9 @@ pub fn init_pins() -> (Pkcs11, Slot) {
4545
let pkcs11 = get_pkcs11();
4646

4747
// initialize the library
48-
pkcs11.initialize(CInitializeArgs::OsThreads).unwrap();
48+
pkcs11
49+
.initialize(CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK))
50+
.unwrap();
4951

5052
// find a slot, get the first one
5153
let slot = pkcs11.get_slots_with_token().unwrap().remove(0);

0 commit comments

Comments
 (0)