sequoia_cryptoki/decrypt.rs
1use std::borrow::Cow;
2
3use anyhow::Context;
4
5use sequoia_openpgp as openpgp;
6use openpgp::crypto::Decryptor as _;
7use openpgp::crypto::ecdh::aes_key_unwrap;
8use openpgp::crypto::mem::Protected;
9use openpgp::crypto::mpi;
10use openpgp::crypto::{Curve, SessionKey, SymmetricAlgorithm};
11use openpgp::crypto;
12use openpgp::packet::key::PublicParts;
13use openpgp::packet::key::UnspecifiedRole;
14use openpgp::packet::key;
15use openpgp::packet;
16use openpgp::types::HashAlgorithm;
17use openpgp::types::PublicKeyAlgorithm;
18
19use cryptoki::mechanism::{Mechanism, MechanismType};
20use cryptoki::mechanism::elliptic_curve::EcKdf;
21use cryptoki::mechanism::elliptic_curve::Ecdh1DeriveParams;
22use cryptoki::mechanism::hkdf::{HkdfParams, HkdfSalt};
23use cryptoki::object::Attribute;
24use cryptoki::object::AttributeType;
25use cryptoki::object::KeyType;
26use cryptoki::object::ObjectClass;
27use cryptoki::session::UserType;
28use cryptoki::types::AuthPin;
29use cryptoki::types::Ulong;
30
31use crate::Result;
32use crate::Prompt;
33use crate::key_info::KeyInfo;
34use crate::objects::Key;
35
36const TRACE: bool = false;
37
38/// A decryptor for a PKCS#11 key.
39///
40/// This implements [`sequoia_openpgp::crypto::Decryptor`] and hence can
41/// be used wherever a Sequoia method needs to decrypt data.
42///
43/// [`sequoia_openpgp::crypto::Decryptor`]: https://docs.rs/sequoia-openpgp/latest/sequoia_openpgp/crypto/trait.Decryptor.html
44pub struct Decryptor<'key, 'prompt> {
45 key: Cow<'key, Key>,
46 openpgp_key: packet::Key<PublicParts, UnspecifiedRole>,
47 user_pin: Option<AuthPin>,
48 prompt: Box<dyn Prompt + 'prompt>,
49}
50
51impl<'key, 'prompt> Decryptor<'key, 'prompt> {
52 /// Creates a `Decryptor`.
53 ///
54 /// This is a bit ugly, because we can't stash a PKCS#11
55 /// `Session`: a struct that implements `Decryptor` has to
56 /// implement `Sync`, but a `Session` is not `Sync`.
57 ///
58 /// If the user PIN is known, pass it through to avoid prompting
59 /// the user. (If `user_pin` is wrong, we don't prompt the user,
60 /// but immediately return an error.) Otherwise, the user is
61 /// prompted.
62 pub fn new<P>(prompt: P, key: &'key Key, user_pin: Option<AuthPin>)
63 -> Result<Self>
64 where
65 P: Prompt + 'prompt,
66 {
67 // Before we prompt for the PIN, make sure we can convert the
68 // public key to an OpenPGP key.
69 let openpgp_key = key.to_openpgp_key()
70 .context("Converting public key to OpenPGP format")?
71 .role_into_unspecified();
72
73 Ok(Self {
74 key: Cow::Borrowed(key),
75 openpgp_key,
76 user_pin,
77 prompt: Box::new(prompt),
78 })
79 }
80
81 /// Creates a `Decryptor`.
82 ///
83 /// Like [`Decryptor::new`], but takes ownership of `key`.
84 pub fn new_owned<P>(prompt: P, key: Key, user_pin: Option<AuthPin>)
85 -> Result<Self>
86 where
87 P: Prompt + 'prompt,
88 {
89 // Before we prompt for the PIN, make sure we can convert the
90 // public key to an OpenPGP key.
91 let openpgp_key = key.to_openpgp_key()
92 .context("Converting public key to OpenPGP format")?
93 .role_into_unspecified();
94
95 Ok(Self {
96 key: Cow::Owned(key),
97 openpgp_key,
98 user_pin,
99 prompt: Box::new(prompt),
100 })
101 }
102}
103
104impl crypto::Decryptor for Decryptor<'_, '_> {
105 fn public(&self) -> &packet::Key<PublicParts, UnspecifiedRole> {
106 &self.openpgp_key
107 }
108
109 fn decrypt(&mut self, ciphertext: &mpi::Ciphertext,
110 plaintext_len: Option<usize>)
111 -> Result<crypto::SessionKey>
112 {
113 // We wrap the real implementation so that we can more easily
114 // trace any errors.
115 tracer!(TRACE, "Decryptor::decrypt");
116 self.decrypt_internal(ciphertext, plaintext_len)
117 .map_err(|err| {
118 t!("Decryption error: {}", err);
119 err
120 })
121 }
122}
123
124impl Decryptor<'_, '_> {
125 fn decrypt_internal(&mut self,
126 ciphertext: &mpi::Ciphertext,
127 plaintext_len: Option<usize>)
128 -> Result<crypto::SessionKey>
129 {
130 tracer!(TRACE, "Decryptor::decrypt_internal");
131 t!("ciphertext: {:?}, plaintext_len: {:?}",
132 ciphertext, plaintext_len);
133
134 let (session, _object) = self.key.open_ro_session()?;
135
136 // Login as the user.
137 if let Some(user_pin) = self.user_pin.as_ref() {
138 // PIN was supplied.
139 session.login(UserType::User, Some(&user_pin))
140 .context("Logging in to token")?;
141 } else {
142 // Prompt the user for the PIN.
143 loop {
144 let user_pin = self.prompt.prompt_to_unlock("the user PIN")?;
145 let user_pin = String::from_utf8(user_pin.map(|p| p.to_vec()))
146 .context("Parsing user PIN")?;
147 let user_pin = AuthPin::new(user_pin.into());
148
149 match session.login(UserType::User, Some(&user_pin)) {
150 Ok(_) => {
151 self.user_pin = Some(user_pin);
152 break;
153 }
154 Err(err) => {
155 eprintln!("Error logging in: {}", err);
156 }
157 }
158 }
159 }
160
161 // The default public session only allows enumerating public
162 // key objects. We now look up the private key object using
163 // the user session. By convention, the public and private
164 // keys have the same ID (CKA_ID).
165 let key_info = KeyInfo::new(&session, &self.key)?;
166 let composite_info = if let Some(composite)
167 = self.key.composite_key().as_ref()
168 {
169 Some(KeyInfo::new(&session, composite)?)
170 } else {
171 None
172 };
173
174 let decrypt_mlkem = |pk_algo,
175 key_info: KeyInfo,
176 composite_info: Option<KeyInfo>,
177 ecdh_public: &[u8],
178 ecdh_part: &[u8],
179 mlkem_part: &[u8],
180 esk: &[u8]|
181 {
182 // Decrypt the ML-KEM key share.
183
184 let (mlkem_info, ecdh_info) = key_info.check_composite(
185 &self.openpgp_key, composite_info,
186 KeyType::ML_KEM, KeyType::EC_MONTGOMERY)?;
187
188 let attributes = &[
189 Attribute::Class(ObjectClass::SECRET_KEY),
190 Attribute::KeyType(KeyType::GENERIC_SECRET),
191 // Don't persist the session key on the token.
192 Attribute::Token(false),
193 // Mark the session key bundle as extractable.
194 Attribute::Extractable(true),
195 Attribute::Sensitive(false),
196 ];
197
198 let mlkem_share_handle = session.decapsulate_key(
199 &Mechanism::MlKem, mlkem_info.private_key,
200 attributes,
201 &mlkem_part[..])
202 .context("Decrypting ML-KEM part")?;
203
204 // Extract the share from the token.
205 let mut mlkem_share = None;
206 for attribute in session.get_attributes(
207 mlkem_share_handle,
208 &[ AttributeType::Value ])?
209 {
210 if let Attribute::Value(v) = attribute {
211 mlkem_share = Some(v);
212 } else {
213 return Err(anyhow::anyhow!(
214 "Token returned unrequested attribute: {:?}",
215 attribute));
216 }
217 }
218
219 let Some(mlkem_share) = mlkem_share else {
220 return Err(anyhow::anyhow!(
221 "Failed to extract ML-KEM share from token"));
222 };
223
224 // Decrypt the ECDH key share.
225
226 let kdf = EcKdf::null();
227 let ecdh1_derive_params = Ecdh1DeriveParams::new(
228 kdf, &ecdh_part[..]);
229
230 let attributes = &[
231 Attribute::Class(ObjectClass::SECRET_KEY),
232 Attribute::KeyType(KeyType::GENERIC_SECRET),
233 // Don't persist the KEK on the token.
234 Attribute::Token(false),
235 // Mark the session key bundle as extractable.
236 Attribute::Extractable(true),
237 Attribute::Sensitive(false),
238 ];
239
240 t!("Deriving ECDH share from {} bytes", ecdh_part.len());
241 let ecdh_share_handle = session.derive_key(
242 &Mechanism::Ecdh1Derive(ecdh1_derive_params),
243 ecdh_info.private_key,
244 attributes)?;
245 t!("Derived ECDH share on token");
246
247 // Extract the share from the token.
248 let mut ecdh_share = None;
249 for attribute in session.get_attributes(
250 ecdh_share_handle,
251 &[ AttributeType::Value ])?
252 {
253 if let Attribute::Value(v) = attribute {
254 ecdh_share = Some(v);
255 } else {
256 return Err(anyhow::anyhow!(
257 "Token returned unrequested attribute: {:?}",
258 attribute));
259 }
260 }
261
262 let Some(ecdh_share) = ecdh_share else {
263 return Err(anyhow::anyhow!(
264 "Failed to extract ECDH share from token"));
265 };
266 t!("Extracted ECDH share from token, got {} bytes",
267 ecdh_share.len());
268
269 let kek = multi_key_combine(
270 &mlkem_share,
271 &ecdh_share,
272 &ecdh_part[..],
273 &ecdh_public[..],
274 pk_algo)
275 .context("Combining ML-KEM and ECDH key parts")?;
276
277 Ok(aes_key_unwrap(SymmetricAlgorithm::AES256,
278 kek.as_protected(),
279 esk)
280 .context("Unwrapping KEK")?.into())
281 };
282
283 match (key_info.key_type, self.openpgp_key.mpis(), ciphertext) {
284 (KeyType::EC_MONTGOMERY,
285 mpi::PublicKey::MLKEM768_X25519 {
286 ecdh: ecdh_public,
287 ..
288 },
289 mpi::Ciphertext::MLKEM768_X25519 {
290 ecdh: ecdh_part,
291 mlkem: mlkem_part,
292 esk,
293 })
294 | (KeyType::ML_KEM,
295 mpi::PublicKey::MLKEM768_X25519 {
296 ecdh: ecdh_public,
297 ..
298 },
299 mpi::Ciphertext::MLKEM768_X25519 {
300 ecdh: ecdh_part,
301 mlkem: mlkem_part,
302 esk,
303 }) =>
304 {
305 decrypt_mlkem(PublicKeyAlgorithm::MLKEM768_X25519,
306 key_info, composite_info,
307 &ecdh_public[..], &ecdh_part[..],
308 &mlkem_part[..], &esk[..])
309 }
310
311 (KeyType::EC_MONTGOMERY,
312 mpi::PublicKey::MLKEM1024_X448 {
313 ecdh: ecdh_public,
314 ..
315 },
316 mpi::Ciphertext::MLKEM1024_X448 {
317 ecdh: ecdh_part,
318 mlkem: mlkem_part,
319 esk,
320 })
321 | (KeyType::ML_KEM,
322 mpi::PublicKey::MLKEM1024_X448 {
323 ecdh: ecdh_public,
324 ..
325 },
326 mpi::Ciphertext::MLKEM1024_X448 {
327 ecdh: ecdh_part,
328 mlkem: mlkem_part,
329 esk,
330 }) =>
331 {
332 decrypt_mlkem(PublicKeyAlgorithm::MLKEM1024_X448,
333 key_info, composite_info,
334 &ecdh_public[..], &ecdh_part[..],
335 &mlkem_part[..], &esk[..])
336 }
337
338 (KeyType::EC_MONTGOMERY,
339 mpi::PublicKey::X25519 { u },
340 mpi::Ciphertext::X25519 { e, key }) =>
341 {
342 let key_info = key_info.check_standalone(
343 &self.openpgp_key, composite_info,
344 KeyType::EC_MONTGOMERY)?;
345
346 // Derive the shared key from our private key on the
347 // token and the ephemeral key.
348
349 // For the key derivation, we use PKCS#11's
350 // CKM_ECDH1_DERIVE mechanism. Per PKCS#11, v3.2,
351 // draft 13, Section 6.3.17 Elliptic Curve
352 // Diffie-Hellman key derivation:
353 //
354 // The Elliptic Curve Diffie-Hellman (ECDH) key
355 // derivation mechanism, denoted CKM_ECDH1_DERIVE,
356 // is a mechanism for key derivation based on the
357 // Diffie-Hellman version of the Elliptic Curve key
358 // agreement scheme, as defined in [ANSI X9.63] for
359 // short Weierstrass EC keys and [RFC 7748] for
360 // Montgomery keys, where each party contributes one
361 // key pair all using the same EC domain parameters.
362
363 let ecdh1_derive_params = Ecdh1DeriveParams::new(
364 EcKdf::null(), &e[..]);
365
366 let attributes = &[
367 Attribute::Class(ObjectClass::SECRET_KEY),
368 Attribute::KeyType(KeyType::GENERIC_SECRET),
369 // Don't persist the shared key on the token.
370 Attribute::Token(false),
371 // Make the shared key as extractable.
372 Attribute::Extractable(true),
373 Attribute::Sensitive(false),
374 ];
375
376 let shared_key_handle = session.derive_key(
377 &Mechanism::Ecdh1Derive(ecdh1_derive_params),
378 key_info.private_key,
379 attributes)?;
380 t!("Derived shared key on token");
381
382 // Extract the shared key from the token.
383 let mut shared_key = None;
384 for attribute in session.get_attributes(
385 shared_key_handle,
386 &[ AttributeType::Value ])?
387 {
388 if let Attribute::Value(v) = attribute {
389 shared_key = Some(v);
390 } else {
391 return Err(anyhow::anyhow!(
392 "Token returned unrequested attribute: {:?}",
393 attribute));
394 }
395 }
396
397 let shared_key = if let Some(shared_key) = shared_key {
398 shared_key
399 } else {
400 return Err(anyhow::anyhow!(
401 "Failed to export shared key form token"));
402 };
403
404 t!("Extracted shared key: {} bytes", shared_key.len());
405
406 // Compute the wrap key.
407 let wrap_algo = SymmetricAlgorithm::AES128;
408 let mut ikm = vec![0; 32 + 32 + 32];
409
410 // Yes clippy, this operation will always return
411 // zero. This is the intended outcome. Chill.
412 #[allow(clippy::erasing_op)]
413 ikm[0 * 32..1 * 32].copy_from_slice(&e[..]);
414 ikm[1 * 32..2 * 32].copy_from_slice(&u[..]);
415 ikm[2 * 32..3 * 32].copy_from_slice(&shared_key[..]);
416
417 // XXX: We should chain the operations so that
418 // intermediate values don't leave the token. But, it
419 // seems that cryptoki doesn't expose
420 // CKM_CONCATENATE_BASE_AND_KEY and
421 // CKM_CONCATENATE_BASE_AND_DATA. So, in the mean
422 // time, we do the concatenation here.
423
424 // Load the IKM.
425 let ikm = session.create_object(&[
426 Attribute::Class(ObjectClass::SECRET_KEY),
427 Attribute::KeyType(KeyType::GENERIC_SECRET),
428 Attribute::Token(false),
429 Attribute::Derive(true),
430 Attribute::Value(ikm.into()),
431 ])?;
432
433 // Prepare HKDF/SHA256.
434 let hkdf_params = HkdfParams::new(MechanismType::SHA256_HMAC,
435 Some(HkdfSalt::Null),
436 Some(b"OpenPGP X25519"));
437
438 let attributes = &[
439 Attribute::KeyType(KeyType::GENERIC_SECRET),
440 // Don't persist the shared key on the token.
441 Attribute::Token(false),
442 // Make the shared key as extractable.
443 Attribute::Extractable(true),
444 Attribute::Sensitive(false),
445 Attribute::ValueLen(wrap_algo.key_size()?.try_into()?),
446 ];
447
448 let kek_handle = session.derive_key(
449 &Mechanism::HkdfDerive(hkdf_params),
450 ikm,
451 attributes)?;
452 session.destroy_object(ikm)?;
453 t!("Executed HKDF on the token");
454
455 // XXX: We shouldn't extract, just chain aes unwrap.
456
457 // Extract the OKM from the token.
458 let mut kek = None;
459 for attribute in session.get_attributes(
460 kek_handle,
461 &[ AttributeType::Value ])?
462 {
463 if let Attribute::Value(v) = attribute {
464 kek = Some(v);
465 } else {
466 return Err(anyhow::anyhow!(
467 "Token returned unrequested attribute: {:?}",
468 attribute));
469 }
470 }
471
472 let kek = kek.map(SessionKey::from)
473 .ok_or(anyhow::anyhow!(
474 "Failed to export shared key form token"))?;
475
476 // Decrypt the session key.
477 Ok(aes_key_unwrap(wrap_algo, kek.as_protected(),
478 key)?.into())
479 },
480
481 (KeyType::EC_MONTGOMERY,
482 mpi::PublicKey::X448 { u },
483 mpi::Ciphertext::X448 { e, key }) =>
484 {
485 let key_info = key_info.check_standalone(
486 &self.openpgp_key, composite_info,
487 KeyType::EC_MONTGOMERY)?;
488
489 // Derive the shared key from our private key on the
490 // token and the ephemeral key.
491
492 // For the key derivation, we use PKCS#11's
493 // CKM_ECDH1_DERIVE mechanism. Per PKCS#11, v3.2,
494 // draft 13, Section 6.3.17 Elliptic Curve
495 // Diffie-Hellman key derivation:
496 //
497 // The Elliptic Curve Diffie-Hellman (ECDH) key
498 // derivation mechanism, denoted CKM_ECDH1_DERIVE,
499 // is a mechanism for key derivation based on the
500 // Diffie-Hellman version of the Elliptic Curve key
501 // agreement scheme, as defined in [ANSI X9.63] for
502 // short Weierstrass EC keys and [RFC 7748] for
503 // Montgomery keys, where each party contributes one
504 // key pair all using the same EC domain parameters.
505
506 let ecdh1_derive_params = Ecdh1DeriveParams::new(
507 EcKdf::null(), &e[..]);
508
509 let attributes = &[
510 Attribute::Class(ObjectClass::SECRET_KEY),
511 Attribute::KeyType(KeyType::GENERIC_SECRET),
512 // Don't persist the shared key on the token.
513 Attribute::Token(false),
514 // Make the shared key as extractable.
515 Attribute::Extractable(true),
516 Attribute::Sensitive(false),
517 ];
518
519 let shared_key_handle = session.derive_key(
520 &Mechanism::Ecdh1Derive(ecdh1_derive_params),
521 key_info.private_key,
522 attributes)?;
523 t!("Derived shared key on token");
524
525 // Extract the shared key from the token.
526 let mut shared_key = None;
527 for attribute in session.get_attributes(
528 shared_key_handle,
529 &[ AttributeType::Value ])?
530 {
531 if let Attribute::Value(v) = attribute {
532 shared_key = Some(v);
533 } else {
534 return Err(anyhow::anyhow!(
535 "Token returned unrequested attribute: {:?}",
536 attribute));
537 }
538 }
539
540 let shared_key = if let Some(shared_key) = shared_key {
541 shared_key
542 } else {
543 return Err(anyhow::anyhow!(
544 "Failed to export shared key form token"));
545 };
546
547 t!("Extracted shared key: {} bytes", shared_key.len());
548
549 // Compute the wrap key.
550 let wrap_algo = SymmetricAlgorithm::AES256;
551 let mut ikm = vec![0; 56 + 56 + 56];
552
553 // Yes clippy, this operation will always return
554 // zero. This is the intended outcome. Chill.
555 #[allow(clippy::erasing_op)]
556 ikm[0 * 56..1 * 56].copy_from_slice(&e[..]);
557 ikm[1 * 56..2 * 56].copy_from_slice(&u[..]);
558 ikm[2 * 56..3 * 56].copy_from_slice(&shared_key[..]);
559
560 // XXX: We should chain the operations so that
561 // intermediate values don't leave the token. But, it
562 // seems that cryptoki doesn't expose
563 // CKM_CONCATENATE_BASE_AND_KEY and
564 // CKM_CONCATENATE_BASE_AND_DATA. So, in the mean
565 // time, we do the concatenation here.
566
567 // Load the IKM.
568 let ikm = session.create_object(&[
569 Attribute::Class(ObjectClass::SECRET_KEY),
570 Attribute::KeyType(KeyType::GENERIC_SECRET),
571 Attribute::Token(false),
572 Attribute::Derive(true),
573 Attribute::Value(ikm.into()),
574 ])?;
575
576 // Prepare HKDF/SHA512.
577 let hkdf_params = HkdfParams::new(MechanismType::SHA512_HMAC,
578 Some(HkdfSalt::Null),
579 Some(b"OpenPGP X448"));
580
581 let attributes = &[
582 Attribute::KeyType(KeyType::GENERIC_SECRET),
583 // Don't persist the shared key on the token.
584 Attribute::Token(false),
585 // Make the shared key as extractable.
586 Attribute::Extractable(true),
587 Attribute::Sensitive(false),
588 Attribute::ValueLen(wrap_algo.key_size()?.try_into()?),
589 ];
590
591 let kek_handle = session.derive_key(
592 &Mechanism::HkdfDerive(hkdf_params),
593 ikm,
594 attributes)?;
595 session.destroy_object(ikm)?;
596 t!("Executed HKDF on the token");
597
598 // XXX: We shouldn't extract, just chain aes unwrap.
599
600 // Extract the OKM from the token.
601 let mut kek = None;
602 for attribute in session.get_attributes(
603 kek_handle,
604 &[ AttributeType::Value ])?
605 {
606 if let Attribute::Value(v) = attribute {
607 kek = Some(v);
608 } else {
609 return Err(anyhow::anyhow!(
610 "Token returned unrequested attribute: {:?}",
611 attribute));
612 }
613 }
614
615 let kek = kek.map(SessionKey::from)
616 .ok_or(anyhow::anyhow!(
617 "Failed to export shared key form token"))?;
618
619 // Decrypt the session key.
620 Ok(aes_key_unwrap(wrap_algo, kek.as_protected(),
621 key)?.into())
622 },
623
624 (KeyType::EC_MONTGOMERY,
625 mpi::PublicKey::ECDH { curve, hash, sym, .. },
626 mpi::Ciphertext::ECDH { e, key, .. }) =>
627 {
628 let key_info = key_info.check_standalone(
629 &self.openpgp_key, composite_info,
630 KeyType::EC_MONTGOMERY)?;
631
632 // 1.) Get the shared secret using the private key on
633 // the token, 2.) derive the KEK from the shared
634 // secret, 3.) use the KEK to decrypt the session key
635 // bundle (session key plus metadata), then 4.)
636 // extract the session key bundle.
637
638 // The decryption algorithm is defined in RFC 9580,
639 // Section 11.5. ECDH Algorithm:
640 //
641 // This section describes the One-Pass
642 // Diffie-Hellman method, which is a combination of
643 // the ECC Diffie-Hellman method that establishes a
644 // shared secret and the key derivation method that
645 // processes the shared secret into a derived key.
646 //
647 // https://www.rfc-editor.org/rfc/rfc9580.html#name-ecdh-algorithm
648
649 // For 1) getting the shared secret, and 2) deriving
650 // the KEK, we use PKCS#11's CKM_ECDH1_DERIVE
651 // mechanism. Per PKCS#11, v3.2, draft 13, Section
652 // 6.3.17 Elliptic Curve Diffie-Hellman key
653 // derivation:
654 //
655 // The Elliptic Curve Diffie-Hellman (ECDH) key
656 // derivation mechanism, denoted CKM_ECDH1_DERIVE,
657 // is a mechanism for key derivation based on the
658 // Diffie-Hellman version of the Elliptic Curve key
659 // agreement scheme, as defined in [ANSI X9.63] for
660 // short Weierstrass EC keys and [RFC 7748] for
661 // Montgomery keys, where each party contributes one
662 // key pair all using the same EC domain parameters.
663
664 // Configure the KDF. According to
665 //
666 // 11.4. Key Derivation Function
667 //
668 // A key derivation function (KDF) is necessary to
669 // implement EC encryption. The Concatenation Key
670 // Derivation Function (Approved Alternative 1)
671 // [SP800-56A] with the KDF hash function that is
672 // SHA2-256 [FIPS180] or stronger is REQUIRED.
673 //
674 // https://www.rfc-editor.org/rfc/rfc9580.html#section-11.4
675 let param = make_ecdh_derive_param(
676 self.public(), curve, hash, sym);
677 let kdf = match hash {
678 HashAlgorithm::SHA256 => EcKdf::sha256_sp800(¶m),
679 HashAlgorithm::SHA384 => EcKdf::sha384_sp800(¶m),
680 HashAlgorithm::SHA512 => EcKdf::sha512_sp800(¶m),
681 HashAlgorithm::SHA1 // Too weak.
682 | HashAlgorithm::SHA224 // Too weak.
683 | _ =>
684 {
685 return Err(anyhow::anyhow!(
686 "Can't decrypt message: using {} with the \
687 ECDH KDF is not supported",
688 hash));
689 }
690 };
691
692 let ephemeral_key = e.decode_point(&Curve::Cv25519)?.0;
693
694 let ecdh1_derive_params = Ecdh1DeriveParams::new(
695 kdf, ephemeral_key);
696
697 // The derived key's symmetric algorithm is encoded in
698 // the public key.
699 let sym_key_size = sym.key_size()
700 .with_context(|| {
701 format!("Symmetric algorithm {:?} not support",
702 sym)
703 })? as u64;
704
705 let attributes = &[
706 Attribute::Class(ObjectClass::SECRET_KEY),
707 Attribute::KeyType(KeyType::AES),
708 Attribute::ValueLen(Ulong::new(sym_key_size.try_into()?)),
709 // Don't persist the KEK on the token.
710 Attribute::Token(false),
711 // Mark the KEK as unwrap capable.
712 Attribute::Unwrap(true),
713 ];
714
715 t!("Deriving {:?} KEK using {:?} as the hash function",
716 sym, hash);
717 let kek_handle = session.derive_key(
718 &Mechanism::Ecdh1Derive(ecdh1_derive_params),
719 key_info.private_key,
720 attributes)?;
721 t!("Derived KEK on token");
722
723 // We now 3.) use the KEK to decrypt the session key
724 // bundle.
725 //
726 // From PKCS#11, v3.2, draft 13, Section
727 // 6.16.3.17 AES Key Wrap:
728 //
729 // The mechanisms support only single-part
730 // operations, i.e. single part wrapping and
731 // unwrapping, and single-part encryption and
732 // decryption.
733 //
734 // • CKM_AES_KEY_WRAP
735 //
736 // For unwrapping, the mechanism decrypts the
737 // wrapped key. In case of a secret key, it
738 // truncates the result according to the
739 // CKA_KEY_TYPE attribute of the template and, if it
740 // has one and the key type supports it, the
741 // CKA_VALUE_LEN attribute of the template. The
742 // length specified in the template must not be less
743 // than n-7 bytes, where n is the length of the
744 // wrapped key. In case of a private key, the
745 // mechanism parses the encoding as defined in
746 // section 6.7 and ignores trailing zero bytes.
747
748 let attributes = &[
749 Attribute::Class(ObjectClass::SECRET_KEY),
750 Attribute::KeyType(KeyType::GENERIC_SECRET),
751 // Don't persist the session key on the token.
752 Attribute::Token(false),
753 // Mark the session key bundle as extractable.
754 Attribute::Extractable(true),
755 Attribute::Sensitive(false),
756 ];
757
758 t!("Unwrapping the session key bundle on the token");
759 let session_key_handle = session.unwrap_key(
760 &Mechanism::AesKeyWrap,
761 kek_handle,
762 key,
763 attributes)
764 .context("Unwrapping session key")?;
765 t!("Unwrapped the session key on the token");
766
767 // Finally, we 4.) extract the session key bundle.
768
769 let mut session_key_bundle = None;
770 for attribute in session.get_attributes(
771 session_key_handle,
772 &[ AttributeType::Value ])?
773 {
774 if let Attribute::Value(v) = attribute {
775 session_key_bundle = Some(v);
776 } else {
777 return Err(anyhow::anyhow!(
778 "Token returned unrequested attribute: {:?}",
779 attribute));
780 }
781 }
782
783 // The "session key" isn't just a session key. For v3
784 // PKESKs, we get:
785 //
786 // symm_alg_ID || session key || checksum || pkcs5_padding
787 //
788 // (The algorithm ID is one byte and the checksum is
789 // two bytes.)
790 //
791 // For v6 PKESKs, the symmetric algo is not included.
792 //
793 // For details, see
794 // https://www.rfc-editor.org/rfc/rfc9580.html#section-11.5-20.4.1
795 //
796 // As hinted at above, this interface operates below
797 // the OpenPGP level (we don't know if this is a v3
798 // PKESK, a v6 PKESK, or something else entirely). As
799 // such, we only remove the padding, and treat the
800 // rest as an opaque blob. The caller does the rest.
801 let session_key_bundle = if let Some(session_key_bundle)
802 = session_key_bundle
803 {
804 session_key_bundle
805 } else {
806 return Err(anyhow::anyhow!(
807 "Failed to export session key form token"));
808 };
809
810 let session_key_bundle = pkcs5_unpad(session_key_bundle)?;
811
812 t!("Unwrapped {} bytes of session key", session_key_bundle.len());
813
814 // The following may be useful for debugging, but
815 // leaks the session key.
816 //
817 //t!("Returning {} bytes: {}",
818 // session_key_bundle.len(),
819 // session_key_bundle.iter()
820 // .map(|k| format!("{:02X}", k))
821 // .collect::<Vec<_>>()
822 // .join(""));
823
824 Ok(session_key_bundle.into())
825 },
826
827 (KeyType::RSA,
828 mpi::PublicKey::RSA { n, .. },
829 mpi::Ciphertext::RSA { c }) =>
830 {
831 let key_info = key_info.check_standalone(
832 &self.openpgp_key, composite_info,
833 KeyType::RSA)?;
834
835 let value = c.value_padded((n.bits() + 7) / 8)
836 // value_padded returns an error if the target
837 // size is smaller than the input. This is quite
838 // unusual, but let's not fail here and instead
839 // just pass the ciphertext through as is and
840 // propagate the backend's error.
841 .unwrap_or_else(|_| c.value().into());
842
843 let shared_key = session.decrypt(
844 &Mechanism::RsaPkcs, key_info.private_key, &value)?;
845
846 Ok(shared_key.into())
847 },
848
849 (_, _, _) => {
850 Err(anyhow::anyhow!("{} keys are not supported",
851 self.openpgp_key.pk_algo()))
852 },
853 }
854 }
855}
856
857// This is based on pkcs5_unpad from sequoia-openpgp:
858//
859// https://gitlab.com/sequoia-pgp/sequoia/-/blob/6773ab9a/openpgp/src/crypto/ecdh.rs#L201
860/// Removes PKCS5 padding from a session key.
861///
862/// See [Section 8 of RFC 6637].
863///
864/// [Section 8 of RFC 6637]: https://tools.ietf.org/html/rfc6637#section-8
865fn pkcs5_unpad(mut buf: Vec<u8>) -> Result<Protected> {
866 if buf.len() > 0xff {
867 return Err(anyhow::anyhow!("Can't unpad: message too large").into());
868 }
869 let mut good = true;
870 let mut target_len = 0;
871
872 let padding = buf[buf.len() - 1];
873 if padding == 0 || padding as usize > buf.len() {
874 // The padding can't be "0" or longer than the buffer.
875 good = false
876 } else {
877 target_len = buf.len() - padding as usize;
878 for &b in &buf[target_len..] {
879 good = b == padding && good;
880 }
881 }
882 if good {
883 buf.truncate(target_len);
884 Ok(buf.into())
885 } else {
886 let sk: Protected = buf.into();
887 drop(sk);
888 Err(anyhow::anyhow!("Can't unpad: bad padding").into())
889 }
890}
891
892// Copied from sequoia-openpgp:
893// https://gitlab.com/sequoia-pgp/sequoia/-/blob/6773ab9a/openpgp/src/crypto/ecdh.rs#L383
894fn make_ecdh_derive_param<P, R>(recipient: &key::Key<P, R>,
895 curve: &Curve, hash: &HashAlgorithm,
896 sym: &SymmetricAlgorithm)
897 -> Vec<u8>
898 where P: key::KeyParts,
899 R: key::KeyRole
900{
901 // Param = curve_OID_len || curve_OID ||
902 // public_key_alg_ID || 03 || 01 || KDF_hash_ID ||
903 // KEK_alg_ID for AESKeyWrap || "Anonymous Sender " ||
904 // recipient_fingerprint;
905 let fp = recipient.fingerprint();
906 let mut param = Vec::with_capacity(
907 1 + curve.oid().len() // Length and Curve OID,
908 + 1 // Public key algorithm ID,
909 + 4 // KDF parameters,
910 + 20 // "Anonymous Sender ",
911 + fp.as_bytes().len()); // Recipients key fingerprint.
912 param.push(curve.oid().len() as u8);
913 param.extend_from_slice(curve.oid());
914 param.push(PublicKeyAlgorithm::ECDH.into());
915 // KDF parameters.
916 param.push(3); // Octet count of the following parameters.
917 param.push(1); // 1-octet value 0x01, reserved for future extensions.
918 param.push((*hash).into());
919 param.push((*sym).into());
920 param.extend_from_slice(b"Anonymous Sender ");
921 param.extend_from_slice(fp.as_bytes());
922 assert_eq!(param.len(),
923 1 + curve.oid().len() // Length and Curve OID,
924 + 1 // Public key algorithm ID,
925 + 4 // KDF parameters,
926 + 20 // "Anonymous Sender ",
927 + fp.as_bytes().len()); // Recipients key fingerprint.
928
929 param
930}
931
932/// Combines PQC and classical algorithms.
933///
934/// See [Section 4.2.1 of draft-ietf-openpgp-pqc-08].
935///
936/// [Section 4.2.1 of draft-ietf-openpgp-pqc-08]: https://www.ietf.org/archive/id/draft-ietf-openpgp-pqc-08.html#kem-key-combiner
937// Copied from sequoia-openpgp:
938// https://gitlab.com/sequoia-pgp/sequoia/-/blob/03595533/openpgp/src/crypto/asymmetric.rs#L480
939pub(crate) fn multi_key_combine(mlkem_key: &[u8],
940 ecdh_key: &[u8],
941 ecdh_ciphertext: &[u8],
942 ecdh_public: &[u8],
943 pk_algo: PublicKeyAlgorithm)
944 -> Result<SessionKey>
945{
946 // multiKeyCombine(
947 // mlkemKeyShare, ecdhKeyShare,
948 // ecdhCipherText, ecdhPublicKey,
949 // algId
950 // )
951 //
952 // Input:
953 // mlkemKeyShare - the ML-KEM key share encoded as an octet string
954 // ecdhKeyShare - the ECDH key share encoded as an octet string
955 // ecdhCipherText - the ECDH ciphertext encoded as an octet string
956 // ecdhPublicKey - the ECDH public key of the recipient as an octet string
957 // algId - the OpenPGP algorithm ID of the public-key encryption algorithm
958 //
959 // KEK = SHA3-256(
960 // mlkemKeyShare || ecdhKeyShare ||
961 // ecdhCipherText || ecdhPublicKey ||
962 // algId || domSep || len(domSep)
963 // )
964
965 let mut hash = HashAlgorithm::SHA3_256.context()?.for_digest();
966 hash.update(mlkem_key);
967 hash.update(ecdh_key);
968 hash.update(ecdh_ciphertext);
969 hash.update(ecdh_public);
970 hash.update(&[pk_algo.into()]);
971 // Domain separation and length octet.
972 hash.update(b"OpenPGPCompositeKDFv1\x15");
973
974 let mut kek = SessionKey::from(vec![0; 32]);
975 hash.digest(&mut kek)?;
976 Ok(kek)
977}