Skip to content
Merged
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
18 changes: 18 additions & 0 deletions bindings/bindings.toml
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,9 @@ types = [
"HpkeAeadId",
"HpkeKdfId",
"HpkeKemId",
"PK11AttrFlags",
"PK11SlotListStr",
"PK11SlotListElementStr",
"PK11SymKeyStr",
"SECKEYPrivateKeyStr",
]
Expand All @@ -147,6 +150,7 @@ functions = [
"CERT_GetCertificateDer",
"NSS_SetAlgorithmPolicy",
"PK11_AEADOp",
"PK11_Authenticate",
"PK11_CipherOp",
"PK11_CreateContextBySymKey",
"PK11_Decrypt",
Expand All @@ -160,14 +164,20 @@ functions = [
"PK11_FindCertFromNickname",
"PK11_FindKeyByAnyCert",
"PK11_FreeSlot",
"PK11_FreeSlotList",
"PK11_FreeSymKey",
"PK11_GenerateKeyPairWithOpFlags",
"PK11_GetNextSymKey",
"PK11_GetSymKeyNickname",
"PK11_GenerateKeyPair",
"PK11_GenerateRandom",
"PK11_GetAllTokens",
"PK11_GetBlockSize",
"PK11_GetInternalKeySlot",
"PK11_GetInternalSlot",
"PK11_GetKeyData",
"PK11_GetMechanism",
"PK11_GetTokenName",
"PK11_HashBuf",
"PK11_HPKE_Deserialize",
"PK11_HPKE_ExportSecret",
Expand All @@ -184,10 +194,14 @@ functions = [
"PK11_ImportDERPrivateKeyInfoAndReturnKey",
"PK11_ImportPublicKey",
"PK11_ImportSymKey",
"PK11_ListFixedKeysInSlot",
"PK11_PubDeriveWithKDF",
"PK11_ReadRawAttribute",
"PK11_ReferenceSlot",
"PK11_ReferenceSymKey",
"PK11_SetSymKeyNickname",
"PK11_SignWithMechanism",
"PK11_TokenKeyGenWithFlags",
"PK11_VerifyWithMechanism",
"PK11_WrapPrivKey",
"SECITEM_AllocItem",
Expand Down Expand Up @@ -217,6 +231,7 @@ variables = [
"NSS_USE_ALG_IN_SSL_KX",
"PK11_ATTR_INSENSITIVE",
"PK11_ATTR_PRIVATE",
"PK11_ATTR_TOKEN",
"PK11_ATTR_PUBLIC",
"PK11_ATTR_SENSITIVE",
"PK11_ATTR_SESSION",
Expand All @@ -236,7 +251,9 @@ variables = [
"CKG_NO_GENERATE",
"CKM_AES_GCM",
"CKM_CHACHA20_POLY1305",
"CKF_DECRYPT",
"CKF_DERIVE",
"CKF_ENCRYPT",
"CKM_EC_KEY_PAIR_GEN",
"CK_INVALID_HANDLE",
"CKF_HKDF_SALT_NULL",
Expand All @@ -249,6 +266,7 @@ variables = [
"CKM_SHA256_HMAC",
"CKM_SHA384_HMAC",
"CKM_SHA512_HMAC",
"CKM_AES_KEY_GEN",
"CKM_ECDSA",
"CKM_EDDSA",
]
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub mod ec;
pub mod hash;
pub mod hmac;
pub mod p11;
pub mod pk11_utils;
mod prio;
mod replay;
mod secrets;
Expand Down
94 changes: 92 additions & 2 deletions src/p11.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use std::{
cell::RefCell,
convert::TryFrom as _,
fmt::{self, Debug, Formatter},
os::raw::c_uint,
os::raw::{c_int, c_uint},
ptr::null_mut,
};

Expand Down Expand Up @@ -174,6 +174,96 @@ impl Slot {
pub fn internal() -> Res<Self> {
unsafe { Self::from_ptr(PK11_GetInternalSlot()) }
}

pub fn internal_key_slot() -> Res<Self> {
unsafe { Self::from_ptr(PK11_GetInternalKeySlot()) }
}

#[must_use]
pub fn token_name(&self) -> String {
let name = unsafe { PK11_GetTokenName(self.ptr) };
if name.is_null() {
return String::new();
}
unsafe { std::ffi::CStr::from_ptr(name) }
.to_string_lossy()
.into_owned()
}

pub fn authenticate(&self) -> Res<()> {
secstatus_to_res(unsafe { PK11_Authenticate(self.ptr, PRBool::from(true), null_mut()) })
}

/// Find a persistent symmetric key on this slot by nickname.
/// Returns `None` if no key with the given nickname exists.
#[must_use]
pub fn find_key_by_nickname(&self, nickname: &str) -> Option<SymKey> {
let c_nickname = std::ffi::CString::new(nickname).ok()?;
let ptr = unsafe {
PK11_ListFixedKeysInSlot(self.ptr, c_nickname.as_ptr().cast_mut(), null_mut())
};
if ptr.is_null() {
None
} else {
SymKey::from_ptr(ptr).ok()
}
}

/// Generate a persistent symmetric key on this slot with a nickname.
pub fn generate_token_key(
&self,
mechanism: CK_MECHANISM_TYPE,
key_size: usize,
nickname: &str,
) -> Res<SymKey> {
let key = unsafe {
SymKey::from_ptr(PK11_TokenKeyGenWithFlags(
self.ptr,
mechanism,
null_mut(),
c_int::try_from(key_size).map_err(|_| Error::IntegerOverflow)?,
null_mut(),
CK_FLAGS::from(CKF_ENCRYPT | CKF_DECRYPT),
PK11AttrFlags::from(PK11_ATTR_TOKEN | PK11_ATTR_PRIVATE | PK11_ATTR_SENSITIVE),
null_mut(),
))
}?;
let c_nickname = std::ffi::CString::new(nickname).map_err(|_| Error::InvalidInput)?;
secstatus_to_res(unsafe { PK11_SetSymKeyNickname(*key, c_nickname.as_ptr()) })?;
Ok(key)
}
}

/// Returns all available token slots for the given mechanism.
#[must_use]
pub fn all_token_slots(mechanism: CK_MECHANISM_TYPE) -> Vec<Slot> {
let list = unsafe {
PK11_GetAllTokens(
mechanism,
PRBool::from(false),
PRBool::from(false),
null_mut(),
)
};
if list.is_null() {
return Vec::new();
}
let mut result = Vec::new();
unsafe {
let mut elem = (*list).head;
while !elem.is_null() {
let slot_ptr = (*elem).slot;
if !slot_ptr.is_null() {
PK11_ReferenceSlot(slot_ptr);
if let Ok(slot) = Slot::from_ptr(slot_ptr) {
result.push(slot);
}
}
elem = (*elem).next;
}
PK11_FreeSlotList(list);
}
result
}

// Note: PK11SymKey is internally reference counted
Expand Down Expand Up @@ -249,7 +339,7 @@ pub fn randomize<B: AsMut<[u8]>>(mut buf: B) -> B {
#[cfg(not(feature = "disable-random"))]
pub fn randomize<B: AsMut<[u8]>>(mut buf: B) -> B {
let m_buf = buf.as_mut();
let len = std::os::raw::c_int::try_from(m_buf.len()).expect("usize fits into c_int");
let len = c_int::try_from(m_buf.len()).expect("usize fits into c_int");
secstatus_to_res(unsafe { PK11_GenerateRandom(m_buf.as_mut_ptr(), len) }).expect("NSS failed");
buf
}
Expand Down
123 changes: 123 additions & 0 deletions src/pk11_utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use crate::err::{Error, Res};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pkcs11Uri {
pub token: Option<String>,
}

fn percent_decode(s: &str) -> String {
let mut result = Vec::with_capacity(s.len());
let bytes = s.as_bytes();
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& i + 2 < bytes.len()
&& let Ok(byte) =
u8::from_str_radix(std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or(""), 16)
{
result.push(byte);
i += 3;
continue;
}
result.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&result).into_owned()
}

fn percent_encode(s: &str) -> String {
let mut result = String::with_capacity(s.len());
for b in s.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
result.push(b as char);
}
_ => {
use std::fmt::Write as _;
write!(result, "%{b:02X}").expect("write to String");
}
}
}
result
}

/// Parse a PKCS#11 URI (RFC 7512).
/// Expects the input to start with "pkcs11:".
pub fn parse(uri: &str) -> Res<Pkcs11Uri> {
let path = uri.strip_prefix("pkcs11:").ok_or(Error::InvalidInput)?;

let mut token = None;
for attr in path.split(';') {
if let Some((key, value)) = attr.split_once('=')
&& key == "token"
{
token = Some(percent_decode(value));
}
}

Ok(Pkcs11Uri { token })
}

/// Build a PKCS#11 URI from a token name.
#[must_use]
pub fn build(token_name: &str) -> String {
format!("pkcs11:token={}", percent_encode(token_name))
}

#[cfg(test)]
mod tests {
use test_fixture::fixture_init;

use super::*;

#[test]
fn parse_simple() {
fixture_init();
let uri = parse("pkcs11:token=NSS%20Certificate%20DB").unwrap();
assert_eq!(uri.token.as_deref(), Some("NSS Certificate DB"));
}

#[test]
fn parse_no_token() {
fixture_init();
let uri = parse("pkcs11:manufacturer=Mozilla").unwrap();
assert_eq!(uri.token, None);
}

#[test]
fn parse_multiple_attrs() {
fixture_init();
let uri = parse("pkcs11:token=MyToken;manufacturer=Test;serial=1234").unwrap();
assert_eq!(uri.token.as_deref(), Some("MyToken"));
}

#[test]
fn parse_not_pkcs11() {
fixture_init();
assert!(parse("http://example.com").is_err());
}

#[test]
fn build_uri() {
fixture_init();
assert_eq!(
build("NSS Certificate DB"),
"pkcs11:token=NSS%20Certificate%20DB"
);
}

#[test]
fn roundtrip() {
fixture_init();
let name = "My Token (Test-v2)";
let uri_str = build(name);
let parsed = parse(&uri_str).unwrap();
assert_eq!(parsed.token.as_deref(), Some(name));
}
}
Loading