| 1 |
use super::{ |
| 2 |
super::hpke::{Aead, Kdf, Kem}, |
| 3 |
err::{sec::SEC_ERROR_INVALID_ARGS, secstatus_to_res, Error}, |
| 4 |
p11::{sys, Item, PrivateKey, PublicKey, Slot, SymKey}, |
| 5 |
}; |
| 6 |
use crate::err::Res; |
| 7 |
use log::{log_enabled, trace}; |
| 8 |
use std::{ |
| 9 |
convert::TryFrom, |
| 10 |
ops::Deref, |
| 11 |
os::raw::c_uint, |
| 12 |
ptr::{addr_of_mut, null, null_mut}, |
| 13 |
}; |
| 14 |
|
| 15 |
pub use sys::{HpkeAeadId as AeadId, HpkeKdfId as KdfId, HpkeKemId as KemId}; |
| 16 |
|
| 17 |
/// Configuration for `Hpke`. |
| 18 |
#[derive(Clone, Copy)] |
| 19 |
pub struct Config { |
| 20 |
kem: Kem, |
| 21 |
kdf: Kdf, |
| 22 |
aead: Aead, |
| 23 |
} |
| 24 |
|
| 25 |
impl Config { |
| 26 |
pub fn new(kem: Kem, kdf: Kdf, aead: Aead) -> Self { |
| 27 |
Self { kem, kdf, aead } |
| 28 |
} |
| 29 |
|
| 30 |
pub fn kem(self) -> Kem { |
| 31 |
self.kem |
| 32 |
} |
| 33 |
|
| 34 |
pub fn kdf(self) -> Kdf { |
| 35 |
self.kdf |
| 36 |
} |
| 37 |
|
| 38 |
pub fn aead(self) -> Aead { |
| 39 |
self.aead |
| 40 |
} |
| 41 |
|
| 42 |
pub fn supported(self) -> bool { |
| 43 |
secstatus_to_res(unsafe { |
| 44 |
sys::PK11_HPKE_ValidateParameters( |
| 45 |
KemId::Type::from(u16::from(self.kem)), |
| 46 |
KdfId::Type::from(u16::from(self.kdf)), |
| 47 |
AeadId::Type::from(u16::from(self.aead)), |
| 48 |
) |
| 49 |
}) |
| 50 |
.is_ok() |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
impl Default for Config { |
| 55 |
fn default() -> Self { |
| 56 |
Self { |
| 57 |
kem: Kem::X25519Sha256, |
| 58 |
kdf: Kdf::HkdfSha256, |
| 59 |
aead: Aead::Aes128Gcm, |
| 60 |
} |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
pub trait Exporter { |
| 65 |
fn export(&self, info: &[u8], len: usize) -> Res<SymKey>; |
| 66 |
} |
| 67 |
|
| 68 |
unsafe fn destroy_hpke_context(cx: *mut sys::HpkeContext) { |
| 69 |
sys::PK11_HPKE_DestroyContext(cx, sys::PRBool::from(true)); |
| 70 |
} |
| 71 |
|
| 72 |
scoped_ptr!(HpkeContext, sys::HpkeContext, destroy_hpke_context); |
| 73 |
|
| 74 |
impl HpkeContext { |
| 75 |
fn new(config: Config) -> Res<Self> { |
| 76 |
let ptr = unsafe { |
| 77 |
sys::PK11_HPKE_NewContext( |
| 78 |
KemId::Type::from(u16::from(config.kem)), |
| 79 |
KdfId::Type::from(u16::from(config.kdf)), |
| 80 |
AeadId::Type::from(u16::from(config.aead)), |
| 81 |
null_mut(), |
| 82 |
null(), |
| 83 |
) |
| 84 |
}; |
| 85 |
Self::from_ptr(ptr) |
| 86 |
} |
| 87 |
} |
| 88 |
|
| 89 |
unsafe impl Send for HpkeContext {} |
| 90 |
|
| 91 |
impl Exporter for HpkeContext { |
| 92 |
fn export(&self, info: &[u8], len: usize) -> Res<SymKey> { |
| 93 |
let mut out: *mut sys::PK11SymKey = null_mut(); |
| 94 |
secstatus_to_res(unsafe { |
| 95 |
sys::PK11_HPKE_ExportSecret( |
| 96 |
self.ptr, |
| 97 |
&Item::wrap(info), |
| 98 |
c_uint::try_from(len).unwrap(), |
| 99 |
&mut out, |
| 100 |
) |
| 101 |
})?; |
| 102 |
SymKey::from_ptr(out) |
| 103 |
} |
| 104 |
} |
| 105 |
|
| 106 |
#[allow(clippy::module_name_repetitions)] |
| 107 |
pub struct HpkeS { |
| 108 |
context: HpkeContext, |
| 109 |
config: Config, |
| 110 |
} |
| 111 |
|
| 112 |
impl HpkeS { |
| 113 |
/// Create a new context that uses the KEM mode for sending. |
| 114 |
#[allow(clippy::similar_names)] |
| 115 |
pub fn new(config: Config, pk_r: &mut PublicKey, info: &[u8]) -> Res<Self> { |
| 116 |
let (sk_e, pk_e) = generate_key_pair(config.kem)?; |
| 117 |
let context = HpkeContext::new(config)?; |
| 118 |
secstatus_to_res(unsafe { |
| 119 |
sys::PK11_HPKE_SetupS(*context, *pk_e, *sk_e, **pk_r, &Item::wrap(info)) |
| 120 |
})?; |
| 121 |
Ok(Self { context, config }) |
| 122 |
} |
| 123 |
|
| 124 |
pub fn config(&self) -> Config { |
| 125 |
self.config |
| 126 |
} |
| 127 |
|
| 128 |
/// Get the encapsulated KEM secret. |
| 129 |
pub fn enc(&self) -> Res<Vec<u8>> { |
| 130 |
let v = unsafe { sys::PK11_HPKE_GetEncapPubKey(*self.context) }; |
| 131 |
let r = unsafe { v.as_ref() }.ok_or_else(|| Error::from(SEC_ERROR_INVALID_ARGS))?; |
| 132 |
// This is just an alias, so we can't use `Item`. |
| 133 |
let len = usize::try_from(r.len).unwrap(); |
| 134 |
let slc = unsafe { std::slice::from_raw_parts(r.data, len) }; |
| 135 |
Ok(Vec::from(slc)) |
| 136 |
} |
| 137 |
|
| 138 |
pub fn seal(&mut self, aad: &[u8], pt: &[u8]) -> Res<Vec<u8>> { |
| 139 |
let mut out: *mut sys::SECItem = null_mut(); |
| 140 |
secstatus_to_res(unsafe { |
| 141 |
sys::PK11_HPKE_Seal(*self.context, &Item::wrap(aad), &Item::wrap(pt), &mut out) |
| 142 |
})?; |
| 143 |
let v = Item::from_ptr(out)?; |
| 144 |
Ok(unsafe { v.into_vec() }) |
| 145 |
} |
| 146 |
} |
| 147 |
|
| 148 |
impl Exporter for HpkeS { |
| 149 |
fn export(&self, info: &[u8], len: usize) -> Res<SymKey> { |
| 150 |
self.context.export(info, len) |
| 151 |
} |
| 152 |
} |
| 153 |
|
| 154 |
impl Deref for HpkeS { |
| 155 |
type Target = Config; |
| 156 |
fn deref(&self) -> &Self::Target { |
| 157 |
&self.config |
| 158 |
} |
| 159 |
} |
| 160 |
|
| 161 |
#[allow(clippy::module_name_repetitions)] |
| 162 |
pub struct HpkeR { |
| 163 |
context: HpkeContext, |
| 164 |
config: Config, |
| 165 |
} |
| 166 |
|
| 167 |
impl HpkeR { |
| 168 |
/// Create a new context that uses the KEM mode for sending. |
| 169 |
#[allow(clippy::similar_names)] |
| 170 |
pub fn new( |
| 171 |
config: Config, |
| 172 |
pk_r: &PublicKey, |
| 173 |
sk_r: &PrivateKey, |
| 174 |
enc: &[u8], |
| 175 |
info: &[u8], |
| 176 |
) -> Res<Self> { |
| 177 |
let context = HpkeContext::new(config)?; |
| 178 |
secstatus_to_res(unsafe { |
| 179 |
sys::PK11_HPKE_SetupR( |
| 180 |
*context, |
| 181 |
**pk_r, |
| 182 |
**sk_r, |
| 183 |
&Item::wrap(enc), |
| 184 |
&Item::wrap(info), |
| 185 |
) |
| 186 |
})?; |
| 187 |
Ok(Self { context, config }) |
| 188 |
} |
| 189 |
|
| 190 |
pub fn config(&self) -> Config { |
| 191 |
self.config |
| 192 |
} |
| 193 |
|
| 194 |
pub fn decode_public_key(kem: Kem, k: &[u8]) -> Res<PublicKey> { |
| 195 |
// NSS uses a context for this, but we don't want that, but a dummy one works fine. |
| 196 |
let context = HpkeContext::new(Config { |
| 197 |
kem, |
| 198 |
..Config::default() |
| 199 |
})?; |
| 200 |
let mut ptr: *mut sys::SECKEYPublicKey = null_mut(); |
| 201 |
secstatus_to_res(unsafe { |
| 202 |
sys::PK11_HPKE_Deserialize( |
| 203 |
*context, |
| 204 |
k.as_ptr(), |
| 205 |
c_uint::try_from(k.len()).unwrap(), |
| 206 |
&mut ptr, |
| 207 |
) |
| 208 |
})?; |
| 209 |
PublicKey::from_ptr(ptr) |
| 210 |
} |
| 211 |
|
| 212 |
pub fn open(&mut self, aad: &[u8], ct: &[u8]) -> Res<Vec<u8>> { |
| 213 |
let mut out: *mut sys::SECItem = null_mut(); |
| 214 |
secstatus_to_res(unsafe { |
| 215 |
sys::PK11_HPKE_Open(*self.context, &Item::wrap(aad), &Item::wrap(ct), &mut out) |
| 216 |
})?; |
| 217 |
let v = Item::from_ptr(out)?; |
| 218 |
Ok(unsafe { v.into_vec() }) |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
impl Exporter for HpkeR { |
| 223 |
fn export(&self, info: &[u8], len: usize) -> Res<SymKey> { |
| 224 |
self.context.export(info, len) |
| 225 |
} |
| 226 |
} |
| 227 |
|
| 228 |
impl Deref for HpkeR { |
| 229 |
type Target = Config; |
| 230 |
fn deref(&self) -> &Self::Target { |
| 231 |
&self.config |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
/// Generate a key pair for the identified KEM. |
| 236 |
pub fn generate_key_pair(kem: Kem) -> Res<(PrivateKey, PublicKey)> { |
| 237 |
assert_eq!(kem, Kem::X25519Sha256); |
| 238 |
let slot = Slot::internal()?; |
| 239 |
|
| 240 |
let oid_data = unsafe { sys::SECOID_FindOIDByTag(sys::SECOidTag::SEC_OID_CURVE25519) }; |
| 241 |
let oid = unsafe { oid_data.as_ref() }.ok_or_else(Error::internal)?; |
| 242 |
let oid_slc = |
| 243 |
unsafe { std::slice::from_raw_parts(oid.oid.data, usize::try_from(oid.oid.len).unwrap()) }; |
| 244 |
let mut params: Vec<u8> = Vec::with_capacity(oid_slc.len() + 2); |
| 245 |
params.push(u8::try_from(sys::SEC_ASN1_OBJECT_ID).unwrap()); |
| 246 |
params.push(u8::try_from(oid.oid.len).unwrap()); |
| 247 |
params.extend_from_slice(oid_slc); |
| 248 |
|
| 249 |
let mut public_ptr: *mut sys::SECKEYPublicKey = null_mut(); |
| 250 |
let mut wrapped = Item::wrap(¶ms); |
| 251 |
|
| 252 |
// Try to make an insensitive key so that we can read the key data for tracing. |
| 253 |
let insensitive_secret_ptr = if log_enabled!(log::Level::Trace) { |
| 254 |
unsafe { |
| 255 |
sys::PK11_GenerateKeyPairWithOpFlags( |
| 256 |
*slot, |
| 257 |
sys::CK_MECHANISM_TYPE::from(sys::CKM_EC_KEY_PAIR_GEN), |
| 258 |
addr_of_mut!(wrapped).cast(), |
| 259 |
&mut public_ptr, |
| 260 |
sys::PK11_ATTR_SESSION | sys::PK11_ATTR_INSENSITIVE | sys::PK11_ATTR_PUBLIC, |
| 261 |
sys::CK_FLAGS::from(sys::CKF_DERIVE), |
| 262 |
sys::CK_FLAGS::from(sys::CKF_DERIVE), |
| 263 |
null_mut(), |
| 264 |
) |
| 265 |
} |
| 266 |
} else { |
| 267 |
null_mut() |
| 268 |
}; |
| 269 |
assert_eq!(insensitive_secret_ptr.is_null(), public_ptr.is_null()); |
| 270 |
let secret_ptr = if insensitive_secret_ptr.is_null() { |
| 271 |
unsafe { |
| 272 |
sys::PK11_GenerateKeyPairWithOpFlags( |
| 273 |
*slot, |
| 274 |
sys::CK_MECHANISM_TYPE::from(sys::CKM_EC_KEY_PAIR_GEN), |
| 275 |
addr_of_mut!(wrapped).cast(), |
| 276 |
&mut public_ptr, |
| 277 |
sys::PK11_ATTR_SESSION | sys::PK11_ATTR_SENSITIVE | sys::PK11_ATTR_PRIVATE, |
| 278 |
sys::CK_FLAGS::from(sys::CKF_DERIVE), |
| 279 |
sys::CK_FLAGS::from(sys::CKF_DERIVE), |
| 280 |
null_mut(), |
| 281 |
) |
| 282 |
} |
| 283 |
} else { |
| 284 |
insensitive_secret_ptr |
| 285 |
}; |
| 286 |
assert_eq!(secret_ptr.is_null(), public_ptr.is_null()); |
| 287 |
let sk = PrivateKey::from_ptr(secret_ptr)?; |
| 288 |
let pk = PublicKey::from_ptr(public_ptr)?; |
| 289 |
trace!("Generated key pair: sk={:?} pk={:?}", sk, pk); |
| 290 |
Ok((sk, pk)) |
| 291 |
} |
| 292 |
|
| 293 |
#[cfg(test)] |
| 294 |
mod test { |
| 295 |
use super::{generate_key_pair, Config, HpkeContext, HpkeR, HpkeS}; |
| 296 |
use crate::{hpke::Aead, init}; |
| 297 |
|
| 298 |
const INFO: &[u8] = b"info"; |
| 299 |
const AAD: &[u8] = b"aad"; |
| 300 |
const PT: &[u8] = b"message"; |
| 301 |
|
| 302 |
#[allow(clippy::similar_names)] // for sk_x and pk_x |
| 303 |
#[test] |
| 304 |
fn make() { |
| 305 |
init(); |
| 306 |
let cfg = Config::default(); |
| 307 |
let (sk_r, mut pk_r) = generate_key_pair(cfg.kem()).unwrap(); |
| 308 |
let hpke_s = HpkeS::new(cfg, &mut pk_r, INFO).unwrap(); |
| 309 |
let _hpke_r = HpkeR::new(cfg, &pk_r, &sk_r, &hpke_s.enc().unwrap(), INFO).unwrap(); |
| 310 |
} |
| 311 |
|
| 312 |
#[allow(clippy::similar_names)] // for sk_x and pk_x |
| 313 |
fn seal_open(aead: Aead) { |
| 314 |
// Setup |
| 315 |
init(); |
| 316 |
let cfg = Config { |
| 317 |
aead, |
| 318 |
..Config::default() |
| 319 |
}; |
| 320 |
assert!(cfg.supported()); |
| 321 |
let (sk_r, mut pk_r) = generate_key_pair(cfg.kem()).unwrap(); |
| 322 |
|
| 323 |
// Send |
| 324 |
let mut hpke_s = HpkeS::new(cfg, &mut pk_r, INFO).unwrap(); |
| 325 |
let enc = hpke_s.enc().unwrap(); |
| 326 |
let ct = hpke_s.seal(AAD, PT).unwrap(); |
| 327 |
|
| 328 |
// Receive |
| 329 |
let mut hpke_r = HpkeR::new(cfg, &pk_r, &sk_r, &enc, INFO).unwrap(); |
| 330 |
let pt = hpke_r.open(AAD, &ct).unwrap(); |
| 331 |
assert_eq!(&pt[..], PT); |
| 332 |
} |
| 333 |
|
| 334 |
#[test] |
| 335 |
fn seal_open_gcm() { |
| 336 |
seal_open(Aead::Aes128Gcm); |
| 337 |
} |
| 338 |
|
| 339 |
#[test] |
| 340 |
fn seal_open_chacha() { |
| 341 |
seal_open(Aead::ChaCha20Poly1305); |
| 342 |
} |
| 343 |
|
| 344 |
#[test] |
| 345 |
fn send_hpkecontext() { |
| 346 |
use std::{sync::mpsc, thread}; |
| 347 |
|
| 348 |
let (tx, rx) = mpsc::channel(); |
| 349 |
|
| 350 |
thread::spawn(move || { |
| 351 |
let context = HpkeContext::new(Config::default()); |
| 352 |
tx.send(context).unwrap(); |
| 353 |
}); |
| 354 |
|
| 355 |
let context = rx.recv().unwrap(); |
| 356 |
drop(context); |
| 357 |
} |
| 358 |
} |