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