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