Skip to content

Feat: Add NIST SP800-108 KDF mechanisms #257

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

Open
wants to merge 22 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
f0a2974
Added mechanisms for NIST SP 800-108 KDF and their parameters
jacobprudhomme Apr 4, 2025
543dd75
Added derive_keys function to get additional derived keys from mechan…
jacobprudhomme Apr 8, 2025
0641873
Restructured design to actually be able to reference original memory …
jacobprudhomme Apr 9, 2025
799469a
Qualified all cryptoki_sys imports as a stylistic choice
jacobprudhomme Apr 9, 2025
5f7a922
Simplified CounterFormat and DkmLengthFormat wrapper structs
jacobprudhomme Apr 9, 2025
8258b7b
Added support for not providing additional keys to derive
jacobprudhomme Apr 9, 2025
d2b09c4
Fixed issue where underlying derived key structs were being formed in…
jacobprudhomme Apr 10, 2025
3cb3c34
Cleaned up code with implementation of From for DerivedKey
jacobprudhomme Apr 11, 2025
8ac48ed
Removed additional types to match the PKCS#11 spec 1-to-1
jacobprudhomme Apr 11, 2025
f1a15f7
Changed paradigm for how additional derived keys should be retrieved …
jacobprudhomme Apr 11, 2025
6cd230f
Improved doc comments
jacobprudhomme Apr 11, 2025
3a6d286
Improved comments and expect() error messages
jacobprudhomme Apr 11, 2025
8a9a30a
Added tests for NIST SP800-108 KDF (KBKDF)
jacobprudhomme Apr 11, 2025
91cd39f
Removed all cryptoki_sys qualifiers
jacobprudhomme Apr 14, 2025
1d2fca8
Renamed `DkmLengthMethod` to `KbkdfDkmLengthMethod` for consistency
jacobprudhomme Apr 14, 2025
4e6be13
Removed unused tests I forgot about
jacobprudhomme Apr 14, 2025
56a113d
Made lint fixes
jacobprudhomme Apr 14, 2025
d0a7c87
Improved doc comments
jacobprudhomme Apr 15, 2025
53f116f
Made spelling fix
jacobprudhomme Apr 22, 2025
18de278
Changed to `NonZeroUsize` for defining bit-width of `CounterFormat` a…
jacobprudhomme Apr 22, 2025
e34b4b6
Split out tests for different modes of the SP800-108 KDF
jacobprudhomme Apr 22, 2025
bea29ba
Added mutability marker to `PhantomData` sitting inside KDF params, t…
jacobprudhomme Apr 22, 2025
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
374 changes: 374 additions & 0 deletions cryptoki/src/mechanism/kbkdf.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,374 @@
// Copyright 2025 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! Mechanisms of NIST key-based key derive functions (SP 800-108, informally KBKDF)
//! See: <https://docs.oasis-open.org/pkcs11/pkcs11-curr/v3.0/os/pkcs11-curr-v3.0-os.html#_Toc30061446>

use core::{convert::TryInto, marker::PhantomData, pin::Pin, ptr};
use std::num::NonZeroUsize;

use cryptoki_sys::{
CK_ATTRIBUTE, CK_ATTRIBUTE_PTR, CK_DERIVED_KEY, CK_DERIVED_KEY_PTR, CK_INVALID_HANDLE,
CK_OBJECT_HANDLE, CK_OBJECT_HANDLE_PTR, CK_PRF_DATA_PARAM, CK_PRF_DATA_PARAM_PTR,
CK_SP800_108_BYTE_ARRAY, CK_SP800_108_COUNTER, CK_SP800_108_COUNTER_FORMAT,
CK_SP800_108_DKM_LENGTH, CK_SP800_108_DKM_LENGTH_FORMAT, CK_SP800_108_DKM_LENGTH_SUM_OF_KEYS,
CK_SP800_108_DKM_LENGTH_SUM_OF_SEGMENTS, CK_SP800_108_FEEDBACK_KDF_PARAMS,
CK_SP800_108_ITERATION_VARIABLE, CK_SP800_108_KDF_PARAMS, CK_ULONG,
};

use crate::object::{Attribute, ObjectHandle};

use super::MechanismType;

/// Endianness of byte representation of data.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Endianness {
/// Little endian.
Little,
/// Big endian.
Big,
}

/// Defines encoding format for a counter value.
///
/// This structure wraps a `CK_SP800_108_COUNTER_FORMAT` structure.
#[derive(Debug, Clone, Copy)]
#[repr(transparent)]
pub struct KbkdfCounterFormat(CK_SP800_108_COUNTER_FORMAT);

impl KbkdfCounterFormat {
/// Construct encoding format for KDF's internal counter variable.
///
/// # Arguments
///
/// * `endianness` - The endianness of the counter's bit representation.
///
/// * `width_in_bits` - The number of bits used to represent the counter value.
pub fn new(endianness: Endianness, width_in_bits: NonZeroUsize) -> Self {
Self(CK_SP800_108_COUNTER_FORMAT {
bLittleEndian: (endianness == Endianness::Little).into(),
ulWidthInBits: width_in_bits
.get()
.try_into()
.expect("bit width of KBKDF internal counter does not fit in CK_ULONG"),
})
}
}

/// Method for calculating length of DKM (derived key material).
///
/// Corresponds to CK_SP800_108_DKM_LENGTH_METHOD.
#[derive(Debug, Clone, Copy)]
pub enum KbkdfDkmLengthMethod {
/// Sum of length of all keys derived by given invocation of KDF.
SumOfKeys,
/// Sum of length of all segments of output produced by PRF in given invocation of KDF.
SumOfSegments,
}

/// Defines encoding format for DKM (derived key material).
///
/// This structure wraps a `CK_SP800_108_DKM_LENGTH_FORMAT` structure.
#[derive(Debug, Clone, Copy)]
#[repr(transparent)]
pub struct KbkdfDkmLengthFormat(CK_SP800_108_DKM_LENGTH_FORMAT);

impl KbkdfDkmLengthFormat {
/// Construct encoding format for length value of DKM (derived key material) from KDF.
///
/// # Arguments
///
/// * `dkm_length_method` - The method used to calculate the DKM length value.
///
/// * `endianness` - The endianness of the DKM length value's bit representation.
///
/// * `width_in_bits` - The number of bits used to represent the DKM length value.
pub fn new(
dkm_length_method: KbkdfDkmLengthMethod,
endianness: Endianness,
width_in_bits: NonZeroUsize,
) -> Self {
Self(CK_SP800_108_DKM_LENGTH_FORMAT {
dkmLengthMethod: match dkm_length_method {
KbkdfDkmLengthMethod::SumOfKeys => CK_SP800_108_DKM_LENGTH_SUM_OF_KEYS,
KbkdfDkmLengthMethod::SumOfSegments => CK_SP800_108_DKM_LENGTH_SUM_OF_SEGMENTS,
},
bLittleEndian: (endianness == Endianness::Little).into(),
ulWidthInBits: width_in_bits
.get()
.try_into()
.expect("bit width of KBKDF DKM length value does not fit in CK_ULONG"),
})
}
}

/// The type of a segment of input data for the PRF, for a KBKDF operating in feedback- or double pipeline-mode.
#[derive(Debug, Clone, Copy)]
pub enum PrfDataParamType<'a> {
/// Identifies location of predefined iteration variable in constructed PRF input data.
///
/// For counter-mode, this must contain a [`KbkdfCounterFormat`].
/// For feedback- and double-pipeline mode, this must contain [`None`].
IterationVariable(Option<&'a KbkdfCounterFormat>),
/// Identifies location of counter in constructed PRF input data.
Counter(&'a KbkdfCounterFormat),
/// Identifies location of DKM (derived key material) length value in constructed PRF input data.
DkmLength(&'a KbkdfDkmLengthFormat),
/// Identifies location and value of byte array of data in constructed PRF input data.
ByteArray(&'a [u8]),
}

/// A segment of input data for the PRF, to be used to construct a sequence of input.
///
/// This structure wraps a `CK_PRF_DATA_PARAM` structure.
///
/// * [`PrfDataParamType::IterationVariable`] is required for the KDF in all modes.
/// * In counter-mode, [`PrfDataParamType::IterationVariable`] must contain [`KbkdfCounterFormat`].
/// In feedback- and double pipeline-mode, it must contain [`None`].
/// * [`PrfDataParamType::Counter`] must not be present in counter-mode, and can be present at most
/// once in feedback- and double-pipeline modes.
/// * [`PrfDataParamType::DkmLength`] can be present at most once, in any mode.
/// * [`PrfDataParamType::ByteArray`] can be present any amount of times, in any mode.
#[derive(Debug, Clone, Copy)]
#[repr(transparent)]
pub struct PrfDataParam<'a> {
inner: CK_PRF_DATA_PARAM,
/// Marker type to ensure we don't outlive the data
_marker: PhantomData<&'a [u8]>,
}

impl<'a> PrfDataParam<'a> {
/// Construct data parameter for input of the PRF internal to the KBKDF.
///
/// # Arguments
///
/// * `type_` - The specific type and parameters for the data parameter.
pub fn new(type_: PrfDataParamType<'a>) -> Self {
Self {
inner: match type_ {
PrfDataParamType::IterationVariable(None) => CK_PRF_DATA_PARAM {
type_: CK_SP800_108_ITERATION_VARIABLE,
pValue: ptr::null_mut(),
ulValueLen: 0,
},
PrfDataParamType::IterationVariable(Some(counter_format)) => CK_PRF_DATA_PARAM {
type_: CK_SP800_108_ITERATION_VARIABLE,
pValue: counter_format as *const _ as *mut _,
ulValueLen: size_of::<CK_SP800_108_COUNTER_FORMAT>() as CK_ULONG,
},
PrfDataParamType::Counter(counter_format) => CK_PRF_DATA_PARAM {
type_: CK_SP800_108_COUNTER,
pValue: counter_format as *const _ as *mut _,
ulValueLen: size_of::<CK_SP800_108_COUNTER_FORMAT>() as CK_ULONG,
},
PrfDataParamType::DkmLength(dkm_length_format) => CK_PRF_DATA_PARAM {
type_: CK_SP800_108_DKM_LENGTH,
pValue: dkm_length_format as *const _ as *mut _,
ulValueLen: size_of::<CK_SP800_108_DKM_LENGTH_FORMAT>() as CK_ULONG,
},
PrfDataParamType::ByteArray(data) => CK_PRF_DATA_PARAM {
type_: CK_SP800_108_BYTE_ARRAY,
pValue: data.as_ptr() as *mut _,
ulValueLen: data
.len()
.try_into()
.expect("length of PRF data parameter does not fit in CK_ULONG"),
},
},
_marker: PhantomData,
}
}
}

/// Container for information on an additional key to be derived.
#[derive(Debug)]
pub struct DerivedKey {
template: Pin<Box<[CK_ATTRIBUTE]>>,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just out of curiosity why this is pinned?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Essentially I just wanted to include some visual hint to the programmer that it's crucial that the address of this data doesn't change (because of the fact that we pass pointers into it to the backend). I know this is redundant since Box guarantees this anyway, but I thought it would be nice to make this explicit. If you think it's just noise or could be confusing, I'm happy to remove it

handle: CK_OBJECT_HANDLE,
}

impl DerivedKey {
/// Construct template for additional key to be derived by KDF.
///
/// # Arguments
///
/// * `template` - The template for the key to be derived.
pub fn new(template: &[Attribute]) -> Self {
let template: Box<[CK_ATTRIBUTE]> = template.iter().map(Into::into).collect();
let template = Pin::new(template);

Self {
template,
handle: CK_INVALID_HANDLE,
}
}

/// Return handle for derived key, if it has been created yet
pub fn handle(&self) -> Option<ObjectHandle> {
if self.handle == CK_INVALID_HANDLE {
None
} else {
Some(ObjectHandle::new(self.handle))
}
}
}

impl From<&mut DerivedKey> for CK_DERIVED_KEY {
fn from(value: &mut DerivedKey) -> Self {
CK_DERIVED_KEY {
pTemplate: value.template.as_ptr() as CK_ATTRIBUTE_PTR,
ulAttributeCount: value
.template
.len()
.try_into()
.expect("number of attributes in template does not fit in CK_ULONG"),
phKey: &mut value.handle as CK_OBJECT_HANDLE_PTR,
}
}
}

/// NIST SP 800-108 (aka KBKDF) counter and double pipeline-mode parameters.
///
/// This structure wraps a `CK_SP800_108_KDF_PARAMS` structure.
#[derive(Debug)]
pub struct KbkdfParams<'a> {
/// Holds own data so that we have a contiguous memory region to give to backend
_additional_derived_keys: Option<Pin<Box<[CK_DERIVED_KEY]>>>,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why the underscore?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we don't use this member, the lint check complains without it. It's just an internal member needed to hold the slice of additional key PKCS#11 structs so that it remains valid for the lifetime of the params object (this is a consequence of what I explained in the Design Justifications section of the PR body)


inner: CK_SP800_108_KDF_PARAMS,
/// Marker type to ensure we don't outlive the data
_marker: PhantomData<&'a mut [u8]>,
}

impl<'a> KbkdfParams<'a> {
/// Construct parameters for NIST SP 800-108 KDF (aka KBKDF) pseudorandom function-based key
/// derivation function, in counter or double pipeline-mode.
///
/// # Arguments
///
/// * `prf_mechanism` - The pseudorandom function that underlies the KBKDF operation.
///
/// * `prf_data_params` - The sequence of data segments used as input data for the PRF. Requires at least [`PrfDataParamType::IterationVariable`].
///
/// * `additional_derived_keys` - Any additional keys to be generated by the KDF from the base key.
pub fn new(
prf_mechanism: MechanismType,
prf_data_params: &'a [PrfDataParam<'a>],
additional_derived_keys: Option<&'a mut [DerivedKey]>,
) -> Self {
let mut additional_derived_keys = additional_derived_keys
.map(|keys| {
keys.iter_mut()
.map(Into::into)
.collect::<Box<[CK_DERIVED_KEY]>>()
})
.map(Pin::new);

let inner = CK_SP800_108_KDF_PARAMS {
prfType: prf_mechanism.into(),
ulNumberOfDataParams: prf_data_params
.len()
.try_into()
.expect("number of PRF data parameters does not fit in CK_ULONG"),
pDataParams: prf_data_params.as_ptr() as CK_PRF_DATA_PARAM_PTR,
ulAdditionalDerivedKeys: additional_derived_keys.as_ref().map_or(0, |keys| {
keys.len()
.try_into()
.expect("number of additional derived keys does not fit in CK_ULONG")
}),
pAdditionalDerivedKeys: additional_derived_keys
.as_mut()
.map_or(ptr::null_mut(), |keys| {
keys.as_mut_ptr() as CK_DERIVED_KEY_PTR
}),
};

Self {
_additional_derived_keys: additional_derived_keys,

inner,
_marker: PhantomData,
}
}

pub(crate) fn inner(&self) -> &CK_SP800_108_KDF_PARAMS {
&self.inner
}
}

/// NIST SP 800-108 (aka KBKDF) feedback-mode parameters.
///
/// This structure wraps a `CK_SP800_108_FEEDBACK_KDF_PARAMS` structure.
#[derive(Debug)]
pub struct KbkdfFeedbackParams<'a> {
/// Holds own data so that we have a contiguous memory region to give to backend
_additional_derived_keys: Option<Pin<Box<[CK_DERIVED_KEY]>>>,

inner: CK_SP800_108_FEEDBACK_KDF_PARAMS,
/// Marker type to ensure we don't outlive the data
_marker: PhantomData<&'a mut [u8]>,
}

impl<'a> KbkdfFeedbackParams<'a> {
/// Construct parameters for NIST SP 800-108 KDF (aka KBKDF) pseuderandom function-based key
/// derivation function, in feedback-mode.
///
/// # Arguments
///
/// * `prf_mechanism` - The pseudorandom function that underlies the KBKDF operation.
///
/// * `prf_data_params` - The sequence of data segments used as input data for the PRF. Requires at least [`PrfDataParamType::IterationVariable`].
///
/// * `iv` - The IV to be used for the feedback-mode KDF.
///
/// * `additional_derived_keys` - Any additional keys to be generated by the KDF from the base key.
pub fn new(
prf_mechanism: MechanismType,
prf_data_params: &'a [PrfDataParam<'a>],
iv: Option<&'a [u8]>,
additional_derived_keys: Option<&'a mut [DerivedKey]>,
) -> Self {
let mut additional_derived_keys = additional_derived_keys
.map(|keys| {
keys.iter_mut()
.map(Into::into)
.collect::<Box<[CK_DERIVED_KEY]>>()
})
.map(Pin::new);

let inner = CK_SP800_108_FEEDBACK_KDF_PARAMS {
prfType: prf_mechanism.into(),
ulNumberOfDataParams: prf_data_params
.len()
.try_into()
.expect("number of PRF data parameters does not fit in CK_ULONG"),
pDataParams: prf_data_params.as_ptr() as CK_PRF_DATA_PARAM_PTR,
ulIVLen: iv.map_or(0, |iv| {
iv.len()
.try_into()
.expect("IV length does not fit in CK_ULONG")
}),
pIV: iv.map_or(ptr::null_mut(), |iv| iv.as_ptr() as *mut _),
ulAdditionalDerivedKeys: additional_derived_keys.as_ref().map_or(0, |keys| {
keys.len()
.try_into()
.expect("number of additional derived keys does not fit in CK_ULONG")
}),
pAdditionalDerivedKeys: additional_derived_keys
.as_mut()
.map_or(ptr::null_mut(), |keys| {
keys.as_mut_ptr() as CK_DERIVED_KEY_PTR
}),
};

Self {
_additional_derived_keys: additional_derived_keys,

inner,
_marker: PhantomData,
}
}

pub(crate) fn inner(&self) -> &CK_SP800_108_FEEDBACK_KDF_PARAMS {
&self.inner
}
}
Loading
Loading