-
Notifications
You must be signed in to change notification settings - Fork 2
/
lib.rs
1431 lines (1288 loc) · 50.4 KB
/
lib.rs
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
//! Fortanix Self-Defending KMS
//!
//! This module implements the necessary logic to use secrets stored inside
//! Fortanix DSM for low-level signing and decryption operations, given proper
//! credentials.
//!
//! # Env variables for authentication with DSM
//!
//! - `FORTANIX_API_ENDPOINT`
//! - `FORTANIX_API_KEY`
//! - `FORTANIX_PKCS12_ID`, absolute path for a PKCS12 file (.pfx or .p12)
//! - `FORTANIX_APP_UUID`, required for certificate-based authentication
//!
//! # Proxy configuration
//!
//! The connection with DSM can be set through an http proxy. This crate
//! follows the `http_proxy` / `no_proxy` environment variables convention,
//! i.e., if `http_proxy` is set and the DSM API endpoint is not in
//! `no_proxy`, then a connection through said proxy is established.
use core::fmt::Display;
use std::borrow::Cow;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::env;
use std::io::Read;
use std::fs::File;
use std::net::IpAddr;
use std::str::FromStr;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use anyhow::{Context, Error, Result};
use http::uri::Uri;
use hyper::client::{Client as HyperClient, ProxyConfig};
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
use hyper_native_tls::native_tls::{TlsConnector, Identity};
use ipnetwork::IpNetwork;
use log::info;
use sdkms::api_model::Algorithm::Rsa;
use sdkms::api_model::{
AgreeKeyMechanism, AgreeKeyRequest, ApprovalStatus, DecryptRequest,
DecryptResponse, DigestAlgorithm, EllipticCurve as ApiCurve, KeyLinks,
KeyOperations, ObjectType, RsaEncryptionPaddingPolicy, RsaEncryptionPolicy,
RsaOptions, RsaSignaturePaddingPolicy, RsaSignaturePolicy, SignRequest,
SignResponse, Sobject, SobjectDescriptor, SobjectRequest,
};
use sdkms::{SdkmsClient as DsmClient, Error as DsmError, PendingApproval};
use sdkms::operations::Operation;
use semver::{Version, VersionReq};
use sequoia_openpgp::crypto::mem::Protected;
use sequoia_openpgp::crypto::{ecdh, mpi, Decryptor, SessionKey, Signer};
use sequoia_openpgp::packet::key::{
Key4, PrimaryRole, PublicParts, SubordinateRole, UnspecifiedRole,
};
use sequoia_openpgp::packet::prelude::SecretKeyMaterial;
use sequoia_openpgp::packet::signature::SignatureBuilder;
use sequoia_openpgp::packet::{Key, UserID};
use sequoia_openpgp::serialize::SerializeInto;
use sequoia_openpgp::types::{
Curve as SequoiaCurve, Features, HashAlgorithm, KeyFlags,
PublicKeyAlgorithm, SignatureType, SymmetricAlgorithm,
};
use sequoia_openpgp::{Cert, Packet};
use serde_derive::{Deserialize, Serialize};
use uuid::Uuid;
mod der;
/// DsmAgent implements [Signer] and [Decryptor] with secrets stored inside
/// Fortanix DSM.
///
/// [Decryptor]: ../../crypto/trait.Decryptor.html
/// [Signer]: ../../crypto/trait.Signer.html
pub struct DsmAgent {
credentials: Credentials,
descriptor: SobjectDescriptor,
public: Key<PublicParts, UnspecifiedRole>,
role: Role,
}
/// The version of this crate.
pub const SQ_DSM_VERSION: &str = env!("CARGO_PKG_VERSION");
const DSM_LABEL_PGP: &str = "sq_dsm";
const ENV_API_KEY: &str = "FORTANIX_API_KEY";
const ENV_API_ENDPOINT: &str = "FORTANIX_API_ENDPOINT";
const ENV_APP_UUID: &str = "FORTANIX_APP_UUID";
const ENV_HTTP_PROXY: &str = "http_proxy";
const ENV_NO_PROXY: &str = "no_proxy";
const ENV_P12: &str = "FORTANIX_PKCS12_ID";
const MIN_DSM_VERSION: &str = "4.2.0";
// As seen on sdkms-client-rust/blob/master/examples/approval_request.rs
const OP_APPROVAL_MSG: &str = "This operation requires approval";
#[derive(Clone)]
pub enum Auth {
ApiKey(String),
// App UUID and PKCS12 identity
Cert(Uuid, Identity),
}
impl Auth {
pub fn from_options_or_env(
cli_api_key: Option<&str>,
cli_client_cert: Option<&str>,
cli_app_uuid: Option<&str>,
) -> Result<Self> {
// Try API key
let api_key = match (cli_api_key, env::var(ENV_API_KEY).ok()) {
(Some(api_key), None) => Some(api_key.to_string()),
(None, Some(api_key)) => Some(api_key),
(Some(api_key), Some(_)) => {
println!(
"API key both in parameters and env; ignoring env"
);
Some(api_key.to_string())
},
(None, None) => None,
};
// Try client cert
let cert_based = {
let client_cert = match (cli_client_cert, env::var(ENV_P12).ok()) {
(Some(cert), None) => Some(cert.to_string()),
(None, Some(cert)) => Some(cert),
(Some(cert), Some(_)) => {
println!(
"P12 cert both in parameters and env; ignoring env"
);
Some(cert.to_string())
},
(None, None) => None,
};
let app_uuid = match (cli_app_uuid, env::var(ENV_APP_UUID).ok()) {
(Some(id), None) => Some(id.to_string()),
(None, Some(id)) => Some(id),
(Some(id), Some(_)) => {
println!(
"APP UUID both in parameters and env; ignoring env"
);
Some(id.to_string())
},
(None, None) => None,
};
match (client_cert, app_uuid) {
(Some(cert), Some(uuid)) => Some((cert, uuid)),
_ => None,
}
};
match (api_key, cert_based) {
(Some(api_key), None) => Ok(Auth::ApiKey(api_key)),
(Some(api_key), Some(_)) => {
println!(
"Multiple auth methods found. Using API key"
);
Ok(Auth::ApiKey(api_key))
},
(None, Some((client_cert, app_uuid))) => {
let p12_id = try_unlock_p12(client_cert)?;
let uuid = Uuid::parse_str(&app_uuid)
.context("bad app UUID")?;
Ok(Auth::Cert(uuid, p12_id))
}
(None, None) => return Err(Error::msg("no auth credentials found")),
}
}
}
#[derive(Clone)]
pub struct Credentials {
api_endpoint: String,
auth: Auth,
}
trait OperateOrAskApproval<S: Into<Cow<'static, str>> + Display> {
fn __retry_until_resolved<O: Operation>(&self, pa: &PendingApproval<O>, desc: S)
-> Result<O::Output>;
fn __update_sobject(&self, uuid: &Uuid, req: &SobjectRequest, desc: S)
-> Result<Sobject>;
fn __sign(&self, req: &SignRequest, desc: S)
-> Result<SignResponse>;
fn __decrypt(&self, req: &DecryptRequest, desc: S)
-> Result<DecryptResponse>;
fn __export_sobject(&self, descriptor: &SobjectDescriptor, desc: S)
-> Result<Sobject>;
// Currently unsupported due to backend constraints.
fn __agree(&self, req: &AgreeKeyRequest, desc: S)
-> Result<Sobject>;
}
impl <S: Into<Cow<'static, str>> + Display> OperateOrAskApproval<S> for DsmClient {
fn __retry_until_resolved<O: Operation>(
&self, pa: &PendingApproval<O>, desc: S
) -> Result<O::Output> {
let id = pa.request_id();
while pa.status(&self)? == ApprovalStatus::Pending {
println!(
"Approval request {} ({}) pending. Press Enter to check status",
id, desc
);
std::io::stdin().read_line(&mut String::new())?;
}
match pa.result(&self) {
Ok(output) => {
println!("Approval request {} approved", id);
output.map_err(|e|e.into())
}
Err(e) => {
println!("Approval request {} denied", id);
Err(e.into())
}
}
}
fn __update_sobject(
&self, uuid: &Uuid, req: &SobjectRequest, desc: S
) -> Result<Sobject> {
match self.update_sobject(uuid, req) {
Err(DsmError::Forbidden(ref msg)) if msg == OP_APPROVAL_MSG => {
info!("Creating UPDATE approval request: {}", desc);
let pa = self.request_approval_to_update_sobject(
uuid, req, Some(format!("sq-dsm: {}", desc))
)?;
self.__retry_until_resolved(&pa, desc)
}
Err(err) => Err(err.into()),
Ok(resp) => Ok(resp)
}
}
fn __sign(&self, req: &SignRequest, desc: S) -> Result<SignResponse> {
match self.sign(req) {
Err(DsmError::Forbidden(ref msg)) if msg == OP_APPROVAL_MSG => {
info!("Creating SIGN approval request: {}", desc);
let pa = self.request_approval_to_sign(
req, Some(format!("sq-dsm: {}", desc))
)?;
self.__retry_until_resolved(&pa, desc)
}
Err(err) => Err(err.into()),
Ok(resp) => Ok(resp)
}
}
fn __decrypt(
&self, req: &DecryptRequest, desc: S
) -> Result<DecryptResponse> {
match self.decrypt(req) {
Err(DsmError::Forbidden(ref msg)) if msg == OP_APPROVAL_MSG => {
info!("Creating DECRYPT approval request: {}", desc);
let pa = self.request_approval_to_decrypt(
req, Some(format!("sq-dsm: {}", desc))
)?;
self.__retry_until_resolved(&pa, desc)
}
Err(err) => Err(err.into()),
Ok(resp) => Ok(resp)
}
}
fn __export_sobject(
&self, descriptor: &SobjectDescriptor, desc: S
) -> Result<Sobject> {
match self.export_sobject(descriptor) {
Err(DsmError::Forbidden(ref msg)) if msg == OP_APPROVAL_MSG => {
info!("Creating EXPORT approval request: {}", desc);
let pa = self.request_approval_to_export_sobject(
descriptor, Some(format!("sq-dsm: {}", desc))
)?;
self.__retry_until_resolved(&pa, desc)
}
Err(err) => Err(err.into()),
Ok(resp) => Ok(resp)
}
}
fn __agree(&self, req: &AgreeKeyRequest, _desc: S) -> Result<Sobject> {
match self.agree(req) {
Err(DsmError::Forbidden(ref msg)) if msg == OP_APPROVAL_MSG => {
// FIXME: In DSM, AGREEKEY results in a transient key which
// cannot be retrieved with the DSM client.
Err(Error::msg("Quorum approval for EC decryption unsupported"))
}
Err(err) => Err(err.into()),
Ok(resp) => Ok(resp)
}
}
}
impl Credentials {
pub fn new(auth: Auth) -> Result<Self> {
let api_endpoint = env::var(ENV_API_ENDPOINT)
.with_context(|| format!("{} absent", ENV_API_ENDPOINT))?;
Ok(Self { api_endpoint, auth })
}
fn dsm_client(&self) -> Result<DsmClient> {
let builder = DsmClient::builder()
.with_api_endpoint(&self.api_endpoint);
let cli = match &self.auth {
Auth::ApiKey(api_key) => {
let tls_conn = TlsConnector::builder()
.build()?;
let ssl = NativeTlsClient::from(tls_conn);
let hyper_client = maybe_proxied(&self.api_endpoint, ssl)?;
let cli = builder
.with_hyper_client(Arc::new(hyper_client))
.build()
.context("could not initiate a DSM client")?;
cli.authenticate_with_api_key(&api_key)?
},
Auth::Cert(app_uuid, identity) => {
let tls_conn = TlsConnector::builder()
.identity(identity.clone())
.build()?;
let ssl = NativeTlsClient::from(tls_conn);
let hyper_client = maybe_proxied(&self.api_endpoint, ssl)?;
let cli = builder
.with_hyper_client(Arc::new(hyper_client))
.build()
.context("could not initiate a DSM client")?;
cli.authenticate_with_cert(Some(&app_uuid))?
}
};
let min = VersionReq::parse(&(">=".to_string() + MIN_DSM_VERSION))?;
let ver = Version::parse(&cli.version()?.version)?;
if min.matches(&ver) {
Ok(cli)
} else {
Err(Error::msg(format!(
"Incompatible DSM version: ({} < {})",
ver,
MIN_DSM_VERSION
)))
}
}
}
#[derive(PartialEq)]
enum Role {
Signer,
Decryptor,
}
impl DsmAgent {
/// Returns a DsmAgent with signing capabilities, corresponding to the given
/// key name.
pub fn new_signer(credentials: Credentials, key_name: &str) -> Result<Self> {
let dsm_client = credentials.dsm_client()?;
let descriptor = SobjectDescriptor::Name(key_name.to_string());
let sobject = dsm_client
.get_sobject(None, &descriptor)
.context(format!("could not get primary key {}", key_name))?;
let key = PublicKey::from_sobject(sobject, KeyRole::Primary)?;
Ok(DsmAgent {
credentials,
descriptor,
public: key.sequoia_key.context("key is not loaded")?,
role: Role::Signer,
})
}
/// Returns a DsmAgent with decryption capabilities, corresponding to the
/// given key name.
pub fn new_decryptor(credentials: Credentials, key_name: &str) -> Result<Self> {
let dsm_client = credentials.dsm_client()?;
let descriptor = SobjectDescriptor::Name(key_name.to_string());
let sobject = dsm_client
.get_sobject(None, &descriptor)
.context(format!("could not get primary key {}", key_name))?;
if let Some(KeyLinks { subkeys, .. }) = sobject.links {
if subkeys.len() == 0 {
return Err(Error::msg("No subkeys found in DSM"));
}
let uid = subkeys[0];
let descriptor = SobjectDescriptor::Kid(uid);
let sobject = dsm_client
.get_sobject(None, &descriptor)
.context("could not get subkey".to_string())?;
let key = PublicKey::from_sobject(sobject, KeyRole::Subkey)?;
Ok(DsmAgent {
credentials,
descriptor,
public: key.sequoia_key.context("key is not loaded")?,
role: Role::Decryptor,
})
} else {
Err(Error::msg("was not able to get decryption subkey"))
}
}
}
#[derive(Clone)]
struct PublicKey {
role: KeyRole,
descriptor: SobjectDescriptor,
sequoia_key: Option<Key<PublicParts, UnspecifiedRole>>,
}
enum SupportedPkAlgo {
Rsa(u32),
Ec(ApiCurve),
Curve25519,
}
#[derive(Clone, Debug, PartialEq)]
enum KeyRole {
Primary,
Subkey,
}
#[derive(Serialize, Deserialize)]
struct KeyMetadata {
certificate: String,
}
impl KeyMetadata {
fn from_primary_sobject(sob: &Sobject) -> Result<Self> {
match &sob.custom_metadata {
Some(dict) => {
if !dict.contains_key(DSM_LABEL_PGP) {
return Err(anyhow::anyhow!("malformed metadata"));
}
let key_md: KeyMetadata =
serde_json::from_str(&dict[DSM_LABEL_PGP])?;
Ok(key_md)
}
None => Err(anyhow::anyhow!("no custom metadata found")),
}
}
}
/// Generates an OpenPGP key with secrets stored in DSM. At the OpenPGP
/// level, this method produces a key consisting of
///
/// - A primary signing key (flags C + S),
/// - a transport and storage encryption subkey (flags Et + Er).
///
/// At the DSM level, this method creates the two corresponding Sobjects.
/// The encryption key's KID is stored as a custom metadata field of the
/// signing key.
///
/// The public certificate (Transferable Public Key) is computed, stored as
/// an additional custom metadata field on the primary key, and returned.
pub fn generate_key(
key_name: &str,
validity_period: Option<Duration>,
user_id: Option<&str>,
algo: Option<&str>,
exportable: bool,
credentials: Credentials,
) -> Result<()> {
// User ID
let uid: UserID = match user_id {
Some(id) => id.into(),
None => return Err(Error::msg("no User ID")),
};
// Cipher Suite
let algorithm = match algo {
Some("rsa2k") => SupportedPkAlgo::Rsa(2048),
Some("rsa3k") => SupportedPkAlgo::Rsa(3072),
Some("rsa4k") => SupportedPkAlgo::Rsa(4096),
Some("cv25519") => SupportedPkAlgo::Curve25519,
Some("nistp256") => SupportedPkAlgo::Ec(ApiCurve::NistP256),
Some("nistp384") => SupportedPkAlgo::Ec(ApiCurve::NistP384),
Some("nistp521") => SupportedPkAlgo::Ec(ApiCurve::NistP521),
_ => unreachable!("argument has a default value"),
};
let dsm_client = credentials.dsm_client()?;
info!("create primary key");
let primary = PublicKey::create(
&dsm_client,
key_name.to_string(),
KeyRole::Primary,
&algorithm,
exportable,
)
.context("could not create primary key")?;
info!("create decryption subkey");
let subkey = PublicKey::create(
&dsm_client,
key_name.to_string(),
KeyRole::Subkey,
&algorithm,
exportable,
)?;
info!("bind subkey to primary key in DSM");
let links = KeyLinks {
parent: Some(primary.uid()?),
..Default::default()
};
let link_update_req = SobjectRequest {
links: Some(links),
..Default::default()
};
dsm_client.__update_sobject(
&subkey.uid()?, &link_update_req, "bind subkey to primary key"
)?;
// Primary + sig, UserID + sig, subkey + sig
let mut packets = Vec::<Packet>::with_capacity(6);
// Self-sign primary key
info!("generate certificate - self-sign primary key");
let prim: Key<PublicParts, PrimaryRole> = primary
.sequoia_key
.clone()
.context("unloaded primary key")?
.into();
let prim_creation_time = prim.creation_time();
let mut prim_signer = DsmAgent::new_signer(credentials, &key_name)?;
let primary_flags = KeyFlags::empty().set_certification().set_signing();
let prim_sig_builder = SignatureBuilder::new(SignatureType::DirectKey)
.set_features(Features::sequoia())?
.set_key_flags(primary_flags.clone())?
.set_key_validity_period(validity_period)?
.set_signature_creation_time(prim_creation_time)?
.set_preferred_symmetric_algorithms(vec![
SymmetricAlgorithm::AES256,
SymmetricAlgorithm::AES128,
])?
.set_preferred_hash_algorithms(vec![
HashAlgorithm::SHA512,
HashAlgorithm::SHA256,
])?
.set_hash_algo(HashAlgorithm::SHA512);
// A direct key signature is always over the primary key.
let prim_sig = prim_sig_builder.sign_direct_key(&mut prim_signer, None)?;
packets.push(prim.into());
packets.push(prim_sig.into());
let mut cert = Cert::try_from(packets)?;
// User ID + signature
info!("sign user ID");
let builder = SignatureBuilder::new(SignatureType::PositiveCertification)
.set_primary_userid(true)?
.set_features(Features::sequoia())?
.set_key_flags(primary_flags)?
.set_key_validity_period(validity_period)?
.set_signature_creation_time(prim_creation_time)?
.set_preferred_symmetric_algorithms(vec![
SymmetricAlgorithm::AES256,
SymmetricAlgorithm::AES128,
])?
.set_preferred_hash_algorithms(vec![
HashAlgorithm::SHA512,
HashAlgorithm::SHA256,
])?;
let uid_sig = uid.bind(&mut prim_signer, &cert, builder)?;
cert = cert.insert_packets(vec![Packet::from(uid), uid_sig.into()])?;
// Subkey + signature
info!("sign subkey");
let subkey_public: Key<PublicParts, SubordinateRole> = subkey
.sequoia_key
.as_ref()
.context("unloaded subkey")?
.clone()
.into();
let subkey_creation_time = subkey_public.creation_time();
let subkey_flags = KeyFlags::empty()
.set_storage_encryption()
.set_transport_encryption();
let builder = SignatureBuilder::new(SignatureType::SubkeyBinding)
.set_key_validity_period(validity_period)?
.set_hash_algo(HashAlgorithm::SHA512)
.set_signature_creation_time(subkey_creation_time)?
.set_key_flags(subkey_flags)?;
let signature = subkey_public.bind(&mut prim_signer, &cert, builder)?;
cert = cert
.insert_packets(vec![Packet::from(subkey_public), signature.into()])?;
info!("store certificate in DSM");
let armored = String::from_utf8(cert.armored().to_vec()?)?;
let key_md = KeyMetadata {
certificate: armored,
};
let key_json = serde_json::to_string(&key_md)?;
let mut metadata = HashMap::<String, String>::new();
metadata.insert(DSM_LABEL_PGP.to_string(), key_json);
let update_req = SobjectRequest {
custom_metadata: Some(metadata),
..Default::default()
};
dsm_client.__update_sobject(
&primary.uid()?, &update_req, "store PGP certificate as metadata"
)?;
Ok(())
}
/// Extracts the certificate of the corresponding PGP key. Note that this
/// certificate, created at key-generation time, is stored in the custom
/// metadata of the Security Object representing the primary key.
pub fn extract_cert(key_name: &str, cred: Credentials) -> Result<Cert> {
info!("dsm extract_cert");
let dsm_client = cred.dsm_client()?;
let metadata = {
let sobject = dsm_client
.get_sobject(None, &SobjectDescriptor::Name(key_name.to_string()))
.context(format!("could not get primary key {}", key_name))?;
match sobject.custom_metadata {
None => return Err(Error::msg("metadata not found".to_string())),
Some(dict) => dict,
}
};
if !metadata.contains_key(DSM_LABEL_PGP) {
return Err(Error::msg("malformed metadata in DSM".to_string()));
}
let key_md: KeyMetadata = serde_json::from_str(&metadata[DSM_LABEL_PGP])?;
Ok(Cert::from_str(&key_md.certificate)?)
}
pub fn extract_tsk_from_dsm(key_name: &str, cred: Credentials) -> Result<Cert> {
// Extract all secrets as packets
let dsm_client = cred.dsm_client()?;
let mut packets = Vec::<Packet>::with_capacity(2);
// Primary key
let prim_sob = dsm_client
.__export_sobject(
&SobjectDescriptor::Name(key_name.to_string()),
"export primary key",
)
.context(format!("could not export primary secret {}", key_name))?;
let key_md = KeyMetadata::from_primary_sobject(&prim_sob)?;
let packet = secret_packet_from_sobject(&prim_sob, KeyRole::Primary)?;
packets.push(packet);
// Subkeys
if let Some(KeyLinks { subkeys, .. }) = prim_sob.links {
for uid in &subkeys {
let sob = dsm_client
.__export_sobject(
&SobjectDescriptor::Kid(*uid),
"export subkey",
)
.context(format!("could not export subkey secret {}", key_name))?;
let packet = secret_packet_from_sobject(&sob, KeyRole::Subkey)?;
packets.push(packet);
}
} else {
return Err(Error::msg("could not find subkeys"));
}
// Merge with the known public certificate
let priv_cert = Cert::try_from(packets)?;
let cert = Cert::from_str(&key_md.certificate)?;
let merged = cert
.merge_public_and_secret(priv_cert)
.context("Could not merge public and private certificates")?;
Ok(merged)
}
impl PublicKey {
fn create(
client: &DsmClient,
name: String,
role: KeyRole,
algo: &SupportedPkAlgo,
exportable: bool,
) -> Result<Self> {
let description = Some("Created with sq-dsm".to_string());
let mut sobject_request = match (&role, algo) {
(KeyRole::Primary, SupportedPkAlgo::Rsa(key_size)) => {
let sig_policy = RsaSignaturePolicy {
padding: Some(RsaSignaturePaddingPolicy::Pkcs1V15 {}),
};
let rsa_options = Some(RsaOptions {
signature_policy: vec![sig_policy],
..Default::default()
});
SobjectRequest {
name: Some(name),
description,
obj_type: Some(ObjectType::Rsa),
key_ops: Some(
KeyOperations::SIGN | KeyOperations::APPMANAGEABLE,
),
key_size: Some(*key_size),
rsa: rsa_options,
..Default::default()
}
}
(KeyRole::Subkey, SupportedPkAlgo::Rsa(key_size)) => {
let enc_policy = RsaEncryptionPolicy {
padding: Some(RsaEncryptionPaddingPolicy::Pkcs1V15 {}),
};
let rsa_options = Some(RsaOptions {
encryption_policy: vec![enc_policy],
..Default::default()
});
SobjectRequest {
name: Some(name + " (PGP: decryption subkey)"),
description,
obj_type: Some(ObjectType::Rsa),
key_ops: Some(
KeyOperations::DECRYPT | KeyOperations::APPMANAGEABLE,
),
key_size: Some(*key_size),
rsa: rsa_options,
..Default::default()
}
}
(KeyRole::Primary, SupportedPkAlgo::Curve25519) => SobjectRequest {
name: Some(name),
description,
obj_type: Some(ObjectType::Ec),
key_ops: Some(
KeyOperations::SIGN | KeyOperations::APPMANAGEABLE,
),
elliptic_curve: Some(ApiCurve::Ed25519),
..Default::default()
},
(KeyRole::Subkey, SupportedPkAlgo::Curve25519) => {
let name = name + " (PGP: decryption subkey)";
SobjectRequest {
name: Some(name),
description,
obj_type: Some(ObjectType::Ec),
key_ops: Some(
KeyOperations::AGREEKEY | KeyOperations::APPMANAGEABLE,
),
elliptic_curve: Some(ApiCurve::X25519),
..Default::default()
}
}
(KeyRole::Primary, SupportedPkAlgo::Ec(curve)) => SobjectRequest {
name: Some(name),
description,
obj_type: Some(ObjectType::Ec),
key_ops: Some(
KeyOperations::SIGN | KeyOperations::APPMANAGEABLE,
),
elliptic_curve: Some(*curve),
..Default::default()
},
(KeyRole::Subkey, SupportedPkAlgo::Ec(curve)) => SobjectRequest {
name: Some(name + " (PGP: decryption subkey)"),
description,
obj_type: Some(ObjectType::Ec),
key_ops: Some(
KeyOperations::AGREEKEY | KeyOperations::APPMANAGEABLE,
),
elliptic_curve: Some(*curve),
..Default::default()
},
};
if exportable {
sobject_request.key_ops =
Some(sobject_request.key_ops.unwrap() | KeyOperations::EXPORT)
}
let sobject = client.create_sobject(&sobject_request)
.context("dsm client could not create sobject")?;
PublicKey::from_sobject(sobject, role)
}
fn from_sobject(sob: Sobject, role: KeyRole) -> Result<Self> {
let descriptor = SobjectDescriptor::Kid(sob.kid.context("no kid")?);
let time: SystemTime = sob.created_at.to_datetime().into();
let raw_pk = sob.pub_key.context("public bits of sobject missing")?;
let (pk_algo, pk_material, role) = match sob.obj_type {
ObjectType::Ec => match sob.elliptic_curve {
Some(ApiCurve::Ed25519) => {
if role == KeyRole::Subkey {
return Err(Error::msg("signing subkeys unsupported"));
}
let pk_algo = PublicKeyAlgorithm::EdDSA;
let curve = SequoiaCurve::Ed25519;
// Strip the leading OID
let point = mpi::MPI::new_compressed_point(&raw_pk[12..]);
let ec_pk = mpi::PublicKey::EdDSA { curve, q: point };
(pk_algo, ec_pk, KeyRole::Primary)
}
Some(ApiCurve::X25519) => {
let pk_algo = PublicKeyAlgorithm::ECDH;
let curve = SequoiaCurve::Cv25519;
// Strip the leading OID
let point = mpi::MPI::new_compressed_point(&raw_pk[12..]);
let ec_pk = mpi::PublicKey::ECDH {
curve,
q: point,
hash: HashAlgorithm::SHA512,
sym: SymmetricAlgorithm::AES256,
};
(pk_algo, ec_pk, KeyRole::Subkey)
}
Some(curve @ ApiCurve::NistP256)
| Some(curve @ ApiCurve::NistP384)
| Some(curve @ ApiCurve::NistP521) => {
let curve = sequoia_curve_from_api_curve(curve)?;
let (x, y) = der::parse::ec_point_x_y(&raw_pk)?;
let bits_field = curve.bits()
.ok_or_else(|| Error::msg("bad curve"))?;
let point = mpi::MPI::new_point(&x, &y, bits_field);
let (pk_algo, ec_pk) = match role {
KeyRole::Primary => (
PublicKeyAlgorithm::ECDSA,
mpi::PublicKey::ECDSA { curve, q: point },
),
KeyRole::Subkey => (
PublicKeyAlgorithm::ECDH,
mpi::PublicKey::ECDH {
curve,
q: point,
hash: HashAlgorithm::SHA512,
sym: SymmetricAlgorithm::AES256,
},
),
};
(pk_algo, ec_pk, role)
}
Some(curve) => {
return Err(Error::msg(format!(
"unimplemented curve: {:?}",
curve
)))
}
None => {
return Err(Error::msg("Sobject has no curve attribute"))
}
},
ObjectType::Rsa => {
let pk = der::parse::rsa_n_e(&raw_pk)?;
let pk_material = mpi::PublicKey::RSA {
e: pk.e.into(),
n: pk.n.into()
};
let pk_algo = PublicKeyAlgorithm::RSAEncryptSign;
(pk_algo, pk_material, role)
}
t @ _ => {
return Err(Error::msg(format!("unknown object : {:?}", t)));
}
};
let key = Key::V4(
Key4::new(time, pk_algo, pk_material)
.context("cannot import RSA key into Sequoia")?,
);
Ok(PublicKey {
descriptor,
role,
sequoia_key: Some(key),
})
}
fn uid(&self) -> Result<Uuid> {
match self.descriptor {
SobjectDescriptor::Kid(x) => Ok(x),
_ => Err(Error::msg("bad descriptor")),
}
}
}
impl Signer for DsmAgent {
fn public(&self) -> &Key<PublicParts, UnspecifiedRole> { &self.public }
fn sign(
&mut self,
hash_algo: HashAlgorithm,
digest: &[u8],
) -> Result<mpi::Signature> {
if self.role != Role::Signer {
return Err(Error::msg("bad role for DSM agent"));
}
let dsm_client = self.credentials.dsm_client()
.context("could not initialize the http client")?;
let hash_alg = match hash_algo {
HashAlgorithm::SHA1 => DigestAlgorithm::Sha1,
HashAlgorithm::SHA512 => DigestAlgorithm::Sha512,
HashAlgorithm::SHA256 => DigestAlgorithm::Sha256,
hash @ _ => {
panic!("unimplemented: {}", hash);
}
};
match self.public.pk_algo() {
PublicKeyAlgorithm::RSAEncryptSign => {
let sign_req = SignRequest {
key: Some(self.descriptor.clone()),
hash_alg,
hash: Some(digest.to_vec().into()),
data: None,
mode: None,
deterministic_signature: None,
};
let sign_resp = dsm_client.__sign(&sign_req, "signature")
.context("bad response for signature request")?;
let plain: Vec<u8> = sign_resp.signature.into();
Ok(mpi::Signature::RSA { s: plain.into() })
}
PublicKeyAlgorithm::EdDSA => {
let sign_req = SignRequest {
key: Some(self.descriptor.clone()),
hash_alg,
data: Some(digest.to_vec().into()),
hash: None,
mode: None,
deterministic_signature: None,
};
let sign_resp = dsm_client.__sign(&sign_req, "signature")
.context("bad response for signature request")?;
let plain: Vec<u8> = sign_resp.signature.into();
Ok(mpi::Signature::EdDSA {
r: mpi::MPI::new(&plain[..32]),
s: mpi::MPI::new(&plain[32..]),
})
}
PublicKeyAlgorithm::ECDSA => {
let sign_req = SignRequest {
key: Some(self.descriptor.clone()),
hash_alg,
hash: Some(digest.to_vec().into()),
data: None,
mode: None,
deterministic_signature: None,
};
let sign_resp = dsm_client.__sign(&sign_req, "signature")
.context("bad response for signature request")?;
let plain: Vec<u8> = sign_resp.signature.into();
let (r, s) = der::parse::ecdsa_r_s(&plain)
.context("could not decode ECDSA der")?;
Ok(mpi::Signature::ECDSA {
r: r.to_vec().into(),
s: s.to_vec().into(),
})
}
algo @ _ => {
return Err(Error::msg(format!("unknown algo: {}", algo)));
}
}
}
}
impl Decryptor for DsmAgent {