-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
manager.rs
2503 lines (2233 loc) · 103 KB
/
manager.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
use std::{collections::HashMap, convert::TryFrom, ops::Deref, str::FromStr, sync::Arc};
use bytes::Bytes;
use chrono::Duration;
use rpki::{
ca::{
idexchange::{self, ServiceUri},
idexchange::{CaHandle, ChildHandle, ParentHandle},
provisioning,
provisioning::{
IssuanceRequest, ProvisioningCms, ResourceClassListResponse, ResourceClassName, RevocationRequest,
RevocationResponse,
},
publication,
publication::{ListReply, Publish, PublishDelta, Update, Withdraw},
},
crypto::KeyIdentifier,
repository::resources::ResourceSet,
uri,
};
use crate::{
commons::{
actor::Actor,
api::{
import::{ExportChild, ImportChild},
rrdp::PublishElement,
BgpSecCsrInfoList, BgpSecDefinitionUpdates, IdCertInfo, ParentServerInfo, PublicationServerInfo,
RoaConfigurationUpdates, Timestamp,
},
api::{
AddChildRequest, AspaDefinitionList, AspaDefinitionUpdates, AspaProvidersUpdate, CaCommandDetails,
CertAuthList, CertAuthSummary, ChildCaInfo, CommandHistory, CommandHistoryCriteria, CustomerAsn,
ParentCaContact, ParentCaReq, ReceivedCert, RepositoryContact, RtaName, UpdateChildRequest,
},
crypto::KrillSigner,
error::Error,
eventsourcing::{Aggregate, AggregateStore},
util::{cmslogger::CmsLogger, httpclient},
KrillResult,
},
constants::{CASERVER_NS, STATUS_NS, TA_PROXY_SERVER_NS, TA_SIGNER_SERVER_NS},
daemon::{
auth::common::permissions::Permission,
auth::Handle,
ca::{
CaObjectsStore, CaStatus, CertAuth, CertAuthCommand, CertAuthCommandDetails, DeprecatedRepository,
ResourceTaggedAttestation, RtaContentRequest, RtaPrepareRequest, StatusStore,
},
config::Config,
mq::{now, Task, TaskQueue},
},
pubd::RepositoryManager,
ta::{
self, ta_handle, TrustAnchorProxy, TrustAnchorProxyCommand, TrustAnchorProxyInitCommand,
TrustAnchorSignedRequest, TrustAnchorSignedResponse, TrustAnchorSigner, TrustAnchorSignerCommand,
TrustAnchorSignerInfo, TrustAnchorSignerInitCommand, TrustAnchorSignerInitCommandDetails, TA_NAME,
},
};
use super::{CertAuthInitCommand, CertAuthInitCommandDetails};
//------------ CaManager -----------------------------------------------------
pub struct CaManager {
// Used to manage CAs
ca_store: AggregateStore<CertAuth>,
// Used to manage objects for CAs. Also shared with the ca_store as well
// as a listener so that it can create manifests and CRLs as needed. Accessed
// here for publishing.
ca_objects_store: Arc<CaObjectsStore>,
// Keep track of CA parent and CA repository interaction status.
status_store: StatusStore,
// We may have a TA Proxy that we need to manage. Many functions are
// similar to CA operations, so it makes sense to manage this as a
// special kind of CA here.
ta_proxy_store: Option<AggregateStore<TrustAnchorProxy>>,
// We may also have a local TA signer - in case we are running in
// testbed or benchmarking mode - so that we can do all TA signing
// without the need for user interactions through the API and
// TA signer CLI.
ta_signer_store: Option<AggregateStore<TrustAnchorSigner>>,
// shared task queue:
// - listens for events in the ca_store
// - processed by the Scheduler
// - can be used here to schedule tasks through the api
tasks: Arc<TaskQueue>,
config: Arc<Config>,
signer: Arc<KrillSigner>,
// System actor is used for (scheduled or triggered) system actions where
// we have no operator actor context.
system_actor: Actor,
}
impl CaManager {
/// Builds a new CaServer. Will return an error if the CA store cannot be initialized.
pub async fn build(
config: Arc<Config>,
tasks: Arc<TaskQueue>,
signer: Arc<KrillSigner>,
system_actor: Actor,
) -> KrillResult<Self> {
// Create the AggregateStore for the event-sourced `CertAuth` structures that handle
// most CA functions.
let mut ca_store =
AggregateStore::<CertAuth>::create(&config.storage_uri, CASERVER_NS, config.use_history_cache)?;
if let Err(e) = ca_store.warm() {
// Start to 'warm' the cache. This serves two purposes:
// 1. this ensures that all `CertAuth` structs are available in memory
// 2. this ensures that there are no apparent data issues
//
// If there are issues, then we need to bail out. Krill 0.14.0+ uses single
// files for all change sets, and files are first completely written to disk,
// and only then renamed.
//
// In other words, if we fail to warm the cache then this points at:
// - data corruption
// - user started
error!(
"Could not warm up cache, data seems corrupt. You may need to restore a backup. Error was: {}",
e
);
}
// Create the `CaObjectStore` that is responsible for maintaining CA objects: the `CaObjects`
// for a CA gets copies of all ROAs and issued certificates from the `CertAuth` and is responsible
// for manifests and CRL generation.
let ca_objects_store = Arc::new(CaObjectsStore::create(
&config.storage_uri,
config.issuance_timing.clone(),
signer.clone(),
)?);
// Register the `CaObjectsStore` as a pre-save listener to the 'ca_store' so that it can update
// its ROAs and issued certificates and/or generate manifests and CRLs when relevant changes
// occur in a `CertAuth`.
ca_store.add_pre_save_listener(ca_objects_store.clone());
// Register the `MessageQueue` as a pre-save listener to 'ca_store' so that relevant changes in
// a `CertAuth` can trigger follow-up actions. This is done as pre-save listener, because commands
// that would result in a follow-up should fail, if the task cannot be planned.
//
// Tasks will typically be picked up after the CA changes are committed, but they may also be
// picked up sooner by another thread. Because of that the tasks will remember which minimal version
// of the CA they are intended for, so that they can be rescheduled should they have been picked up
// too soon.
//
// An example of a triggered task: schedule a synchronisation with the repository (publication
// server) in case ROAs have been updated.
ca_store.add_pre_save_listener(tasks.clone());
// Now also register the `MessageQueue` as a post-save listener. We use this to send best-effort
// post-save signals to children in case a certificate was updated or a child key was revoked.
// This is a no-op for remote children (we cannot send a signal over RFC 6492).
ca_store.add_post_save_listener(tasks.clone());
// Create TA proxy store if we need it.
let ta_proxy_store = if config.ta_proxy_enabled() {
let mut store = AggregateStore::<TrustAnchorProxy>::create(
&config.storage_uri,
TA_PROXY_SERVER_NS,
config.use_history_cache,
)?;
// We need a pre-save listener so that we can schedule:
// - publication on updates
// - signing by the Trust Anchor Signer when there are requests [in testbed mode]
store.add_pre_save_listener(tasks.clone());
// We need a post-save listener so that we can schedule:
// - re-sync for local children when the proxy has new responses AND is saved
store.add_post_save_listener(tasks.clone());
Some(store)
} else {
None
};
let ta_signer_store = if config.ta_signer_enabled() {
Some(AggregateStore::create(
&config.storage_uri,
TA_SIGNER_SERVER_NS,
config.use_history_cache,
)?)
} else {
None
};
// Create the status store which will maintain the last known connection status between each CA
// and their parent(s) and repository.
let status_store = StatusStore::create(&config.storage_uri, STATUS_NS)?;
Ok(CaManager {
ca_store,
ca_objects_store,
status_store,
ta_proxy_store,
ta_signer_store,
tasks,
config,
signer,
system_actor,
})
}
pub fn testbed_enabled(&self) -> bool {
self.config.testbed().is_some()
}
/// Send a command to a CA
async fn send_ca_command(&self, cmd: CertAuthCommand) -> KrillResult<Arc<CertAuth>> {
self.ca_store.command(cmd)
}
/// Republish the embedded TA and CAs if needed, i.e. if they are close
/// to their next update time.
pub async fn republish_all(&self, force: bool) -> KrillResult<Vec<CaHandle>> {
let mut res = vec![];
for ca in self.ca_store.list()? {
match self.ca_objects_store.reissue_if_needed(force, &ca) {
Err(e) => {
error!("Could not reissue manifest and crl for {ca}. Error: {e}");
}
Ok(false) => {
trace!("No re-issuance of manifest and crl needed for {ca}");
}
Ok(true) => {
debug!("Re-issued manifest(s) and CRL(s) for {ca}");
res.push(ca.clone())
}
}
}
Ok(res)
}
}
/// # Trust Anchor Support
///
impl CaManager {
/// Send a command to the TA Proxy. Errors if ta support is not enabled
async fn send_ta_proxy_command(&self, cmd: TrustAnchorProxyCommand) -> KrillResult<Arc<TrustAnchorProxy>> {
self.ta_proxy_store
.as_ref()
.ok_or_else(|| Error::custom("ta_support_enabled is false"))?
.command(cmd)
}
/// Send a command to the TA Proxy. Errors if ta support is not enabled
async fn send_ta_signer_command(&self, cmd: TrustAnchorSignerCommand) -> KrillResult<Arc<TrustAnchorSigner>> {
self.ta_signer_store
.as_ref()
.ok_or_else(|| Error::custom("ta_signer_enabled is false"))?
.command(cmd)
}
/// Gets the Trust Anchor Proxy, if present. Returns an error if the TA is uninitialized.
pub async fn get_trust_anchor_proxy(&self) -> KrillResult<Arc<TrustAnchorProxy>> {
let ta_handle = ta::ta_handle();
self.ta_proxy_store
.as_ref()
.ok_or_else(|| Error::custom("TA proxy not enabled"))?
.get_latest(&ta_handle)
}
/// Gets the Trust Anchor Signer, if present. Returns an error if the TA is uninitialized.
pub async fn get_trust_anchor_signer(&self) -> KrillResult<Arc<TrustAnchorSigner>> {
let ta_handle = ta::ta_handle();
self.ta_signer_store
.as_ref()
.ok_or_else(|| Error::custom("TA signer not enabled"))?
.get_latest(&ta_handle)
}
/// Initialises the (one) Trust Anchor proxy.
///
/// Returns an error if:
/// - ta_support_enabled is false
/// - the proxy was already initialised
pub async fn ta_proxy_init(&self) -> KrillResult<()> {
let ta_handle = ta::ta_handle();
let ta_proxy_store = self
.ta_proxy_store
.as_ref()
.ok_or_else(|| Error::custom("ta_support_enabled must be true in config"))?;
if ta_proxy_store.has(&ta_handle)? {
Err(Error::TaAlreadyInitialized)
} else {
// Initialise proxy
let proxy_init = TrustAnchorProxyInitCommand::make(&ta_handle, self.signer.clone(), &self.system_actor);
ta_proxy_store.add(proxy_init)?;
Ok(())
}
}
/// Initialises the embedded Trust Anchor Signer (for testbed).
/// This assumes that the one and only local Trust Anchor Proxy exists and
/// is to be associated with this signer.
pub async fn ta_signer_init(
&self,
tal_https: Vec<uri::Https>,
tal_rsync: uri::Rsync,
private_key_pem: Option<String>,
) -> KrillResult<()> {
let ta_signer_store = self
.ta_signer_store
.as_ref()
.ok_or_else(|| Error::custom("ta_signer_enabled must be true in config"))?;
let handle = ta_handle();
if ta_signer_store.has(&handle)? {
Err(Error::TaAlreadyInitialized)
} else {
// Create Signer
let repo_contact = self.ta_proxy_repository_contact().await?;
let proxy_id = self.ta_proxy_id().await?;
let details = TrustAnchorSignerInitCommandDetails {
proxy_id,
repo_info: repo_contact.repo_info().clone(),
tal_https,
tal_rsync,
private_key_pem,
timing: self.config.ta_timing,
signer: self.signer.clone(),
};
let cmd = TrustAnchorSignerInitCommand::new(&handle, details, &self.system_actor);
ta_signer_store.add(cmd)?;
Ok(())
}
}
pub async fn ta_proxy_id(&self) -> KrillResult<IdCertInfo> {
self.get_trust_anchor_proxy().await.map(|proxy| proxy.id().clone())
}
/// Gets the publisher request for the Trust Anchor proxy.
/// Returns an error if the proxy is not initialised.
pub async fn ta_proxy_publisher_request(&self) -> KrillResult<idexchange::PublisherRequest> {
self.get_trust_anchor_proxy()
.await
.map(|proxy| proxy.publisher_request())
}
/// Add the repository to Trust Anchor proxy.
/// Returns an error if the proxy is not enabled or already has a repository.
pub async fn ta_proxy_repository_update(&self, contact: RepositoryContact, actor: &Actor) -> KrillResult<()> {
let add_repo_cmd = TrustAnchorProxyCommand::add_repo(&ta::ta_handle(), contact, actor);
self.send_ta_proxy_command(add_repo_cmd).await?;
Ok(())
}
/// Returns the repository contact for the proxy, or an error if there is
/// no proxy, or no repository configured for it.
pub async fn ta_proxy_repository_contact(&self) -> KrillResult<RepositoryContact> {
self.get_trust_anchor_proxy()
.await?
.repository()
.cloned()
.ok_or(Error::TaProxyHasNoRepository)
}
/// Adds the associated signer to the proxy.
///
/// Errors if:
/// - there is no proxy
/// - the proxy has a signer
pub async fn ta_proxy_signer_add(&self, info: TrustAnchorSignerInfo, actor: &Actor) -> KrillResult<()> {
let add_signer_cmd = TrustAnchorProxyCommand::add_signer(&ta_handle(), info, actor);
self.send_ta_proxy_command(add_signer_cmd).await?;
Ok(())
}
/// Create a new request for the signer.
///
/// Errors if:
/// - there is no proxy
/// - the proxy already has a request
pub async fn ta_proxy_signer_make_request(&self, actor: &Actor) -> KrillResult<TrustAnchorSignedRequest> {
let cmd = TrustAnchorProxyCommand::make_signer_request(&ta_handle(), actor);
let proxy = self.send_ta_proxy_command(cmd).await?;
proxy.get_signer_request(self.config.ta_timing, &self.signer)
}
/// Create a new request for the signer.
///
/// Errors if:
/// - there is no proxy
/// - the proxy already has a request
pub async fn ta_proxy_signer_get_request(&self) -> KrillResult<TrustAnchorSignedRequest> {
self.get_trust_anchor_proxy()
.await?
.get_signer_request(self.config.ta_timing, &self.signer)
}
/// Process a sign response from the signer.
///
/// Errors if:
/// - there is no proxy
/// - there is no matching request
pub async fn ta_proxy_signer_process_response(
&self,
response: TrustAnchorSignedResponse,
actor: &Actor,
) -> KrillResult<()> {
let cmd = TrustAnchorProxyCommand::process_signer_response(&ta_handle(), response, actor);
self.send_ta_proxy_command(cmd).await?;
Ok(())
}
/// Initializes an embedded trust anchor with all resources.
pub async fn ta_init_fully_embedded(
&self,
ta_aia: uri::Rsync,
ta_uris: Vec<uri::Https>,
ta_key_pem: Option<String>,
repo_manager: &Arc<RepositoryManager>,
actor: &Actor,
) -> KrillResult<()> {
let ta_handle = ta::ta_handle();
// Initialise proxy
self.ta_proxy_init().await?;
// Add repository
let pub_req = self.ta_proxy_publisher_request().await?;
// Create publisher
repo_manager.create_publisher(pub_req, actor)?;
let repository_response = repo_manager.repository_response(&ta_handle.convert())?;
// Add repository to proxy
let contact = RepositoryContact::for_response(repository_response).map_err(Error::rfc8183)?;
self.ta_proxy_repository_update(contact, &self.system_actor).await?;
// Initialise signer
self.ta_signer_init(ta_uris, ta_aia, ta_key_pem).await?;
// Add signer to proxy
let signer_info = self.get_trust_anchor_signer().await?.get_signer_info();
self.ta_proxy_signer_add(signer_info, &self.system_actor).await?;
self.sync_ta_proxy_signer_if_possible().await?;
self.cas_repo_sync_single(repo_manager, &ta_handle, 0).await?;
Ok(())
}
/// Renew the embedded testbed TA;
pub async fn ta_renew_testbed_ta(&self) -> KrillResult<()> {
if self.testbed_enabled() {
let proxy = self.get_trust_anchor_proxy().await?;
if !proxy.has_open_request() {
info!("Renew the testbed TA");
self.sync_ta_proxy_signer_if_possible().await?;
}
}
Ok(())
}
}
/// # CA instances and identity
///
impl CaManager {
/// Initializes a CA without a repo, no parents, no children, no nothing
pub fn init_ca(&self, handle: &CaHandle) -> KrillResult<()> {
if handle == &ta_handle() || handle.as_str() == "version" {
Err(Error::TaNameReserved)
} else if self.ca_store.has(handle)? {
Err(Error::CaDuplicate(handle.clone()))
} else {
// Initialize the CA in self.ca_store, but note that there is no need to create
// a new CA entry in self.ca_objects_store or self.status_store, because they will
// generate empty default entries if needed.
let cmd = CertAuthInitCommand::new(
handle,
CertAuthInitCommandDetails::new(self.signer.clone()),
&self.system_actor,
);
self.ca_store.add(cmd)?;
Ok(())
}
}
/// Updates the self-signed ID certificate for a CA. Use this with care as
/// RFC 8183 only talks about initial ID exchanges in the form of XML files.
/// It does not talk about updating identity certificates and keys. Krill supports
/// that a new ID key pair and certificate is generated, and has functions to update
/// this for a parent, a child, a repo and a publisher, but other implementations may
/// not support that identities are updated after initialization.
pub async fn ca_update_id(&self, handle: CaHandle, actor: &Actor) -> KrillResult<()> {
let cmd = CertAuthCommandDetails::update_id(&handle, self.signer.clone(), actor);
self.send_ca_command(cmd).await?;
Ok(())
}
/// Get the CAs that the given actor is permitted to see.
pub fn ca_list(&self, actor: &Actor) -> KrillResult<CertAuthList> {
Ok(CertAuthList::new(
self.ca_store
.list()?
.into_iter()
.filter(|handle| matches!(actor.is_allowed(Permission::CA_READ, Handle::from(handle)), Ok(true)))
.map(CertAuthSummary::new)
.collect(),
))
}
/// Gets a CA by the given handle, returns an `Err(ServerError::UnknownCA)` if it
/// does not exist.
pub async fn get_ca(&self, handle: &CaHandle) -> KrillResult<Arc<CertAuth>> {
self.ca_store
.get_latest(handle)
.map_err(|_| Error::CaUnknown(handle.clone()))
}
/// Checks whether a CA by the given handle exists.
pub fn has_ca(&self, handle: &CaHandle) -> KrillResult<bool> {
self.ca_store.has(handle).map_err(Error::AggregateStoreError)
}
/// Gets current CA status
pub async fn get_ca_status(&self, ca: &CaHandle) -> KrillResult<CaStatus> {
if self.has_ca(ca)? {
Ok(self.status_store.get_ca_status(ca))
} else {
Err(Error::CaUnknown(ca.clone()))
}
}
/// Delete a CA. Let it do best effort revocation requests and withdraw
/// all its objects first. Note that any children of this CA will be left
/// orphaned, and they will only learn of this sad fact when they choose
/// to call home.
pub async fn delete_ca(
&self,
repo_manager: &RepositoryManager,
ca_handle: &CaHandle,
actor: &Actor,
) -> KrillResult<()> {
warn!("Deleting CA '{}' as requested by: {}", ca_handle, actor);
let ca = self.get_ca(ca_handle).await?;
// Request revocations from all parents - best effort
info!(
"Will try to request revocations from all parents CA '{}' before removing it.",
ca_handle
);
for parent in ca.parents() {
if let Err(e) = self.ca_parent_revoke(ca_handle, parent).await {
warn!(
"Removing CA '{}', but could not send revoke requests to parent '{}': {}",
ca_handle, parent, e
);
}
}
// Clean all repos - again best effort
info!(
"Will try to clean up all repositories for CA '{}' before removing it.",
ca_handle
);
let mut repos: Vec<RepositoryContact> = self.ca_repo_elements(ca_handle).await?.into_keys().collect();
for deprecated in self.ca_deprecated_repos(ca_handle)? {
repos.push(deprecated.into());
}
for repo_contact in repos {
if self
.ca_repo_sync(repo_manager, ca_handle, ca.id_cert(), &repo_contact, vec![])
.await
.is_err()
{
info!(
"Could not clean up deprecated repository. This is fine - objects there are no longer referenced."
);
}
}
self.ca_store.drop_aggregate(ca_handle)?;
self.ca_objects_store.remove_ca(ca_handle)?;
self.status_store.remove_ca(ca_handle)?;
Ok(())
}
}
/// # CA History
///
impl CaManager {
/// Gets the history for a CA.
pub async fn ca_history(&self, handle: &CaHandle, crit: CommandHistoryCriteria) -> KrillResult<CommandHistory> {
Ok(self.ca_store.command_history(handle, crit)?)
}
/// Shows the details for a CA command.
pub fn ca_command_details(&self, handle: &CaHandle, version: u64) -> KrillResult<CaCommandDetails> {
self.ca_store
.get_command(handle, version)
.map_err(Error::AggregateStoreError)
}
}
/// # CAs as parents
///
impl CaManager {
/// Adds a child under a CA. If the `AddChildRequest` contains resources not held
/// by this CA, then an `Error::CaChildExtraResources` is returned.
pub async fn ca_add_child(
&self,
ca: &CaHandle,
req: AddChildRequest,
service_uri: &uri::Https,
actor: &Actor,
) -> KrillResult<idexchange::ParentResponse> {
info!("CA '{}' process add child request: {}", &ca, &req);
if ca.as_str() != TA_NAME {
let (child_handle, child_res, id_cert) = req.unpack();
let add_child =
CertAuthCommandDetails::child_add(ca, child_handle.clone(), id_cert.into(), child_res, actor);
self.send_ca_command(add_child).await?;
self.ca_parent_response(ca, child_handle, service_uri).await
} else {
let child_handle = req.handle().clone();
let add_child_cmd = TrustAnchorProxyCommand::add_child(ca, req, actor);
self.send_ta_proxy_command(add_child_cmd).await?;
self.ca_parent_response(ca, child_handle, service_uri).await
}
}
/// Show details for a child under the CA.
pub async fn ca_show_child(&self, ca: &CaHandle, child: &ChildHandle) -> KrillResult<ChildCaInfo> {
trace!("Finding details for CA: {} under parent: {}", child, ca);
let ca = self.get_ca(ca).await?;
ca.get_child(child).map(|details| details.clone().into())
}
/// Export a child. Fails if:
/// - the child does not exist
/// - the child has no received certificate
/// - the child has more than one received certificate or resource class
///
/// Primarily meant for testing that the child import function works.
pub async fn ca_child_export(&self, ca: &CaHandle, child_handle: &ChildHandle) -> KrillResult<ExportChild> {
trace!("Exporting CA: {} under parent: {}", child_handle, ca);
self.get_ca(ca).await?.child_export(child_handle)
}
/// Import a child under the given CA. Will fail if:
/// - the ca does not exist
/// - the ca has less than, or more than one resource class
/// - the ca does not hold the resources for the child
/// - the child already exists
pub async fn ca_child_import(&self, ca: &CaHandle, import_child: ImportChild, actor: &Actor) -> KrillResult<()> {
trace!("Importing CA: {} under parent: {}", import_child.name, ca);
self.send_ca_command(CertAuthCommandDetails::child_import(
ca,
import_child,
self.config.clone(),
self.signer.clone(),
actor,
))
.await?;
Ok(())
}
/// Show a contact for a child.
pub async fn ca_parent_contact(
&self,
ca_handle: &CaHandle,
child_handle: ChildHandle,
service_uri: &uri::Https,
) -> KrillResult<ParentCaContact> {
let service_uri = Self::service_uri_for_ca(service_uri, ca_handle);
let ca = self.get_ca(ca_handle).await?;
let server_info = ParentServerInfo::new(service_uri, ca_handle.convert(), child_handle, ca.id_cert().clone());
Ok(ParentCaContact::for_parent_server_info(server_info))
}
/// Gets an RFC8183 Parent Response for the child.
pub async fn ca_parent_response(
&self,
ca_handle: &CaHandle,
child_handle: ChildHandle,
service_uri: &uri::Https,
) -> KrillResult<idexchange::ParentResponse> {
let service_uri = Self::service_uri_for_ca(service_uri, ca_handle);
let id_cert: publication::Base64 = if ca_handle.as_str() != TA_NAME {
let ca = self.get_ca(ca_handle).await?;
ca.get_child(&child_handle)?; // ensure the child is known
ca.id_cert().base64().clone()
} else {
let proxy = self.get_trust_anchor_proxy().await?;
proxy.get_child(&child_handle)?;
proxy.id().base64().clone()
};
Ok(idexchange::ParentResponse::new(
id_cert,
ca_handle.convert(),
child_handle,
service_uri,
None,
))
}
fn service_uri_for_ca(base_uri: &uri::Https, ca_handle: &CaHandle) -> ServiceUri {
let service_uri = format!("{}rfc6492/{}", base_uri, ca_handle);
let service_uri = uri::Https::from_string(service_uri).unwrap();
ServiceUri::Https(service_uri)
}
/// Update a child under this CA. The submitted `UpdateChildRequest` can contain a
/// new `IdCert`, or `ResourceSet`, or both. When resources are updated, the existing
/// resource entitlements are replaced by the new value - i.e. this is not a delta
/// and it affects all Internet Number Resource (INR) types (IPv4, IPV6, ASN). Setting
/// resource entitlements beyond the resources held by the parent CA will return
/// an `Error::CaChildExtraResources`.
pub async fn ca_child_update(
&self,
ca: &CaHandle,
child: ChildHandle,
req: UpdateChildRequest,
actor: &Actor,
) -> KrillResult<()> {
let (id_opt, resources_opt, suspend_opt, resource_class_name_mapping_opt) = req.unpack();
if let Some(id) = id_opt {
self.send_ca_command(CertAuthCommandDetails::child_update_id(
ca,
child.clone(),
id.into(),
actor,
))
.await?;
}
if let Some(resources) = resources_opt {
self.send_ca_command(CertAuthCommandDetails::child_update_resources(
ca,
child.clone(),
resources,
actor,
))
.await?;
}
if let Some(suspend) = suspend_opt {
if suspend {
self.send_ca_command(CertAuthCommandDetails::child_suspend_inactive(ca, child.clone(), actor))
.await?;
} else {
self.send_ca_command(CertAuthCommandDetails::child_unsuspend(ca, child.clone(), actor))
.await?;
}
}
if let Some(mapping) = resource_class_name_mapping_opt {
self.send_ca_command(CertAuthCommandDetails::child_update_resource_class_name_mapping(
ca, child, mapping, actor,
))
.await?;
}
Ok(())
}
/// Removes a child from this CA. This will also ensure that certificates issued to the child
/// are revoked and withdrawn.
pub async fn ca_child_remove(&self, ca: &CaHandle, child: ChildHandle, actor: &Actor) -> KrillResult<()> {
self.status_store.remove_child(ca, &child)?;
self.send_ca_command(CertAuthCommandDetails::child_remove(ca, child, actor))
.await?;
Ok(())
}
/// Processes an RFC 6492 request sent to this CA:
/// - parses the message bytes
/// - validates the request
/// - processes the child request
/// - signs a response and returns the bytes
pub async fn rfc6492(
&self,
ca_handle: &CaHandle,
msg_bytes: Bytes,
user_agent: Option<String>,
actor: &Actor,
) -> KrillResult<Bytes> {
if ca_handle.as_str() == TA_NAME {
return Err(Error::custom("Remote RFC 6492 to TA is not supported"));
}
let ca = self.get_ca(ca_handle).await?;
let req_msg = self.rfc6492_unwrap_request(&ca, &msg_bytes)?;
// Create a logger for CMS (avoid cloning recipient)
let cms_logger = CmsLogger::for_rfc6492_rcvd(
self.config.rfc6492_log_dir.as_ref(),
req_msg.recipient(),
req_msg.sender(),
);
let res_msg = self
.rfc6492_process_request(ca_handle, req_msg, user_agent, actor)
.await;
match res_msg {
Ok(msg) => {
let should_log_cms = !msg.is_list_response();
let reply_bytes = ca.sign_rfc6492_response(msg, self.signer.deref())?;
if should_log_cms {
cms_logger.received(&msg_bytes)?;
cms_logger.reply(&reply_bytes)?;
}
Ok(reply_bytes)
}
Err(e) => {
cms_logger.received(&msg_bytes)?;
cms_logger.err(&e)?;
Err(e)
}
}
}
/// Process an rfc6492 message and create an unsigned response
pub async fn rfc6492_process_request(
&self,
ca_handle: &CaHandle,
req_msg: provisioning::Message,
user_agent: Option<String>,
actor: &Actor,
) -> KrillResult<provisioning::Message> {
let (sender, _recipient, payload) = req_msg.unpack();
let child_handle = sender.convert();
// If the child was suspended, because it was inactive, then we can now conclude
// that it's become active again. So unsuspend it first, before processing the request
// further.
//
// The TA will never suspend children, and does not support it.
if ca_handle.as_str() != TA_NAME {
let ca = self.get_ca(ca_handle).await?;
let child_ca = ca.get_child(&child_handle)?;
if child_ca.is_suspended() {
info!(
"Child '{}' under CA '{}' became active again, will unsuspend it.",
child_handle,
ca.handle()
);
let req = UpdateChildRequest::unsuspend();
self.ca_child_update(ca.handle(), child_handle.clone(), req, actor)
.await?;
}
}
let res_msg = match payload {
provisioning::Payload::Revoke(req) => self.revoke(ca_handle, child_handle.clone(), req, actor).await,
provisioning::Payload::List => self.list(ca_handle, &child_handle).await,
provisioning::Payload::Issue(req) => self.issue(ca_handle, child_handle.clone(), req, actor).await,
_ => Err(Error::custom("Unsupported RFC6492 message")),
};
// Set child status
match &res_msg {
Ok(_) => {
self.status_store
.set_child_success(ca_handle, &child_handle, user_agent)?;
}
Err(e) => {
self.status_store
.set_child_failure(ca_handle, &child_handle, user_agent, e)?;
}
}
res_msg
}
/// Unpack and validate a request message
fn rfc6492_unwrap_request(&self, ca: &CertAuth, msg_bytes: &Bytes) -> KrillResult<provisioning::Message> {
match ProvisioningCms::decode(msg_bytes.as_ref()) {
Ok(msg) => ca.verify_rfc6492(msg),
Err(e) => Err(Error::custom(format!(
"Could not decode RFC6492 message for: {}, err: {}",
ca.handle(),
e
))),
}
}
/// List the entitlements for a child: 3.3.2 of RFC 6492.
async fn list(&self, ca_handle: &CaHandle, child: &ChildHandle) -> KrillResult<provisioning::Message> {
let list_response = if ca_handle.as_str() != TA_NAME {
self.get_ca(ca_handle).await?.list(child, &self.config.issuance_timing)
} else {
self.get_trust_anchor_proxy()
.await?
.entitlements(child, &self.config.ta_timing)
.map(|entitlements| ResourceClassListResponse::new(vec![entitlements]))
}?;
Ok(provisioning::Message::list_response(
ca_handle.convert(),
child.convert(),
list_response,
))
}
/// Issue a Certificate in response to an RFC 6492 Certificate Issuance request sent by a child.
///
/// See: https://tools.ietf.org/html/rfc6492#section3.4.1-2
async fn issue(
&self,
ca_handle: &CaHandle,
child_handle: ChildHandle,
issue_req: IssuanceRequest,
actor: &Actor,
) -> KrillResult<provisioning::Message> {
if ca_handle.as_str() == TA_NAME {
let request = ta::ProvisioningRequest::Issuance(issue_req);
self.ta_slow_rfc6492_request(ca_handle, child_handle, request, actor)
.await
} else {
let child_rcn = issue_req.class_name();
let pub_key = issue_req.csr().public_key();
let cmd = CertAuthCommandDetails::child_certify(
ca_handle,
child_handle.clone(),
issue_req.clone(),
self.config.clone(),
self.signer.clone(),
actor,
);
let ca = self.send_ca_command(cmd).await?;
// The updated CA will now include the newly issued certificate.
let child = ca.get_child(&child_handle)?;
let my_rcn = child.parent_name_for_rcn(child_rcn);
let response = ca.issuance_response(&child_handle, &my_rcn, pub_key, &self.config.issuance_timing)?;
Ok(provisioning::Message::issue_response(
ca_handle.convert(),
child_handle.into_converted(),
response,
))
}
}
/// Process an RFC 6492 revocation request sent by a child.
/// See: https://tools.ietf.org/html/rfc6492#section3.5.1-2
async fn revoke(
&self,
ca_handle: &CaHandle,
child: ChildHandle,
revoke_request: RevocationRequest,
actor: &Actor,
) -> KrillResult<provisioning::Message> {
if ca_handle.as_str() == TA_NAME {
let request = ta::ProvisioningRequest::Revocation(revoke_request);
self.ta_slow_rfc6492_request(ca_handle, child, request, actor).await
} else {
let res = RevocationResponse::from(&revoke_request); // response provided that no errors are returned
let msg = provisioning::Message::revoke_response(ca_handle.convert(), child.convert(), res);
let cmd = CertAuthCommandDetails::child_revoke_key(ca_handle, child, revoke_request, actor);
self.send_ca_command(cmd).await?;
Ok(msg)
}
}
/// Processes a 'slow' RFC 6492 request to the TA: an issue or revoke request
/// which will require the Trust Anchor Signer to use the TA key.
async fn ta_slow_rfc6492_request(
&self,
ta_handle: &CaHandle,
child: ChildHandle,