Debian Codegraph @

third_party/rust/nss-gk-api/src/hpke.rs

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