-
-
Notifications
You must be signed in to change notification settings - Fork 35
/
manager.rs
1988 lines (1767 loc) · 78.8 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, ops::Deref, sync::Arc};
use api::{Publish, Update, Withdraw};
use futures::future::join_all;
use tokio::sync::Mutex;
use bytes::Bytes;
use chrono::Duration;
use rpki::{repository::crypto::KeyIdentifier, uri};
use crate::{
commons::{
actor::Actor,
api::{
self, AddChildRequest, AspaCustomer, AspaDefinitionList, AspaDefinitionUpdates, AspaProvidersUpdate,
Base64, CaCommandDetails, CaCommandResult, CertAuthList, CertAuthSummary, ChildCaInfo, ChildHandle,
CommandHistory, CommandHistoryCriteria, Entitlements, Handle, IssuanceRequest, IssuanceResponse, ListReply,
ParentCaContact, ParentCaReq, ParentHandle, PublishDelta, RcvdCert, RepositoryContact, ResourceClassName,
ResourceSet, RevocationRequest, RevocationResponse, RtaName, StoredEffect, UpdateChildRequest,
},
api::{rrdp::PublishElement, Timestamp},
crypto::{IdCert, KrillSigner, ProtocolCms, ProtocolCmsBuilder},
error::Error,
eventsourcing::{Aggregate, AggregateStore, Command, CommandKey},
remote::cmslogger::CmsLogger,
remote::{rfc6492, rfc8181, rfc8183},
util::httpclient,
KrillResult,
},
constants::{CASERVER_DIR, REQUEUE_DELAY_SECONDS, STATUS_DIR},
daemon::{
auth::common::permissions::Permission,
ca::{
self, ta_handle, CaObjectsStore, CaStatus, CertAuth, Cmd, CmdDet, DeprecatedRepository, IniDet,
ResourceTaggedAttestation, RouteAuthorizationUpdates, RtaContentRequest, RtaPrepareRequest, StatusStore,
},
config::Config,
mq::MessageQueue,
},
pubd::RepositoryManager,
};
//------------ CaLocks ------------------------------------------------------
pub struct CaLockMap(HashMap<Handle, tokio::sync::RwLock<()>>);
impl CaLockMap {
fn create_ca_lock(&mut self, ca: &Handle) {
self.0.insert(ca.clone(), tokio::sync::RwLock::new(()));
}
fn has_ca(&self, ca: &Handle) -> bool {
self.0.contains_key(ca)
}
fn drop_ca_lock(&mut self, ca: &Handle) {
self.0.remove(ca);
}
}
impl Default for CaLockMap {
fn default() -> Self {
CaLockMap(HashMap::new())
}
}
pub struct CaLock<'a> {
map: tokio::sync::RwLockReadGuard<'a, CaLockMap>,
ca: Handle,
}
impl CaLock<'_> {
async fn read(&self) -> tokio::sync::RwLockReadGuard<'_, ()> {
self.map.0.get(&self.ca).unwrap().read().await
}
async fn write(&self) -> tokio::sync::RwLockWriteGuard<'_, ()> {
self.map.0.get(&self.ca).unwrap().write().await
}
}
pub struct CaLocks {
locks: tokio::sync::RwLock<CaLockMap>,
}
impl Default for CaLocks {
fn default() -> Self {
CaLocks {
locks: tokio::sync::RwLock::new(CaLockMap::default()),
}
}
}
impl CaLocks {
async fn ca(&self, ca: &Handle) -> CaLock<'_> {
// self.create_lock_if_needed(ca).await;
{
let map = self.locks.read().await;
if map.has_ca(ca) {
return CaLock { map, ca: ca.clone() };
}
}
{
let mut lock = self.locks.write().await;
lock.create_ca_lock(ca);
}
let map = self.locks.read().await;
CaLock { map, ca: ca.clone() }
}
async fn drop_ca(&self, ca: &Handle) {
let mut map = self.locks.write().await;
map.drop_ca_lock(ca);
}
}
//------------ CaManager -----------------------------------------------------
#[derive(Clone)]
pub struct CaManager {
ca_store: Arc<AggregateStore<CertAuth>>,
ca_objects_store: Arc<CaObjectsStore>,
status_store: Arc<Mutex<StatusStore>>,
locks: Arc<CaLocks>,
config: Arc<Config>,
signer: Arc<KrillSigner>,
}
impl CaManager {
/// Builds a new CaServer. Will return an error if the CA store cannot be initialized.
pub async fn build(config: Arc<Config>, mq: Arc<MessageQueue>, signer: Arc<KrillSigner>) -> KrillResult<Self> {
// Create the AggregateStore for the event-sourced `CertAuth` structures that handle
// most CA functions.
let mut ca_store = AggregateStore::<CertAuth>::disk(&config.data_dir, CASERVER_DIR)?;
if config.always_recover_data {
// If the user chose to 'always recover data' then do so.
// This is slow, but it will ensure that all commands and events are accounted for,
// and there are no incomplete changes where some but not all files for a change were
// written to disk.
ca_store.recover()?;
} else if let Err(e) = ca_store.warm() {
// Otherwise we just tried 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 complain and try to recover.
error!(
"Could not warm up cache, data seems corrupt. Will try to recover!! Error was: {}",
e
);
ca_store.recover()?;
}
// Create the `CaObjectStore` that is responsible for maintaining CA objects: the `CaObjects`
// for a CA gets copies of all ROAs and delegated certificates from the `CertAuth` and is responsible
// for manifests and CRL generation.
let ca_objects_store = Arc::new(CaObjectsStore::disk(config.clone(), signer.clone())?);
// Register the `CaObjectsStore` as a pre-save listener to the 'ca_store' so that it can update
// its ROAs and delegated 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 post-save listener to 'ca_store' so that relevant changes in
// a `CertAuth` can trigger follow up actions. Most importantly: synchronize with a parent CA or
// the RPKI repository.
ca_store.add_post_save_listener(mq);
// 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::new(&config.data_dir, STATUS_DIR)?;
// Create the per-CA lock structure so that we can guarantee safe access to each CA, while allowing
// multiple CAs in a single Krill instance to interact: e.g. a child can talk to its parent and they
// are locked individually.
let locks = Arc::new(CaLocks::default());
Ok(CaManager {
ca_store: Arc::new(ca_store),
ca_objects_store,
status_store: Arc::new(Mutex::new(status_store)),
locks,
config,
signer,
})
}
pub fn testbed_enabled(&self) -> bool {
self.config.testbed().is_some()
}
/// Gets the TrustAnchor, if present. Returns an error if the TA is uninitialized.
pub async fn get_trust_anchor(&self) -> KrillResult<Arc<CertAuth>> {
let ta_handle = ca::ta_handle();
let lock = self.locks.ca(&ta_handle).await;
let _ = lock.read().await;
self.ca_store.get_latest(&ta_handle).map_err(Error::AggregateStoreError)
}
/// Initializes an embedded trust anchor with all resources.
pub async fn init_ta(
&self,
ta_aia: uri::Rsync,
ta_uris: Vec<uri::Https>,
repo_manager: &Arc<RepositoryManager>,
actor: &Actor,
) -> KrillResult<()> {
let ta_handle = ca::ta_handle();
let lock = self.locks.ca(&ta_handle).await;
let _ = lock.write().await;
if self.ca_store.has(&ta_handle)? {
Err(Error::TaAlreadyInitialized)
} else {
// init normal CA
let init = IniDet::init(&ta_handle, self.signer.deref())?;
self.ca_store.add(init)?;
// add to repo
let ta = self.get_trust_anchor().await?;
let pub_req = ta.publisher_request();
repo_manager.create_publisher(pub_req, actor)?;
let repository_response = repo_manager.repository_response(&ta_handle)?;
let contact = RepositoryContact::new(repository_response);
let upd_repo_cmd = CmdDet::update_repo(&ta_handle, contact, self.signer.clone(), actor);
self.ca_store.command(upd_repo_cmd)?;
// make trust anchor
let make_ta_cmd =
CmdDet::make_trust_anchor(&ta_handle, ta_uris, Some(ta_aia.clone()), self.signer.clone(), actor);
let ta = self.ca_store.command(make_ta_cmd)?;
// receive the self signed cert (now as child of self)
let ta_cert = ta.parent(&ta_handle).unwrap().to_ta_cert();
let rcvd_cert = RcvdCert::new(ta_cert.clone(), ta_aia, ResourceSet::all_resources());
let rcv_cert = CmdDet::upd_received_cert(
&ta_handle,
ResourceClassName::default(),
rcvd_cert,
self.config.clone(),
self.signer.clone(),
actor,
);
self.ca_store.command(rcv_cert)?;
Ok(())
}
}
/// Send a command to a CA
async fn send_command(&self, cmd: Cmd) -> KrillResult<Arc<CertAuth>> {
let lock = self.locks.ca(cmd.handle()).await;
let _ = lock.write().await;
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) -> KrillResult<Vec<Handle>> {
self.ca_objects_store.reissue_all()
}
}
/// # CA instances and identity
///
impl CaManager {
/// Initializes a CA without a repo, no parents, no children, no nothing
pub fn init_ca(&self, handle: &Handle) -> 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 init = IniDet::init(handle, self.signer.deref())?;
self.ca_store.add(init)?;
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: Handle, actor: &Actor) -> KrillResult<()> {
let cmd = CmdDet::update_id(&handle, self.signer.clone(), actor);
self.send_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.clone()), 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: &Handle) -> KrillResult<Arc<CertAuth>> {
let lock = self.locks.ca(handle).await;
let _ = lock.read().await;
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: &Handle) -> KrillResult<bool> {
self.ca_store.has(handle).map_err(Error::AggregateStoreError)
}
/// Gets current CA status
pub async fn get_ca_status(&self, ca: &Handle) -> KrillResult<Arc<CaStatus>> {
if self.has_ca(ca)? {
self.status_store.lock().await.get_ca_status(ca).await
} 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, ca_handle: &Handle, 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_iter()
.map(|(contact, _)| contact)
.collect();
for deprecated in self.ca_deprecated_repos(ca_handle)? {
repos.push(deprecated.into());
}
for repo_contact in repos {
if self.ca_repo_sync(ca_handle, &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.status_store.lock().await.remove_ca(ca_handle).await?;
self.locks.drop_ca(ca_handle).await;
Ok(())
}
/// Re-synchronize the CAs and CaStatus
///
/// - remove any surplus CA status entries
/// - create missing CA status entries
/// - check children for existing CAs:
/// - remove surplus from status
/// - add missing
pub async fn resync_ca_statuses(&self) -> KrillResult<()> {
let cas = self.ca_store.list()?;
let mut ca_statuses = self.status_store.lock().await.cas().await?;
// loop over existing CAs and get their status
for ca_handle in cas {
let ca = self.get_ca(&ca_handle).await?;
let status = match ca_statuses.remove(&ca_handle) {
Some(status) => status,
None => {
// Getting a missing status will ensure that a new empty status is generated.
self.status_store.lock().await.get_ca_status(&ca_handle).await?
}
};
let mut status_children = status.children().clone();
// add default status for missing children
for child in ca.children() {
if status_children.remove(child).is_none() {
self.status_store
.lock()
.await
.set_child_default_if_missing(&ca_handle, child)
.await?;
}
}
// remove surplus children status
for surplus_child in status_children.keys() {
self.status_store
.lock()
.await
.remove_child(&ca_handle, surplus_child)
.await?;
}
}
// remove the status for any left-over CAs with status
for surplus_ca in ca_statuses.keys() {
info!("Removing the cached status for a removed CA: {}", surplus_ca);
self.status_store.lock().await.remove_ca(surplus_ca).await?;
}
Ok(())
}
}
/// # CA History
///
impl CaManager {
/// Gets the history for a CA.
pub async fn ca_history(&self, handle: &Handle, crit: CommandHistoryCriteria) -> KrillResult<CommandHistory> {
let ca_lock = self.locks.ca(handle).await;
let _lock = ca_lock.read().await;
Ok(self.ca_store.command_history(handle, crit)?)
}
/// Shows the details for a CA command.
pub fn ca_command_details(&self, handle: &Handle, command: CommandKey) -> KrillResult<CaCommandDetails> {
let command = self.ca_store.get_command(handle, &command)?;
let effect = command.effect().clone();
match effect {
StoredEffect::Error { msg } => Ok(CaCommandDetails::new(command, CaCommandResult::error(msg))),
StoredEffect::Success { events } => {
let mut stored_events = vec![];
for version in events {
let evt = self.ca_store.get_event(handle, version)?.ok_or_else(|| {
Error::Custom(format!("Cannot find evt: {} in history for CA: {}", version, handle))
})?;
stored_events.push(evt);
}
Ok(CaCommandDetails::new(command, CaCommandResult::events(stored_events)))
}
}
}
}
/// # CAs as parents
///
impl CaManager {
/// Adds a child under a CA. The 'service_uri' is used here so that
/// the appropriate `ParentCaContact` can be returned. If the `AddChildRequest`
/// contains resources not held by this CA, then an `Error::CaChildExtraResources`
/// is returned.
pub async fn ca_add_child(
&self,
ca: &Handle,
req: AddChildRequest,
service_uri: &uri::Https,
actor: &Actor,
) -> KrillResult<ParentCaContact> {
info!("CA '{}' process add child request: {}", &ca, &req);
let (child_handle, child_res, id_cert) = req.unpack();
let add_child = CmdDet::child_add(ca, child_handle.clone(), id_cert, child_res, actor);
self.send_command(add_child).await?;
self.ca_parent_contact(ca, child_handle, service_uri).await
}
/// Show details for a child under the CA.
pub async fn ca_show_child(&self, ca: &Handle, 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())
}
/// Show a contact for a child.
pub async fn ca_parent_contact(
&self,
ca_handle: &Handle,
child_handle: ChildHandle,
service_uri: &uri::Https,
) -> KrillResult<ParentCaContact> {
let response = self.ca_parent_response(ca_handle, child_handle, service_uri).await?;
Ok(ParentCaContact::for_rfc6492(response))
}
/// Gets an RFC8183 Parent Response for the child.
pub async fn ca_parent_response(
&self,
ca: &Handle,
child_handle: ChildHandle,
service_uri: &uri::Https,
) -> KrillResult<rfc8183::ParentResponse> {
let ca = self.get_ca(ca).await?;
let service_uri = format!("{}rfc6492/{}", service_uri.to_string(), ca.handle());
let service_uri = uri::Https::from_string(service_uri).unwrap();
let service_uri = rfc8183::ServiceUri::Https(service_uri);
Ok(rfc8183::ParentResponse::new(
None,
ca.id_cert().clone(),
ca.handle().clone(),
child_handle,
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: &Handle,
child: ChildHandle,
req: UpdateChildRequest,
actor: &Actor,
) -> KrillResult<()> {
let (id_opt, resources_opt, suspend_opt) = req.unpack();
if let Some(id) = id_opt {
self.send_command(CmdDet::child_update_id(ca, child.clone(), id, actor))
.await?;
}
if let Some(resources) = resources_opt {
self.send_command(CmdDet::child_update_resources(ca, child.clone(), resources, actor))
.await?;
}
if let Some(suspend) = suspend_opt {
if suspend {
self.send_command(CmdDet::child_suspend_inactive(ca, child, actor))
.await?;
} else {
self.send_command(CmdDet::child_unsuspend(ca, child, 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: &Handle, child: ChildHandle, actor: &Actor) -> KrillResult<()> {
self.status_store.lock().await.remove_child(ca, &child).await?;
self.send_command(CmdDet::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: &Handle,
msg_bytes: Bytes,
user_agent: Option<String>,
actor: &Actor,
) -> KrillResult<Bytes> {
let ca = self.get_ca(ca_handle).await?;
let msg = match ProtocolCms::decode(msg_bytes.as_ref(), false) {
Ok(msg) => msg,
Err(e) => {
let msg = format!(
"Could not decode RFC6492 message for: {}, msg: {}, err: {}",
ca_handle,
Base64::from_content(msg_bytes.as_ref()),
e
);
return Err(Error::custom(msg));
}
};
let content = ca.verify_rfc6492(msg)?;
let (child_handle, recipient, content) = content.unpack();
// 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.
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 cms_logger = CmsLogger::for_rfc6492_rcvd(self.config.rfc6492_log_dir.as_ref(), &recipient, &child_handle);
let (res, should_log_cms) = match content {
rfc6492::Content::Qry(rfc6492::Qry::Revoke(req)) => {
let res = self.revoke(ca_handle, child_handle.clone(), req, actor).await?;
let msg = rfc6492::Message::revoke_response(child_handle.clone(), recipient, res);
(self.wrap_rfc6492_response(ca_handle, msg).await, true)
}
rfc6492::Content::Qry(rfc6492::Qry::List) => {
let entitlements = self.list(ca_handle, &child_handle).await?;
let msg = rfc6492::Message::list_response(child_handle.clone(), recipient, entitlements);
(self.wrap_rfc6492_response(ca_handle, msg).await, false)
}
rfc6492::Content::Qry(rfc6492::Qry::Issue(req)) => {
let res = self.issue(ca_handle, &child_handle, req, actor).await?;
let msg = rfc6492::Message::issue_response(child_handle.clone(), recipient, res);
(self.wrap_rfc6492_response(ca_handle, msg).await, true)
}
_ => (Err(Error::custom("Unsupported RFC6492 message")), true),
};
// Log CMS messages if needed, and if enabled by config (this is a no-op if it isn't)
match &res {
Ok(reply_bytes) => {
if should_log_cms {
cms_logger.received(&msg_bytes)?;
cms_logger.reply(reply_bytes)?;
}
}
Err(e) => {
cms_logger.received(&msg_bytes)?;
cms_logger.err(e)?;
}
}
// Set child status
match &res {
Ok(_) => {
self.status_store
.lock()
.await
.set_child_success(ca.handle(), &child_handle, user_agent)
.await?;
}
Err(e) => {
self.status_store
.lock()
.await
.set_child_failure(ca.handle(), &child_handle, user_agent, e)
.await?;
}
}
res
}
async fn wrap_rfc6492_response(&self, handle: &Handle, msg: rfc6492::Message) -> KrillResult<Bytes> {
trace!("RFC6492 Response wrapping for {}", handle);
self.get_ca(handle)
.await?
.sign_rfc6492_response(msg, self.signer.deref())
}
/// List the entitlements for a child: 3.3.2 of RFC 6492.
async fn list(&self, ca: &Handle, child: &Handle) -> KrillResult<Entitlements> {
let ca = self.get_ca(ca).await?;
Ok(ca.list(child, &self.config.issuance_timing)?)
}
/// 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,
child: &ChildHandle,
issue_req: IssuanceRequest,
actor: &Actor,
) -> KrillResult<IssuanceResponse> {
let class_name = issue_req.class_name();
let pub_key = issue_req.csr().public_key();
let cmd = CmdDet::child_certify(
ca,
child.clone(),
issue_req.clone(),
self.config.clone(),
self.signer.clone(),
actor,
);
let ca = self.send_command(cmd).await?;
// The updated CA will now include the newly issued certificate.
let response = ca.issuance_response(child, class_name, pub_key, &self.config.issuance_timing)?;
Ok(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: &Handle,
child: ChildHandle,
revoke_request: RevocationRequest,
actor: &Actor,
) -> KrillResult<RevocationResponse> {
let res = (&revoke_request).into(); // response provided that no errors are returned earlier
let cmd = CmdDet::child_revoke_key(ca_handle, child, revoke_request, actor);
self.send_command(cmd).await?;
Ok(res)
}
}
/// # CAs as children
///
impl CaManager {
/// Adds a new parent, or updates an existing parent of a CA. Adding a parent will trigger that the
/// CA connects to this new parent in order to learn its resource entitlements and set up the resource
/// class(es) under it, and request certificate(s).
pub async fn ca_parent_add_or_update(
&self,
handle: Handle,
parent_req: ParentCaReq,
actor: &Actor,
) -> KrillResult<()> {
let ca = self.get_ca(&handle).await?;
let (parent, contact) = parent_req.unpack();
let cmd = if !ca.parent_known(&parent) {
CmdDet::add_parent(&handle, parent, contact, actor)
} else {
CmdDet::update_parent(&handle, parent, contact, actor)
};
self.send_command(cmd).await?;
Ok(())
}
/// Removes a parent from a CA, this will trigger that best effort revocations of existing
/// keys under this parent are requested. Any resource classes under the parent will be removed
/// and all relevant content will be withdrawn from the repository.
pub async fn ca_parent_remove(&self, handle: Handle, parent: ParentHandle, actor: &Actor) -> KrillResult<()> {
// best effort, request revocations for any remaining keys under this parent.
if let Err(e) = self.ca_parent_revoke(&handle, &parent).await {
warn!(
"Removing parent '{}' from CA '{}', but could not send revoke requests: {}",
parent, handle, e
);
}
self.status_store.lock().await.remove_parent(&handle, &parent).await?;
let upd = CmdDet::remove_parent(&handle, parent, actor);
self.send_command(upd).await?;
Ok(())
}
/// Send revocation requests for a parent of a CA when the parent is removed.
pub async fn ca_parent_revoke(&self, handle: &Handle, parent: &ParentHandle) -> KrillResult<()> {
let ca = self.get_ca(handle).await?;
let revoke_requests = ca.revoke_under_parent(parent, &self.signer)?;
self.send_revoke_requests(handle, parent, revoke_requests).await?;
Ok(())
}
/// Refresh all CAs:
/// - process all CAs in parallel
/// - process all parents for CAs in parallel
/// - send pending requests if present, or
/// - ask parent for updates and process if present
///
/// Note: this function can be called manually through the API, but is normally
/// triggered in the background, every 10 mins by default, or as configured
/// by 'ca_refresh' in the configuration.
pub async fn cas_refresh_all(&self, started: Timestamp, actor: &Actor) {
if let Ok(cas) = self.ca_store.list() {
let mut updates = vec![];
for ca_handle in cas {
updates.push(self.cas_refresh_single(ca_handle, started, actor));
}
join_all(updates).await;
}
}
/// Refresh a single CA with its parents, and possibly suspend inactive children.
pub async fn cas_refresh_single(&self, ca_handle: Handle, started: Timestamp, actor: &Actor) {
self.ca_sync_parents(&ca_handle, actor).await;
self.ca_suspend_inactive_children(&ca_handle, started, actor).await;
}
/// Suspend child CAs
async fn ca_suspend_inactive_children(&self, ca_handle: &Handle, started: Timestamp, actor: &Actor) {
// Set threshold hours if it was configured AND this server has been started
// longer ago than the hours specified. Otherwise we risk that *all* children
// without prior recorded status are suspended on upgrade, or that *all* children
// are suspended if the server had been down for more than the threshold hours.
let threshold_seconds = self
.config
.suspend_child_after_inactive_seconds()
.filter(|secs| started < Timestamp::now_minus_seconds(*secs));
// suspend inactive children, if so configured
if let Some(threshold_seconds) = threshold_seconds {
if let Ok(ca_status) = self.get_ca_status(ca_handle).await {
let connections = ca_status.get_children_connection_stats();
for child in connections.suspension_candidates(threshold_seconds) {
let threshold_string = if threshold_seconds >= 3600 {
format!("{} hours", threshold_seconds / 3600)
} else {
format!("{} seconds", threshold_seconds)
};
info!(
"Child '{}' under CA '{}' was inactive for more than {}. Will suspend it.",
child, ca_handle, threshold_string
);
if let Err(e) = self
.status_store
.lock()
.await
.set_child_suspended(ca_handle, &child)
.await
{
panic!("System level error encountered while updating ca status: {}", e);
}
let req = UpdateChildRequest::suspend();
if let Err(e) = self.ca_child_update(ca_handle, child, req, actor).await {
error!("Could not suspend inactive child, error: {}", e);
}
}
}
}
}
/// Synchronizes a CA with its parents - up to the configures batch size.
/// Remaining parents will be done in a future run.
async fn ca_sync_parents(&self, ca_handle: &Handle, actor: &Actor) {
let mut updates = vec![];
if let Ok(ca) = self.get_ca(ca_handle).await {
// get updates from parents
{
if ca.nr_parents() <= self.config.ca_refresh_parents_batch_size {
// Nr of parents is below batch size, so just process all of them
for parent in ca.parents() {
updates.push(self.ca_sync_parent_infallible(ca_handle.clone(), parent.clone(), actor.clone()));
}
} else {
// more parents than the batch size exist, so get candidates based on
// the known parent statuses for this CA.
match self.status_store.lock().await.get_ca_status(ca_handle).await {
Err(e) => {
panic!("System level error encountered while updating ca status: {}", e);
}
Ok(status) => {
for parent in status
.parents()
.sync_candidates(ca.parents().collect(), self.config.ca_refresh_parents_batch_size)
{
updates.push(self.ca_sync_parent_infallible(
ca_handle.clone(),
parent.clone(),
actor.clone(),
));
}
}
};
}
}
join_all(updates).await;
}
}
/// Synchronizes a CA with a parent, logging failures.
async fn ca_sync_parent_infallible(&self, ca: Handle, parent: ParentHandle, actor: Actor) {
if let Err(e) = self.ca_sync_parent(&ca, &parent, &actor).await {
error!(
"Failed to synchronize CA '{}' with parent '{}'. Error was: {}",
ca, parent, e
);
}
}
/// Synchronizes a CA with one of its parents:
/// - send pending requests if present; otherwise
/// - get and process updated entitlements
///
/// Note: if new request events are generated as a result of processing updated entitlements
/// then they will trigger that this synchronization is called again so that the pending
/// requests can be sent.
pub async fn ca_sync_parent(&self, handle: &Handle, parent: &ParentHandle, actor: &Actor) -> KrillResult<()> {
let ca = self.get_ca(handle).await?;
if ca.has_pending_requests(parent) {
self.send_requests(handle, parent, actor).await
} else {
self.get_updates_from_parent(handle, parent, actor).await
}
}
/// Try to get updates from a specific parent of a CA.
async fn get_updates_from_parent(&self, handle: &Handle, parent: &ParentHandle, actor: &Actor) -> KrillResult<()> {
if handle != &ta_handle() {
let ca = self.get_ca(handle).await?;
if ca.repository_contact().is_ok() {
let ca = self.get_ca(handle).await?;
let parent_contact = ca.parent(parent)?;
let entitlements = self
.get_entitlements_from_contact(handle, parent, parent_contact, true)
.await?;
self.update_entitlements(handle, parent.clone(), entitlements, actor)
.await?;
}
}
Ok(())
}
/// Sends requests to a specific parent for the CA matching handle.
async fn send_requests(&self, handle: &Handle, parent: &ParentHandle, actor: &Actor) -> KrillResult<()> {
self.send_revoke_requests_handle_responses(handle, parent, actor)
.await?;
self.send_cert_requests_handle_responses(handle, parent, actor).await
}
async fn send_revoke_requests_handle_responses(
&self,
handle: &Handle,
parent: &ParentHandle,
actor: &Actor,
) -> KrillResult<()> {
let child = self.get_ca(handle).await?;
let requests = child.revoke_requests(parent);
let revoke_responses = self.send_revoke_requests(handle, parent, requests).await?;
for (rcn, revoke_responses) in revoke_responses.into_iter() {
for response in revoke_responses.into_iter() {
let cmd = CmdDet::key_roll_finish(handle, rcn.clone(), response, actor);
self.send_command(cmd).await?;
}
}
Ok(())
}
pub async fn send_revoke_requests(
&self,
handle: &Handle,
parent: &ParentHandle,
revoke_requests: HashMap<ResourceClassName, Vec<RevocationRequest>>,
) -> KrillResult<HashMap<ResourceClassName, Vec<RevocationResponse>>> {
let child = self.get_ca(handle).await?;
match child.parent(parent)? {
ParentCaContact::Ta(_) => Err(Error::TaNotAllowed),
ParentCaContact::Rfc6492(parent_res) => {
let parent_uri = parent_res.service_uri();
let next_run_seconds = self.config.ca_refresh_seconds as i64;
match self