| 1 |
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 2 |
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 3 |
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 4 |
// option. This file may not be copied, modified, or distributed |
| 5 |
// except according to those terms. |
| 6 |
|
| 7 |
use std::{ |
| 8 |
cell::RefCell, |
| 9 |
fmt::{self, Debug, Formatter}, |
| 10 |
ops::{Deref, DerefMut}, |
| 11 |
os::raw::c_uint, |
| 12 |
ptr::null_mut, |
| 13 |
slice::Iter as SliceIter, |
| 14 |
}; |
| 15 |
|
| 16 |
use neqo_common::hex_with_len; |
| 17 |
|
| 18 |
use crate::{ |
| 19 |
err::{secstatus_to_res, Error, Res}, |
| 20 |
null_safe_slice, |
| 21 |
}; |
| 22 |
|
| 23 |
#[expect( |
| 24 |
dead_code, |
| 25 |
non_snake_case, |
| 26 |
non_upper_case_globals, |
| 27 |
non_camel_case_types, |
| 28 |
clippy::unreadable_literal, |
| 29 |
reason = "For included bindgen code." |
| 30 |
)] |
| 31 |
mod nss_p11 { |
| 32 |
include!(concat!(env!("OUT_DIR"), "/nss_p11.rs")); |
| 33 |
} |
| 34 |
|
| 35 |
pub use nss_p11::*; |
| 36 |
|
| 37 |
#[macro_export] |
| 38 |
macro_rules! scoped_ptr { |
| 39 |
($scoped:ident, $target:ty, $dtor:path) => { |
| 40 |
pub struct $scoped { |
| 41 |
ptr: *mut $target, |
| 42 |
} |
| 43 |
|
| 44 |
impl $scoped { |
| 45 |
/// Create a new instance of `$scoped` from a pointer. |
| 46 |
/// |
| 47 |
/// # Errors |
| 48 |
/// |
| 49 |
/// When passed a null pointer generates an error. |
| 50 |
#[allow( |
| 51 |
clippy::allow_attributes, |
| 52 |
dead_code, |
| 53 |
reason = "False positive; is used in code calling the macro." |
| 54 |
)] |
| 55 |
pub fn from_ptr(ptr: *mut $target) -> Result<Self, $crate::err::Error> { |
| 56 |
if ptr.is_null() { |
| 57 |
Err($crate::err::Error::last_nss_error()) |
| 58 |
} else { |
| 59 |
Ok(Self { ptr }) |
| 60 |
} |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
impl Deref for $scoped { |
| 65 |
type Target = *mut $target; |
| 66 |
fn deref(&self) -> &*mut $target { |
| 67 |
&self.ptr |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
impl DerefMut for $scoped { |
| 72 |
fn deref_mut(&mut self) -> &mut *mut $target { |
| 73 |
&mut self.ptr |
| 74 |
} |
| 75 |
} |
| 76 |
|
| 77 |
impl Drop for $scoped { |
| 78 |
fn drop(&mut self) { |
| 79 |
unsafe { _ = $dtor(self.ptr) }; |
| 80 |
} |
| 81 |
} |
| 82 |
}; |
| 83 |
} |
| 84 |
|
| 85 |
scoped_ptr!(Certificate, CERTCertificate, CERT_DestroyCertificate); |
| 86 |
scoped_ptr!(PublicKey, SECKEYPublicKey, SECKEY_DestroyPublicKey); |
| 87 |
|
| 88 |
impl PublicKey { |
| 89 |
/// Get the HPKE serialization of the public key. |
| 90 |
/// |
| 91 |
/// # Errors |
| 92 |
/// |
| 93 |
/// When the key cannot be exported, which can be because the type is not supported. |
| 94 |
/// |
| 95 |
/// # Panics |
| 96 |
/// |
| 97 |
/// When keys are too large to fit in `c_uint/usize`. So only on programming error. |
| 98 |
pub fn key_data(&self) -> Res<Vec<u8>> { |
| 99 |
let mut buf = vec![0; 100]; |
| 100 |
let mut len: c_uint = 0; |
| 101 |
secstatus_to_res(unsafe { |
| 102 |
PK11_HPKE_Serialize( |
| 103 |
**self, |
| 104 |
buf.as_mut_ptr(), |
| 105 |
&mut len, |
| 106 |
c_uint::try_from(buf.len())?, |
| 107 |
) |
| 108 |
})?; |
| 109 |
buf.truncate(usize::try_from(len)?); |
| 110 |
Ok(buf) |
| 111 |
} |
| 112 |
} |
| 113 |
|
| 114 |
impl Clone for PublicKey { |
| 115 |
fn clone(&self) -> Self { |
| 116 |
let ptr = unsafe { SECKEY_CopyPublicKey(self.ptr) }; |
| 117 |
assert!(!ptr.is_null()); |
| 118 |
Self { ptr } |
| 119 |
} |
| 120 |
} |
| 121 |
|
| 122 |
impl Debug for PublicKey { |
| 123 |
fn fmt(&self, f: &mut Formatter) -> fmt::Result { |
| 124 |
if let Ok(b) = self.key_data() { |
| 125 |
write!(f, "PublicKey {}", hex_with_len(b)) |
| 126 |
} else { |
| 127 |
write!(f, "Opaque PublicKey") |
| 128 |
} |
| 129 |
} |
| 130 |
} |
| 131 |
|
| 132 |
scoped_ptr!(PrivateKey, SECKEYPrivateKey, SECKEY_DestroyPrivateKey); |
| 133 |
|
| 134 |
impl PrivateKey { |
| 135 |
/// Get the bits of the private key. |
| 136 |
/// |
| 137 |
/// # Errors |
| 138 |
/// |
| 139 |
/// When the key cannot be exported, which can be because the type is not supported |
| 140 |
/// or because the key data cannot be extracted from the PKCS#11 module. |
| 141 |
/// |
| 142 |
/// # Panics |
| 143 |
/// |
| 144 |
/// When the values are too large to fit. So never. |
| 145 |
pub fn key_data(&self) -> Res<Vec<u8>> { |
| 146 |
let mut key_item = Item::make_empty(); |
| 147 |
secstatus_to_res(unsafe { |
| 148 |
PK11_ReadRawAttribute( |
| 149 |
PK11ObjectType::PK11_TypePrivKey, |
| 150 |
(**self).cast(), |
| 151 |
CK_ATTRIBUTE_TYPE::from(CKA_VALUE), |
| 152 |
&mut key_item, |
| 153 |
) |
| 154 |
})?; |
| 155 |
let slc = unsafe { null_safe_slice(key_item.data, key_item.len) }; |
| 156 |
let key = Vec::from(slc); |
| 157 |
// The data that `key_item` refers to needs to be freed, but we can't |
| 158 |
// use the scoped `Item` implementation. This is OK as long as nothing |
| 159 |
// panics between `PK11_ReadRawAttribute` succeeding and here. |
| 160 |
unsafe { |
| 161 |
SECITEM_FreeItem(&mut key_item, PRBool::from(false)); |
| 162 |
} |
| 163 |
Ok(key) |
| 164 |
} |
| 165 |
} |
| 166 |
unsafe impl Send for PrivateKey {} |
| 167 |
|
| 168 |
impl Clone for PrivateKey { |
| 169 |
fn clone(&self) -> Self { |
| 170 |
let ptr = unsafe { SECKEY_CopyPrivateKey(self.ptr) }; |
| 171 |
assert!(!ptr.is_null()); |
| 172 |
Self { ptr } |
| 173 |
} |
| 174 |
} |
| 175 |
|
| 176 |
impl Debug for PrivateKey { |
| 177 |
fn fmt(&self, f: &mut Formatter) -> fmt::Result { |
| 178 |
if let Ok(b) = self.key_data() { |
| 179 |
write!(f, "PrivateKey {}", hex_with_len(b)) |
| 180 |
} else { |
| 181 |
write!(f, "Opaque PrivateKey") |
| 182 |
} |
| 183 |
} |
| 184 |
} |
| 185 |
|
| 186 |
scoped_ptr!(Slot, PK11SlotInfo, PK11_FreeSlot); |
| 187 |
|
| 188 |
impl Slot { |
| 189 |
pub fn internal() -> Res<Self> { |
| 190 |
let p = unsafe { PK11_GetInternalSlot() }; |
| 191 |
Self::from_ptr(p) |
| 192 |
} |
| 193 |
} |
| 194 |
|
| 195 |
scoped_ptr!(SymKey, PK11SymKey, PK11_FreeSymKey); |
| 196 |
|
| 197 |
impl SymKey { |
| 198 |
/// You really don't want to use this. |
| 199 |
/// |
| 200 |
/// # Errors |
| 201 |
/// |
| 202 |
/// Internal errors in case of failures in NSS. |
| 203 |
pub fn as_bytes(&self) -> Res<&[u8]> { |
| 204 |
secstatus_to_res(unsafe { PK11_ExtractKeyValue(self.ptr) })?; |
| 205 |
|
| 206 |
let key_item = unsafe { PK11_GetKeyData(self.ptr) }; |
| 207 |
// This is accessing a value attached to the key, so we can treat this as a borrow. |
| 208 |
match unsafe { key_item.as_mut() } { |
| 209 |
None => Err(Error::InternalError), |
| 210 |
Some(key) => Ok(unsafe { null_safe_slice(key.data, key.len) }), |
| 211 |
} |
| 212 |
} |
| 213 |
} |
| 214 |
|
| 215 |
impl Clone for SymKey { |
| 216 |
fn clone(&self) -> Self { |
| 217 |
let ptr = unsafe { PK11_ReferenceSymKey(self.ptr) }; |
| 218 |
assert!(!ptr.is_null()); |
| 219 |
Self { ptr } |
| 220 |
} |
| 221 |
} |
| 222 |
|
| 223 |
impl Debug for SymKey { |
| 224 |
fn fmt(&self, f: &mut Formatter) -> fmt::Result { |
| 225 |
if let Ok(b) = self.as_bytes() { |
| 226 |
write!(f, "SymKey {}", hex_with_len(b)) |
| 227 |
} else { |
| 228 |
write!(f, "Opaque SymKey") |
| 229 |
} |
| 230 |
} |
| 231 |
} |
| 232 |
|
| 233 |
impl Default for SymKey { |
| 234 |
fn default() -> Self { |
| 235 |
Self { ptr: null_mut() } |
| 236 |
} |
| 237 |
} |
| 238 |
|
| 239 |
unsafe fn destroy_pk11_context(ctxt: *mut PK11Context) { |
| 240 |
PK11_DestroyContext(ctxt, PRBool::from(true)); |
| 241 |
} |
| 242 |
scoped_ptr!(Context, PK11Context, destroy_pk11_context); |
| 243 |
|
| 244 |
unsafe fn destroy_secitem(item: *mut SECItem) { |
| 245 |
SECITEM_FreeItem(item, PRBool::from(true)); |
| 246 |
} |
| 247 |
scoped_ptr!(Item, SECItem, destroy_secitem); |
| 248 |
|
| 249 |
impl AsRef<[u8]> for SECItem { |
| 250 |
fn as_ref(&self) -> &[u8] { |
| 251 |
unsafe { null_safe_slice(self.data, self.len) } |
| 252 |
} |
| 253 |
} |
| 254 |
|
| 255 |
impl Item { |
| 256 |
/// Create a wrapper for a slice of this object. |
| 257 |
/// Creating this object is technically safe, but using it is extremely dangerous. |
| 258 |
/// Minimally, it can only be passed as a `const SECItem*` argument to functions, |
| 259 |
/// or those that treat their argument as `const`. |
| 260 |
pub fn wrap(buf: &[u8]) -> Res<SECItem> { |
| 261 |
Ok(SECItem { |
| 262 |
type_: SECItemType::siBuffer, |
| 263 |
data: buf.as_ptr().cast_mut(), |
| 264 |
len: c_uint::try_from(buf.len())?, |
| 265 |
}) |
| 266 |
} |
| 267 |
|
| 268 |
/// Create a wrapper for a struct. |
| 269 |
/// Creating this object is technically safe, but using it is extremely dangerous. |
| 270 |
/// Minimally, it can only be passed as a `const SECItem*` argument to functions, |
| 271 |
/// or those that treat their argument as `const`. |
| 272 |
pub fn wrap_struct<T>(v: &T) -> Res<SECItem> { |
| 273 |
let data: *const T = v; |
| 274 |
Ok(SECItem { |
| 275 |
type_: SECItemType::siBuffer, |
| 276 |
data: data.cast_mut().cast(), |
| 277 |
len: c_uint::try_from(size_of::<T>())?, |
| 278 |
}) |
| 279 |
} |
| 280 |
|
| 281 |
/// Make an empty `SECItem` for passing as a mutable `SECItem*` argument. |
| 282 |
pub const fn make_empty() -> SECItem { |
| 283 |
SECItem { |
| 284 |
type_: SECItemType::siBuffer, |
| 285 |
data: null_mut(), |
| 286 |
len: 0, |
| 287 |
} |
| 288 |
} |
| 289 |
} |
| 290 |
|
| 291 |
unsafe fn destroy_secitem_array(array: *mut SECItemArray) { |
| 292 |
SECITEM_FreeArray(array, PRBool::from(true)); |
| 293 |
} |
| 294 |
scoped_ptr!(ItemArray, SECItemArray, destroy_secitem_array); |
| 295 |
|
| 296 |
impl<'a> IntoIterator for &'a ItemArray { |
| 297 |
type Item = &'a [u8]; |
| 298 |
type IntoIter = ItemArrayIterator<'a>; |
| 299 |
fn into_iter(self) -> Self::IntoIter { |
| 300 |
Self::IntoIter { |
| 301 |
iter: AsRef::<[SECItem]>::as_ref(self).iter(), |
| 302 |
} |
| 303 |
} |
| 304 |
} |
| 305 |
|
| 306 |
impl AsRef<[SECItem]> for ItemArray { |
| 307 |
fn as_ref(&self) -> &[SECItem] { |
| 308 |
unsafe { null_safe_slice((*self.ptr).items, (*self.ptr).len) } |
| 309 |
} |
| 310 |
} |
| 311 |
|
| 312 |
pub struct ItemArrayIterator<'a> { |
| 313 |
iter: SliceIter<'a, SECItem>, |
| 314 |
} |
| 315 |
|
| 316 |
impl<'a> Iterator for ItemArrayIterator<'a> { |
| 317 |
type Item = &'a [u8]; |
| 318 |
fn next(&mut self) -> Option<&'a [u8]> { |
| 319 |
self.iter.next().map(AsRef::<[u8]>::as_ref) |
| 320 |
} |
| 321 |
} |
| 322 |
|
| 323 |
#[cfg(feature = "disable-random")] |
| 324 |
thread_local! { |
| 325 |
static CURRENT_VALUE: std::cell::Cell<u8> = const { std::cell::Cell::new(0) }; |
| 326 |
} |
| 327 |
|
| 328 |
#[cfg(feature = "disable-random")] |
| 329 |
/// Fill a buffer with a predictable sequence of bytes. |
| 330 |
pub fn randomize<B: AsMut<[u8]>>(mut buf: B) -> B { |
| 331 |
let m_buf = buf.as_mut(); |
| 332 |
for v in m_buf.iter_mut() { |
| 333 |
*v = CURRENT_VALUE.get(); |
| 334 |
CURRENT_VALUE.set(v.wrapping_add(1)); |
| 335 |
} |
| 336 |
buf |
| 337 |
} |
| 338 |
|
| 339 |
/// Fill a buffer with randomness. |
| 340 |
/// |
| 341 |
/// # Panics |
| 342 |
/// |
| 343 |
/// When `size` is too large or NSS fails. |
| 344 |
#[cfg(not(feature = "disable-random"))] |
| 345 |
pub fn randomize<B: AsMut<[u8]>>(mut buf: B) -> B { |
| 346 |
let m_buf = buf.as_mut(); |
| 347 |
let len = std::os::raw::c_int::try_from(m_buf.len()).expect("usize fits into c_int"); |
| 348 |
secstatus_to_res(unsafe { PK11_GenerateRandom(m_buf.as_mut_ptr(), len) }).expect("NSS failed"); |
| 349 |
buf |
| 350 |
} |
| 351 |
|
| 352 |
struct RandomCache { |
| 353 |
cache: [u8; Self::SIZE], |
| 354 |
used: usize, |
| 355 |
} |
| 356 |
|
| 357 |
impl RandomCache { |
| 358 |
const SIZE: usize = 256; |
| 359 |
const CUTOFF: usize = 32; |
| 360 |
|
| 361 |
const fn new() -> Self { |
| 362 |
Self { |
| 363 |
cache: [0; Self::SIZE], |
| 364 |
used: Self::SIZE, |
| 365 |
} |
| 366 |
} |
| 367 |
|
| 368 |
fn randomize<B: AsMut<[u8]>>(&mut self, mut buf: B) -> B { |
| 369 |
let m_buf = buf.as_mut(); |
| 370 |
debug_assert!(m_buf.len() <= Self::CUTOFF); |
| 371 |
let avail = Self::SIZE - self.used; |
| 372 |
if m_buf.len() <= avail { |
| 373 |
m_buf.copy_from_slice(&self.cache[self.used..self.used + m_buf.len()]); |
| 374 |
self.used += m_buf.len(); |
| 375 |
} else { |
| 376 |
if avail > 0 { |
| 377 |
m_buf[..avail].copy_from_slice(&self.cache[self.used..]); |
| 378 |
} |
| 379 |
randomize(&mut self.cache[..]); |
| 380 |
self.used = m_buf.len() - avail; |
| 381 |
m_buf[avail..].copy_from_slice(&self.cache[..self.used]); |
| 382 |
} |
| 383 |
buf |
| 384 |
} |
| 385 |
} |
| 386 |
|
| 387 |
/// Generate a randomized array. |
| 388 |
/// |
| 389 |
/// # Panics |
| 390 |
/// |
| 391 |
/// When `size` is too large or NSS fails. |
| 392 |
#[must_use] |
| 393 |
pub fn random<const N: usize>() -> [u8; N] { |
| 394 |
thread_local!(static CACHE: RefCell<RandomCache> = const { RefCell::new(RandomCache::new()) }); |
| 395 |
|
| 396 |
let buf = [0; N]; |
| 397 |
if N <= RandomCache::CUTOFF { |
| 398 |
CACHE.with_borrow_mut(|c| c.randomize(buf)) |
| 399 |
} else { |
| 400 |
randomize(buf) |
| 401 |
} |
| 402 |
} |
| 403 |
|
| 404 |
#[cfg(test)] |
| 405 |
mod test { |
| 406 |
use test_fixture::fixture_init; |
| 407 |
|
| 408 |
use super::RandomCache; |
| 409 |
use crate::random; |
| 410 |
|
| 411 |
#[cfg(not(feature = "disable-random"))] |
| 412 |
#[test] |
| 413 |
fn randomness() { |
| 414 |
use crate::randomize; |
| 415 |
|
| 416 |
fixture_init(); |
| 417 |
// If any of these ever fail, there is either a bug, or it's time to buy a lottery ticket. |
| 418 |
assert_ne!(random::<16>(), randomize([0; 16])); |
| 419 |
assert_ne!([0; 16], random::<16>()); |
| 420 |
assert_ne!([0; 64], random::<64>()); |
| 421 |
} |
| 422 |
|
| 423 |
#[test] |
| 424 |
fn cache_random_lengths() { |
| 425 |
const ZERO: [u8; 256] = [0; 256]; |
| 426 |
|
| 427 |
fixture_init(); |
| 428 |
let mut cache = RandomCache::new(); |
| 429 |
let mut buf = [0; 256]; |
| 430 |
let bits = usize::BITS - (RandomCache::CUTOFF - 1).leading_zeros(); |
| 431 |
let mask = 0xff >> (u8::BITS - bits); |
| 432 |
|
| 433 |
for _ in 0..100 { |
| 434 |
let len = loop { |
| 435 |
let len = usize::from(random::<1>()[0] & mask) + 1; |
| 436 |
if len <= RandomCache::CUTOFF { |
| 437 |
break len; |
| 438 |
} |
| 439 |
}; |
| 440 |
buf.fill(0); |
| 441 |
if len >= 16 { |
| 442 |
assert_ne!(&cache.randomize(&mut buf[..len])[..len], &ZERO[..len]); |
| 443 |
} |
| 444 |
} |
| 445 |
} |
| 446 |
} |