Debian Codegraph @

third_party/rust/authenticator/src/crypto/nss.rs

raw
1 use super::CryptoError;
2 use nss_gk_api::p11::{
3 PK11Origin, PK11_CreateContextBySymKey, PK11_Decrypt, PK11_DigestFinal, PK11_DigestOp,
4 PK11_Encrypt, PK11_ExportDERPrivateKeyInfo, PK11_GenerateKeyPairWithOpFlags,
5 PK11_GenerateRandom, PK11_HashBuf, PK11_ImportDERPrivateKeyInfoAndReturnKey, PK11_ImportSymKey,
6 PK11_PubDeriveWithKDF, PK11_SignWithMechanism, PrivateKey, PublicKey,
7 SECKEY_DecodeDERSubjectPublicKeyInfo, SECKEY_ExtractPublicKey, SECOidTag, Slot,
8 SubjectPublicKeyInfo, AES_BLOCK_SIZE, PK11_ATTR_EXTRACTABLE, PK11_ATTR_INSENSITIVE,
9 PK11_ATTR_SESSION, SHA256_LENGTH,
10 };
11 use nss_gk_api::{IntoResult, SECItem, SECItemBorrowed, ScopedSECItem, PR_FALSE};
12 use pkcs11_bindings::{
13 CKA_DERIVE, CKA_ENCRYPT, CKA_SIGN, CKD_NULL, CKF_DERIVE, CKM_AES_CBC, CKM_ECDH1_DERIVE,
14 CKM_ECDSA_SHA256, CKM_EC_KEY_PAIR_GEN, CKM_SHA256_HMAC, CKM_SHA512_HMAC,
15 };
16 use std::convert::TryFrom;
17 use std::os::raw::{c_int, c_uint};
18 use std::ptr;
19
20 use super::der;
21
22 #[cfg(test)]
23 use nss_gk_api::p11::PK11_VerifyWithMechanism;
24
25 impl From<nss_gk_api::Error> for CryptoError {
26 fn from(e: nss_gk_api::Error) -> Self {
27 CryptoError::Backend(format!("{e}"))
28 }
29 }
30
31 pub type Result<T> = std::result::Result<T, CryptoError>;
32
33 fn nss_public_key_from_der_spki(spki: &[u8]) -> Result<PublicKey> {
34 // TODO: replace this with an nss-gk-api function
35 // https://github.com/mozilla/nss-gk-api/issues/7
36 let mut spki_item = SECItemBorrowed::wrap(spki);
37 let spki_item_ptr: *mut SECItem = spki_item.as_mut();
38 let nss_spki = unsafe {
39 SubjectPublicKeyInfo::from_ptr(SECKEY_DecodeDERSubjectPublicKeyInfo(spki_item_ptr))?
40 };
41 let public_key = unsafe { PublicKey::from_ptr(SECKEY_ExtractPublicKey(*nss_spki))? };
42 Ok(public_key)
43 }
44
45 /// ECDH using NSS types. Computes the x coordinate of scalar multiplication of `peer_public` by
46 /// `client_private`.
47 fn ecdh_nss_raw(client_private: PrivateKey, peer_public: PublicKey) -> Result<Vec<u8>> {
48 let ecdh_x_coord = unsafe {
49 PK11_PubDeriveWithKDF(
50 *client_private,
51 *peer_public,
52 PR_FALSE,
53 std::ptr::null_mut(),
54 std::ptr::null_mut(),
55 CKM_ECDH1_DERIVE,
56 CKM_SHA512_HMAC, // unused
57 CKA_DERIVE, // unused
58 0,
59 CKD_NULL,
60 std::ptr::null_mut(),
61 std::ptr::null_mut(),
62 )
63 .into_result()?
64 };
65 let ecdh_x_coord_bytes = ecdh_x_coord.as_bytes()?;
66 Ok(ecdh_x_coord_bytes.to_vec())
67 }
68
69 fn generate_p256_nss() -> Result<(PrivateKey, PublicKey)> {
70 // Hard-coding the P256 OID here is easier than extracting a group name from peer_public and
71 // comparing it with P256. We'll fail in `PK11_GenerateKeyPairWithOpFlags` if peer_public is on
72 // the wrong curve.
73 let oid_bytes = der::object_id(der::OID_SECP256R1_BYTES)?;
74 let mut oid = SECItemBorrowed::wrap(&oid_bytes);
75 let oid_ptr: *mut SECItem = oid.as_mut();
76
77 let slot = Slot::internal()?;
78
79 let mut client_public_ptr = ptr::null_mut();
80
81 // We have to be careful with error handling between the `PK11_GenerateKeyPairWithOpFlags` and
82 // `PublicKey::from_ptr` calls here, so I've wrapped them in the same unsafe block as a
83 // warning. TODO(jms) Replace this once there is a safer alternative.
84 // https://github.com/mozilla/nss-gk-api/issues/1
85 unsafe {
86 let client_private =
87 // Type of `param` argument depends on mechanism. For EC keygen it is
88 // `SECKEYECParams *` which is a typedef for `SECItem *`.
89 PK11_GenerateKeyPairWithOpFlags(
90 *slot,
91 CKM_EC_KEY_PAIR_GEN,
92 oid_ptr.cast(),
93 &mut client_public_ptr,
94 PK11_ATTR_EXTRACTABLE | PK11_ATTR_INSENSITIVE | PK11_ATTR_SESSION,
95 CKF_DERIVE,
96 CKF_DERIVE,
97 ptr::null_mut(),
98 )
99 .into_result()?;
100
101 let client_public = PublicKey::from_ptr(client_public_ptr)?;
102
103 Ok((client_private, client_public))
104 }
105 }
106
107 /// This returns a PKCS#8 ECPrivateKey and an uncompressed SEC1 public key.
108 pub fn gen_p256() -> Result<(Vec<u8>, Vec<u8>)> {
109 nss_gk_api::init();
110
111 let (client_private, client_public) = generate_p256_nss()?;
112
113 let pkcs8_priv = unsafe {
114 let pkcs8_priv_item: ScopedSECItem =
115 PK11_ExportDERPrivateKeyInfo(*client_private, ptr::null_mut()).into_result()?;
116 pkcs8_priv_item.into_vec()
117 };
118
119 let sec1_pub = client_public.key_data()?;
120
121 Ok((pkcs8_priv, sec1_pub))
122 }
123
124 pub fn ecdsa_p256_sha256_sign_raw(private: &[u8], data: &[u8]) -> Result<Vec<u8>> {
125 nss_gk_api::init();
126
127 let slot = Slot::internal()?;
128
129 let imported_private: PrivateKey = unsafe {
130 let mut imported_private_ptr = ptr::null_mut();
131 PK11_ImportDERPrivateKeyInfoAndReturnKey(
132 *slot,
133 SECItemBorrowed::wrap(private).as_mut(),
134 ptr::null_mut(),
135 ptr::null_mut(),
136 PR_FALSE,
137 PR_FALSE,
138 255, /* todo: expose KU_ flags in nss-gk-api */
139 &mut imported_private_ptr,
140 ptr::null_mut(),
141 );
142 imported_private_ptr.into_result()?
143 };
144
145 let signature_buf = vec![0; 64];
146 unsafe {
147 PK11_SignWithMechanism(
148 *imported_private,
149 CKM_ECDSA_SHA256,
150 ptr::null_mut(),
151 SECItemBorrowed::wrap(&signature_buf).as_mut(),
152 SECItemBorrowed::wrap(data).as_mut(),
153 )
154 .into_result()?;
155 }
156
157 let (r, s) = signature_buf.split_at(32);
158 der::sequence(&[&der::integer(r)?, &der::integer(s)?])
159 }
160
161 /// Ephemeral ECDH over P256. Takes a DER SubjectPublicKeyInfo that encodes a public key. Generates
162 /// an ephemeral P256 key pair. Returns
163 /// 1) the x coordinate of the shared point, and
164 /// 2) the uncompressed SEC 1 encoding of the ephemeral public key.
165 pub fn ecdhe_p256_raw(peer_spki: &[u8]) -> Result<(Vec<u8>, Vec<u8>)> {
166 nss_gk_api::init();
167
168 let peer_public = nss_public_key_from_der_spki(peer_spki)?;
169
170 let (client_private, client_public) = generate_p256_nss()?;
171
172 let shared_point = ecdh_nss_raw(client_private, peer_public)?;
173
174 Ok((shared_point, client_public.key_data()?))
175 }
176
177 /// AES-256-CBC encryption for data that is a multiple of the AES block size (16 bytes) in length.
178 /// Uses the zero IV if `iv` is None.
179 pub fn encrypt_aes_256_cbc_no_pad(key: &[u8], iv: Option<&[u8]>, data: &[u8]) -> Result<Vec<u8>> {
180 nss_gk_api::init();
181
182 if key.len() != 32 {
183 return Err(CryptoError::LibraryFailure);
184 }
185
186 let iv = iv.unwrap_or(&[0u8; AES_BLOCK_SIZE]);
187
188 if iv.len() != AES_BLOCK_SIZE {
189 return Err(CryptoError::LibraryFailure);
190 }
191
192 let in_len = match c_uint::try_from(data.len()) {
193 Ok(in_len) => in_len,
194 _ => return Err(CryptoError::LibraryFailure),
195 };
196
197 if data.len() % AES_BLOCK_SIZE != 0 {
198 return Err(CryptoError::LibraryFailure);
199 }
200
201 let slot = Slot::internal()?;
202
203 let sym_key = unsafe {
204 PK11_ImportSymKey(
205 *slot,
206 CKM_AES_CBC,
207 PK11Origin::PK11_OriginUnwrap,
208 CKA_ENCRYPT,
209 SECItemBorrowed::wrap(key).as_mut(),
210 ptr::null_mut(),
211 )
212 .into_result()?
213 };
214
215 let mut params = SECItemBorrowed::wrap(iv);
216 let params_ptr: *mut SECItem = params.as_mut();
217 let mut out_len: c_uint = 0;
218 let mut out = vec![0; data.len()];
219 unsafe {
220 PK11_Encrypt(
221 *sym_key,
222 CKM_AES_CBC,
223 params_ptr,
224 out.as_mut_ptr(),
225 &mut out_len,
226 in_len,
227 data.as_ptr(),
228 in_len,
229 )
230 .into_result()?
231 }
232 // CKM_AES_CBC should have output length equal to input length.
233 debug_assert_eq!(out_len, in_len);
234
235 Ok(out)
236 }
237
238 /// AES-256-CBC decryption for data that is a multiple of the AES block size (16 bytes) in length.
239 /// Uses the zero IV if `iv` is None.
240 pub fn decrypt_aes_256_cbc_no_pad(key: &[u8], iv: Option<&[u8]>, data: &[u8]) -> Result<Vec<u8>> {
241 nss_gk_api::init();
242
243 if key.len() != 32 {
244 return Err(CryptoError::LibraryFailure);
245 }
246
247 let iv = iv.unwrap_or(&[0u8; AES_BLOCK_SIZE]);
248
249 if iv.len() != AES_BLOCK_SIZE {
250 return Err(CryptoError::LibraryFailure);
251 }
252
253 let in_len = match c_uint::try_from(data.len()) {
254 Ok(in_len) => in_len,
255 _ => return Err(CryptoError::LibraryFailure),
256 };
257
258 if data.len() % AES_BLOCK_SIZE != 0 {
259 return Err(CryptoError::LibraryFailure);
260 }
261
262 let slot = Slot::internal()?;
263
264 let sym_key = unsafe {
265 PK11_ImportSymKey(
266 *slot,
267 CKM_AES_CBC,
268 PK11Origin::PK11_OriginUnwrap,
269 CKA_ENCRYPT,
270 SECItemBorrowed::wrap(key).as_mut(),
271 ptr::null_mut(),
272 )
273 .into_result()?
274 };
275
276 let mut params = SECItemBorrowed::wrap(iv);
277 let params_ptr: *mut SECItem = params.as_mut();
278 let mut out_len: c_uint = 0;
279 let mut out = vec![0; data.len()];
280 unsafe {
281 PK11_Decrypt(
282 *sym_key,
283 CKM_AES_CBC,
284 params_ptr,
285 out.as_mut_ptr(),
286 &mut out_len,
287 in_len,
288 data.as_ptr(),
289 in_len,
290 )
291 .into_result()?
292 }
293 // CKM_AES_CBC should have output length equal to input length.
294 debug_assert_eq!(out_len, in_len);
295
296 Ok(out)
297 }
298
299 /// Textbook HMAC-SHA256
300 pub fn hmac_sha256(key: &[u8], data: &[u8]) -> Result<Vec<u8>> {
301 nss_gk_api::init();
302
303 let data_len = match u32::try_from(data.len()) {
304 Ok(data_len) => data_len,
305 _ => return Err(CryptoError::LibraryFailure),
306 };
307
308 let slot = Slot::internal()?;
309 let sym_key = unsafe {
310 PK11_ImportSymKey(
311 *slot,
312 CKM_SHA256_HMAC,
313 PK11Origin::PK11_OriginUnwrap,
314 CKA_SIGN,
315 SECItemBorrowed::wrap(key).as_mut(),
316 ptr::null_mut(),
317 )
318 .into_result()?
319 };
320 let param = SECItemBorrowed::make_empty();
321 let context = unsafe {
322 PK11_CreateContextBySymKey(CKM_SHA256_HMAC, CKA_SIGN, *sym_key, param.as_ref())
323 .into_result()?
324 };
325 unsafe { PK11_DigestOp(*context, data.as_ptr(), data_len).into_result()? };
326 let mut digest = vec![0u8; SHA256_LENGTH];
327 let mut digest_len = 0u32;
328 unsafe {
329 PK11_DigestFinal(
330 *context,
331 digest.as_mut_ptr(),
332 &mut digest_len,
333 digest.len() as u32,
334 )
335 .into_result()?
336 }
337 assert_eq!(digest_len as usize, SHA256_LENGTH);
338 Ok(digest)
339 }
340
341 /// Textbook SHA256
342 pub fn sha256(data: &[u8]) -> Result<Vec<u8>> {
343 nss_gk_api::init();
344
345 let data_len: i32 = match i32::try_from(data.len()) {
346 Ok(data_len) => data_len,
347 _ => return Err(CryptoError::LibraryFailure),
348 };
349 let mut digest = vec![0u8; SHA256_LENGTH];
350 unsafe {
351 PK11_HashBuf(
352 SECOidTag::SEC_OID_SHA256,
353 digest.as_mut_ptr(),
354 data.as_ptr(),
355 data_len,
356 )
357 .into_result()?
358 };
359 Ok(digest)
360 }
361
362 pub fn random_bytes(count: usize) -> Result<Vec<u8>> {
363 nss_gk_api::init();
364
365 let count_cint: c_int = match c_int::try_from(count) {
366 Ok(c) => c,
367 _ => return Err(CryptoError::LibraryFailure),
368 };
369
370 let mut out = vec![0u8; count];
371 unsafe { PK11_GenerateRandom(out.as_mut_ptr(), count_cint).into_result()? };
372 Ok(out)
373 }
374
375 #[cfg(test)]
376 pub fn test_ecdh_p256_raw(
377 peer_spki: &[u8],
378 client_public_x: &[u8],
379 client_public_y: &[u8],
380 client_private: &[u8],
381 ) -> Result<Vec<u8>> {
382 nss_gk_api::init();
383
384 let peer_public = nss_public_key_from_der_spki(peer_spki)?;
385
386 // NSS has no mechanism to import a raw elliptic curve coordinate as a private key.
387 // We need to encode it in an RFC 5208 PrivateKeyInfo:
388 //
389 // PrivateKeyInfo ::= SEQUENCE {
390 // version Version,
391 // privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
392 // privateKey PrivateKey,
393 // attributes [0] IMPLICIT Attributes OPTIONAL }
394 //
395 // Version ::= INTEGER
396 // PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
397 // PrivateKey ::= OCTET STRING
398 // Attributes ::= SET OF Attribute
399 //
400 // The privateKey field will contain an RFC 5915 ECPrivateKey:
401 // ECPrivateKey ::= SEQUENCE {
402 // version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
403 // privateKey OCTET STRING,
404 // parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
405 // publicKey [1] BIT STRING OPTIONAL
406 // }
407
408 // PrivateKeyInfo
409 let priv_key_info = der::sequence(&[
410 // version
411 &der::integer(&[0x00])?,
412 // privateKeyAlgorithm
413 &der::sequence(&[
414 &der::object_id(der::OID_EC_PUBLIC_KEY_BYTES)?,
415 &der::object_id(der::OID_SECP256R1_BYTES)?,
416 ])?,
417 // privateKey
418 &der::octet_string(
419 // ECPrivateKey
420 &der::sequence(&[
421 // version
422 &der::integer(&[0x01])?,
423 // privateKey
424 &der::octet_string(client_private)?,
425 // publicKey
426 &der::context_specific_explicit_tag(
427 1, // publicKey
428 &der::bit_string(&[&[0x04], client_public_x, client_public_y].concat())?,
429 )?,
430 ])?,
431 )?,
432 ])?;
433
434 // Now we can import the private key.
435 let slot = Slot::internal()?;
436 let mut priv_key_info_item = SECItemBorrowed::wrap(&priv_key_info);
437 let priv_key_info_item_ptr: *mut SECItem = priv_key_info_item.as_mut();
438 let mut client_private_ptr = ptr::null_mut();
439 unsafe {
440 PK11_ImportDERPrivateKeyInfoAndReturnKey(
441 *slot,
442 priv_key_info_item_ptr,
443 ptr::null_mut(),
444 ptr::null_mut(),
445 PR_FALSE,
446 PR_FALSE,
447 255, /* todo: expose KU_ flags in nss-gk-api */
448 &mut client_private_ptr,
449 ptr::null_mut(),
450 )
451 };
452 let client_private = unsafe { PrivateKey::from_ptr(client_private_ptr) }?;
453
454 let shared_point = ecdh_nss_raw(client_private, peer_public)?;
455
456 Ok(shared_point)
457 }
458
459 #[cfg(test)]
460 pub fn test_ecdsa_p256_sha256_verify_raw(
461 public: &[u8],
462 signature: &[u8],
463 data: &[u8],
464 ) -> Result<()> {
465 nss_gk_api::init();
466
467 let signature = der::read_p256_sig(signature)?;
468 let public = nss_public_key_from_der_spki(public)?;
469 unsafe {
470 PK11_VerifyWithMechanism(
471 *public,
472 CKM_ECDSA_SHA256,
473 ptr::null_mut(),
474 SECItemBorrowed::wrap(&signature).as_mut(),
475 SECItemBorrowed::wrap(data).as_mut(),
476 ptr::null_mut(),
477 )
478 .into_result()?
479 }
480 Ok(())
481 }