Skip to content

Commit

Permalink
Verify CKK_EC_MONTGOMERY private keys on import
Browse files Browse the repository at this point in the history
Signed-off-by: Simo Sorce <[email protected]>
  • Loading branch information
simo5 committed Nov 26, 2024
1 parent 3d7b094 commit e45d489
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 9 deletions.
7 changes: 0 additions & 7 deletions src/ec/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Copyright 2023 - 2024 Simo Sorce, Jakub Jelen
// See LICENSE.txt file for terms

use crate::bytes_attr_not_empty;
use crate::error::{device_error, Error, Result};
use crate::interface::*;
use crate::kasn1::oid::*;
Expand All @@ -22,12 +21,6 @@ pub mod eddsa;
#[cfg(feature = "ec_montgomery")]
pub mod montgomery;

pub fn ec_key_check_import(obj: &mut Object) -> Result<()> {
bytes_attr_not_empty!(obj; CKA_EC_PARAMS);
bytes_attr_not_empty!(obj; CKA_VALUE);
Ok(())
}

// Bit sized for curves
pub const BITS_SECP256R1: usize = 256;
#[allow(dead_code)]
Expand Down
37 changes: 35 additions & 2 deletions src/ec/montgomery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,42 @@ impl ECMontgomeryPrivFactory {

impl ObjectFactory for ECMontgomeryPrivFactory {
fn create(&self, template: &[CK_ATTRIBUTE]) -> Result<Object> {
let mut obj = self.default_object_create(template)?;
let obj = self.default_object_create(template)?;

/* According to PKCS#11 v3.1 6.3.8:
* CKA_EC_PARAMS, Byte array,
* DER-encoding of a Parameters value as defined above (6.3.3?) */
let oid = get_oid_from_obj(&obj).map_err(|e| {
if e.attr_not_found() {
Error::ck_rv_from_error(CKR_TEMPLATE_INCOMPLETE, e)
} else if e.rv() != CKR_ATTRIBUTE_VALUE_INVALID {
Error::ck_rv_from_error(CKR_ATTRIBUTE_VALUE_INVALID, e)
} else {
general_error(e)
}
})?;
match oid {
oid::X25519_OID | oid::X448_OID => (),
_ => return Err(CKR_ATTRIBUTE_VALUE_INVALID)?,
}

ec_key_check_import(&mut obj)?;
/* According to PKCS#11 v3.1 6.3.8:
* CKA_VALUE, BigInteger,
* Private key bytes in little endian order as defined in RFC 7748 */
match obj.get_attr_as_bytes(CKA_VALUE) {
Ok(v) => {
if v.len() != ec_key_size(&oid)? {
return Err(CKR_ATTRIBUTE_VALUE_INVALID)?;
}
}
Err(e) => {
if e.attr_not_found() {
return Err(CKR_TEMPLATE_INCOMPLETE)?;
} else {
return Err(e);
}
}
}

Ok(obj)
}
Expand Down

0 comments on commit e45d489

Please sign in to comment.