-
-
Notifications
You must be signed in to change notification settings - Fork 35
/
certauth.rs
2160 lines (1832 loc) · 76 KB
/
certauth.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, sync::Arc, vec};
use bytes::Bytes;
use chrono::Duration;
use rpki::{
repository::{
cert::{Cert, KeyUsage, Overclaim, TbsCert},
crypto::{KeyIdentifier, PublicKey},
rta::RtaBuilder,
x509::{Serial, Time, Validity},
},
uri,
};
use crate::{
commons::{
api::{
self, AspaCustomer, AspaDefinitionList, AspaDefinitionUpdates, AspaProvidersUpdate, CertAuthInfo,
ChildHandle, EntitlementClass, Entitlements, Handle, IdCertPem, IssuanceRequest, IssuedCert, ObjectName,
ParentCaContact, ParentHandle, RcvdCert, RepoInfo, RepositoryContact, RequestResourceLimit,
ResourceClassName, ResourceSet, Revocation, RevocationRequest, RevocationResponse, RoaDefinition, RtaList,
RtaName, RtaPrepResponse, SigningCert, StorableCaCommand, TaCertDetails, TrustAnchorLocator,
},
crypto::{CsrInfo, IdCert, IdCertBuilder, KrillSigner, ProtocolCms, ProtocolCmsBuilder},
error::{Error, RoaDeltaError},
eventsourcing::{Aggregate, StoredEvent},
remote::{rfc6492, rfc8183},
KrillResult,
},
constants::test_mode_enabled,
daemon::{
ca::{
events::ChildCertificateUpdates, ta_handle, AspaDefinitions, CaEvt, CaEvtDet, ChildDetails, Cmd, CmdDet,
DropReason, Ini, PreparedRta, ResourceClass, ResourceTaggedAttestation, RouteAuthorization,
RouteAuthorizationUpdates, Routes, RtaContentRequest, RtaPrepareRequest, Rtas, SignedRta,
},
config::{Config, IssuanceTimingConfig},
},
};
//------------ Rfc8183Id ---------------------------------------------------
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Rfc8183Id {
cert: IdCert,
}
impl Rfc8183Id {
pub fn new(cert: IdCert) -> Self {
Rfc8183Id { cert }
}
pub fn generate(signer: &KrillSigner) -> KrillResult<Self> {
let key = signer.create_key()?;
let cert =
IdCertBuilder::new_ta_id_cert(&key, signer.deref()).map_err(|e| Error::SignerError(e.to_string()))?;
Ok(Rfc8183Id { cert })
}
}
impl Rfc8183Id {
pub fn key_hash(&self) -> String {
self.cert.ski_hex()
}
pub fn key_id(&self) -> KeyIdentifier {
self.cert.subject_public_key_info().key_identifier()
}
}
//------------ CertAuthStatus ----------------------------------------------
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
enum CertAuthStatus {
Active,
Deactivated,
}
impl Default for CertAuthStatus {
fn default() -> Self {
CertAuthStatus::Active
}
}
//------------ CertAuth ----------------------------------------------------
/// This type defines a Certification Authority at a slightly higher level
/// than one might expect.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct CertAuth {
handle: Handle,
version: u64,
id: Rfc8183Id, // Used for RFC 6492 (up-down) and RFC 8181 (publication)
repository: Option<RepositoryContact>,
parents: HashMap<ParentHandle, ParentCaContact>,
next_class_name: u32,
resources: HashMap<ResourceClassName, ResourceClass>,
children: HashMap<ChildHandle, ChildDetails>,
routes: Routes,
#[serde(skip_serializing_if = "Rtas::is_empty", default = "Rtas::default")]
rtas: Rtas,
#[serde(
skip_serializing_if = "AspaDefinitions::is_empty",
default = "AspaDefinitions::default"
)]
aspas: AspaDefinitions,
#[serde(skip_serializing, default = "CertAuthStatus::default")]
status: CertAuthStatus,
}
impl Aggregate for CertAuth {
type Command = Cmd;
type StorableCommandDetails = StorableCaCommand;
type Event = CaEvt;
type InitEvent = Ini;
type Error = Error;
fn init(event: Ini) -> KrillResult<Self> {
let (handle, _version, details) = event.unpack();
let id = details.unpack();
let parents = HashMap::new();
let resources = HashMap::new();
let next_class_name = 0;
let children = HashMap::new();
let routes = Routes::default();
let rtas = Rtas::default();
let aspas = AspaDefinitions::default();
let repository = None;
Ok(CertAuth {
handle,
version: 1,
id,
repository,
parents,
next_class_name,
resources,
children,
routes,
rtas,
aspas,
status: CertAuthStatus::Active,
})
}
fn version(&self) -> u64 {
self.version
}
fn apply(&mut self, event: CaEvt) {
self.version += 1;
match event.into_details() {
//-----------------------------------------------------------------------
// Being a trust anchor
//-----------------------------------------------------------------------
CaEvtDet::TrustAnchorMade { ta_cert_details } => {
let key_id = ta_cert_details.cert().subject_key_identifier();
self.parents.insert(ta_handle(), ParentCaContact::Ta(ta_cert_details));
let rcn = ResourceClassName::from(self.next_class_name);
self.next_class_name += 1;
self.resources.insert(rcn.clone(), ResourceClass::for_ta(rcn, key_id));
}
//-----------------------------------------------------------------------
// Being a parent
//-----------------------------------------------------------------------
CaEvtDet::ChildAdded {
child,
id_cert,
resources,
} => {
let details = ChildDetails::new(id_cert, resources);
self.children.insert(child, details);
}
CaEvtDet::ChildCertificateIssued {
child,
resource_class_name,
ki,
} => {
self.children
.get_mut(&child)
.unwrap()
.add_issue_response(resource_class_name, ki);
}
CaEvtDet::ChildKeyRevoked {
child,
resource_class_name,
ki,
} => {
self.resources.get_mut(&resource_class_name).unwrap().key_revoked(&ki);
self.children.get_mut(&child).unwrap().add_revoke_response(ki);
}
CaEvtDet::ChildCertificatesUpdated {
resource_class_name,
updates,
} => {
let rc = self.resources.get_mut(&resource_class_name).unwrap();
let (issued, removed, suspended_certs, unsuspended_certs) = updates.unpack();
for cert in issued {
rc.certificate_issued(cert)
}
for cert in unsuspended_certs {
rc.certificate_unsuspended(cert)
}
for rem in removed {
rc.key_revoked(&rem);
// This loop is inefficient, but certificate revocations are not that common, so it's
// not a big deal. Tracking this better would require that we track the child handle somehow.
// That is a bit hard when this revocation is the result from a republish where we lost
// all resources delegated to the child.
for child in self.children.values_mut() {
if child.is_issued(&rem) {
child.add_revoke_response(rem)
}
}
}
for cert in suspended_certs {
rc.certificate_suspended(cert);
}
}
CaEvtDet::ChildUpdatedIdCert { child, id_cert } => {
self.children.get_mut(&child).unwrap().set_id_cert(id_cert)
}
CaEvtDet::ChildUpdatedResources { child, resources } => {
self.children.get_mut(&child).unwrap().set_resources(resources)
}
CaEvtDet::ChildRemoved { child } => {
self.children.remove(&child);
}
CaEvtDet::ChildSuspended { child } => self.children.get_mut(&child).unwrap().suspend(),
CaEvtDet::ChildUnsuspended { child } => self.children.get_mut(&child).unwrap().unsuspend(),
//-----------------------------------------------------------------------
// Being a child
//-----------------------------------------------------------------------
CaEvtDet::IdUpdated { id } => {
self.id = id;
}
CaEvtDet::ParentAdded { parent, contact } => {
self.parents.insert(parent, contact);
}
CaEvtDet::ParentUpdated { parent, contact } => {
self.parents.insert(parent, contact);
}
CaEvtDet::ParentRemoved { parent } => {
self.parents.remove(&parent);
self.resources.retain(|_, rc| rc.parent_handle() != &parent);
}
CaEvtDet::ResourceClassAdded {
resource_class_name,
parent,
parent_resource_class_name,
pending_key,
} => {
self.next_class_name += 1;
let ns = resource_class_name.to_string();
let rc = ResourceClass::create(
resource_class_name.clone(),
ns,
parent,
parent_resource_class_name,
pending_key,
);
self.resources.insert(resource_class_name, rc);
}
CaEvtDet::ResourceClassRemoved {
resource_class_name, ..
} => {
self.resources.remove(&resource_class_name);
}
CaEvtDet::CertificateRequested {
resource_class_name,
req,
ki,
} => {
self.resources
.get_mut(&resource_class_name)
.unwrap()
.add_request(ki, req);
}
CaEvtDet::CertificateReceived {
resource_class_name,
ki,
rcvd_cert,
} => {
self.resources
.get_mut(&resource_class_name)
.unwrap()
.received_cert(ki, rcvd_cert);
}
//-----------------------------------------------------------------------
// Key Life Cycle
//-----------------------------------------------------------------------
CaEvtDet::KeyRollPendingKeyAdded {
resource_class_name,
pending_key_id: pending_key,
} => {
self.resources
.get_mut(&resource_class_name)
.unwrap()
.pending_key_id_added(pending_key);
}
CaEvtDet::KeyPendingToNew {
resource_class_name,
new_key,
} => {
self.resources
.get_mut(&resource_class_name)
.unwrap()
.pending_key_to_new(new_key);
}
CaEvtDet::KeyPendingToActive {
resource_class_name,
current_key,
} => {
self.resources
.get_mut(&resource_class_name)
.unwrap()
.pending_key_to_active(current_key);
}
CaEvtDet::KeyRollActivated {
resource_class_name,
revoke_req,
} => {
self.resources
.get_mut(&resource_class_name)
.unwrap()
.new_key_activated(revoke_req);
}
CaEvtDet::KeyRollFinished { resource_class_name } => {
self.resources.get_mut(&resource_class_name).unwrap().old_key_removed();
}
CaEvtDet::UnexpectedKeyFound { .. } => {
// no action needed, this is marked to flag that a key may be removed on the
// server side. The revocation requests are picked up by the `MessageQueue`
// listener.
}
//-----------------------------------------------------------------------
// Route Authorizations
//-----------------------------------------------------------------------
CaEvtDet::RouteAuthorizationAdded { auth } => self.routes.add(auth),
CaEvtDet::RouteAuthorizationRemoved { auth } => {
self.routes.remove(&auth);
}
CaEvtDet::RoasUpdated {
resource_class_name,
updates,
} => self
.resources
.get_mut(&resource_class_name)
.unwrap()
.roas_updated(updates),
//-----------------------------------------------------------------------
// Autonomous System Provider Authorization
//-----------------------------------------------------------------------
CaEvtDet::AspaConfigAdded { aspa_config } => self.aspas.add_or_replace(aspa_config),
CaEvtDet::AspaConfigUpdated { customer, update } => self.aspas.apply_update(customer, &update),
CaEvtDet::AspaConfigRemoved { customer } => self.aspas.remove(customer),
CaEvtDet::AspaObjectsUpdated {
resource_class_name,
updates,
} => self
.resources
.get_mut(&resource_class_name)
.unwrap()
.aspa_objects_updated(updates),
//-----------------------------------------------------------------------
// Publication
//-----------------------------------------------------------------------
CaEvtDet::RepoUpdated { contact } => {
if let Some(current) = &self.repository {
for rc in self.resources.values_mut() {
rc.set_old_repo(current.repo_info());
}
}
self.repository = Some(contact);
}
//-----------------------------------------------------------------------
// Resource Tagged Attestations
//-----------------------------------------------------------------------
CaEvtDet::RtaPrepared { name, prepared } => {
self.rtas.add_prepared(name, prepared);
}
CaEvtDet::RtaSigned { name, rta } => {
self.rtas.add_signed(name, rta);
}
}
}
fn process_command(&self, command: Cmd) -> KrillResult<Vec<CaEvt>> {
if log_enabled!(log::Level::Trace) {
trace!(
"Sending command to CA '{}', version: {}: {}",
self.handle,
self.version,
command
);
}
match command.into_details() {
// trust anchor
CmdDet::MakeTrustAnchor(uris, rsync_uri, signer) => self.trust_anchor_make(uris, rsync_uri, signer),
// being a parent
CmdDet::ChildAdd(child, id_cert, resources) => self.child_add(child, id_cert, resources),
CmdDet::ChildUpdateResources(child, res) => self.child_update_resources(&child, res),
CmdDet::ChildUpdateId(child, id) => self.child_update_id(&child, id),
CmdDet::ChildCertify(child, request, config, signer) => self.child_certify(child, request, &config, signer),
CmdDet::ChildRevokeKey(child, request) => self.child_revoke_key(child, request),
CmdDet::ChildRemove(child) => self.child_remove(&child),
CmdDet::ChildSuspendInactive(child) => self.child_suspend_inactive(&child),
CmdDet::ChildUnsuspend(child) => self.child_unsuspend(&child),
// being a child
CmdDet::GenerateNewIdKey(signer) => self.generate_new_id_key(signer),
CmdDet::AddParent(parent, info) => self.add_parent(parent, info),
CmdDet::UpdateParentContact(parent, info) => self.update_parent(parent, info),
CmdDet::RemoveParent(parent) => self.remove_parent(parent),
CmdDet::UpdateEntitlements(parent, entitlements, signer) => {
self.update_entitlements(parent, entitlements, signer)
}
CmdDet::UpdateRcvdCert(class_name, rcvd_cert, config, signer) => {
self.update_received_cert(class_name, rcvd_cert, &config, signer)
}
CmdDet::DropResourceClass(rcn, reason, signer) => self.drop_resource_class(rcn, reason, signer),
// Key rolls
CmdDet::KeyRollInitiate(duration, signer) => self.keyroll_initiate(duration, signer),
CmdDet::KeyRollActivate(duration, config, signer) => self.keyroll_activate(duration, config, signer),
CmdDet::KeyRollFinish(rcn, response) => self.keyroll_finish(rcn, response),
// Route Authorizations
CmdDet::RouteAuthorizationsUpdate(updates, config, signer) => {
self.route_authorizations_update(updates, &config, signer)
}
CmdDet::RouteAuthorizationsRenew(config, signer) => {
self.route_authorizations_renew(false, &config, &signer)
}
CmdDet::RouteAuthorizationsForceRenew(config, signer) => {
self.route_authorizations_renew(true, &config, &signer)
}
// ASPA
CmdDet::AspasUpdate(updates, config, signer) => self.aspas_definitions_update(updates, &config, &signer),
CmdDet::AspasUpdateExisting(customer, update, config, signer) => {
self.aspas_update(customer, update, &config, &signer)
}
CmdDet::AspasRenew(config, signer) => self.aspas_renew(&config, &signer),
// Republish
CmdDet::RepoUpdate(contact, signer) => self.update_repo(contact, &signer),
// Resource Tagged Attestations
CmdDet::RtaMultiPrepare(name, request, signer) => self.rta_multi_prep(name, request, signer.deref()),
CmdDet::RtaCoSign(name, rta, signer) => self.rta_cosign(name, rta, signer.deref()),
CmdDet::RtaSign(name, request, signer) => self.rta_sign(name, request, signer.deref()),
}
}
}
/// # Data presentation
///
impl CertAuth {
// For many commands with multiple resulting events, it's easier to build a list of event *details*
// and worry about numbering the versions here.
fn events_from_details(&self, event_details: Vec<CaEvtDet>) -> Vec<CaEvt> {
let mut res = vec![];
let mut version = self.version;
for event in event_details {
res.push(StoredEvent::new(&self.handle, version, event));
version += 1;
}
res
}
}
/// # Data presentation
///
impl CertAuth {
/// Returns a `CertAuthInfo` for this, which includes a data representation
/// of the internal structure, in particular with regards to parent, children,
/// resource classes and keys.
pub fn as_ca_info(&self) -> CertAuthInfo {
let handle = self.handle.clone();
let repo_info = self.repository.as_ref().map(|repo| repo.repo_info().clone());
let parents = self.parents.clone();
let mut resources = HashMap::new();
for (name, rc) in &self.resources {
resources.insert(name.clone(), rc.as_info());
}
let children: Vec<ChildHandle> = self.children.keys().cloned().collect();
let id_cert_pem = IdCertPem::from(&self.id.cert);
let suspended_children = self
.children
.iter()
.filter(|(_ca, details)| details.is_suspended())
.map(|(ca, _)| ca.clone())
.collect();
CertAuthInfo::new(
handle,
id_cert_pem,
repo_info,
parents,
resources,
children,
suspended_children,
)
}
/// Returns the current RoaDefinitions for this, i.e. the intended authorized
/// prefixes. Provided that the resources are held by this `CertAuth` one can
/// expect that corresponding ROA **objects** are created by the system.
pub fn roa_definitions(&self) -> Vec<RoaDefinition> {
self.routes.authorizations().map(|a| a.as_ref()).cloned().collect()
}
/// Returns an RFC 8183 Child Request - which can be represented as XML to a
/// parent of this `CertAuth`
pub fn child_request(&self) -> rfc8183::ChildRequest {
rfc8183::ChildRequest::new(self.handle.clone(), self.id.cert.clone())
}
/// Returns an RFC 8183 Publisher Request - which can be represented as XML to a
/// repository for this `CertAuth`
pub fn publisher_request(&self) -> rfc8183::PublisherRequest {
rfc8183::PublisherRequest::new(None, self.handle.clone(), self.id_cert().clone())
}
pub fn id_cert(&self) -> &IdCert {
&self.id.cert
}
pub fn id_key(&self) -> KeyIdentifier {
self.id.cert.subject_public_key_info().key_identifier()
}
pub fn handle(&self) -> &Handle {
&self.handle
}
/// Returns the complete set of all currently received resources, under all parents, for
/// this `CertAuth`
pub fn all_resources(&self) -> ResourceSet {
let mut resources = ResourceSet::default();
for rc in self.resources.values() {
if let Some(rc_resources) = rc.current_resources() {
resources = resources.union(rc_resources);
}
}
resources
}
}
/// # Publishing
///
impl CertAuth {
pub fn repository_contact(&self) -> KrillResult<&RepositoryContact> {
self.repository.as_ref().ok_or(Error::RepoNotSet)
}
pub fn repository_info(&self) -> KrillResult<&RepoInfo> {
self.repository_contact().map(|contact| contact.repo_info())
}
}
/// # Being a Trust Anchor
///
impl CertAuth {
fn trust_anchor_make(
&self,
uris: Vec<uri::Https>,
rsync_uri: Option<uri::Rsync>,
signer: Arc<KrillSigner>,
) -> KrillResult<Vec<CaEvt>> {
if !self.resources.is_empty() {
return Err(Error::custom("Cannot turn CA with resources into TA"));
}
let repo_info = self.repository_contact()?.repo_info();
let key = signer.create_key()?;
let resources = ResourceSet::all_resources();
let cert = {
let serial: Serial = signer.random_serial()?;
let pub_key = signer.get_key_info(&key).map_err(Error::signer)?;
let name = pub_key.to_subject_name();
let mut cert = TbsCert::new(
serial,
name.clone(),
Validity::new(Time::five_minutes_ago(), Time::years_from_now(100)),
Some(name),
pub_key.clone(),
KeyUsage::Ca,
Overclaim::Refuse,
);
cert.set_basic_ca(Some(true));
let ns = ResourceClassName::default().to_string();
cert.set_ca_repository(Some(repo_info.ca_repository(&ns)));
cert.set_rpki_manifest(Some(repo_info.rpki_manifest(&ns, &pub_key.key_identifier())));
cert.set_rpki_notify(Some(repo_info.rpki_notify()));
cert.set_as_resources(resources.to_as_resources());
cert.set_v4_resources(resources.to_ip_resources_v4());
cert.set_v6_resources(resources.to_ip_resources_v6());
signer.sign_cert(cert, &key)?
};
let tal = TrustAnchorLocator::new(uris, rsync_uri, &cert);
let ta_cert_details = TaCertDetails::new(cert, resources, tal);
info!("Created Trust Anchor");
Ok(vec![StoredEvent::new(
&self.handle,
self.version,
CaEvtDet::TrustAnchorMade { ta_cert_details },
)])
}
}
/// # Being a parent
///
impl CertAuth {
pub fn verify_rfc6492(&self, msg: ProtocolCms) -> KrillResult<rfc6492::Message> {
let content = rfc6492::Message::from_signed_message(&msg)?;
let child_handle = content.sender();
let child = self.get_child(child_handle)?;
msg.validate(child.id_cert())
.map_err(|_| Error::Rfc6492SignatureInvalid)?;
Ok(content)
}
pub fn sign_rfc6492_response(&self, msg: rfc6492::Message, signer: &KrillSigner) -> KrillResult<Bytes> {
let key = &self.id.key_id();
Ok(ProtocolCmsBuilder::create(key, signer, msg.into_bytes())
.map_err(Error::signer)?
.as_bytes())
}
/// List entitlements (section 3.3.2 of RFC6492). Return an error if
/// the child is not authorized -- or unknown etc.
pub fn list(
&self,
child_handle: &Handle,
issuance_timing: &IssuanceTimingConfig,
) -> KrillResult<api::Entitlements> {
let mut classes = vec![];
for rcn in self.resources.keys() {
if let Some(class) = self.entitlement_class(child_handle, rcn, issuance_timing) {
classes.push(class);
}
}
Ok(Entitlements::new(classes))
}
/// Returns an issuance response for a child and a specific resource
/// class name and public key for the issued certificate.
pub fn issuance_response(
&self,
child_handle: &Handle,
class_name: &ResourceClassName,
pub_key: &PublicKey,
issuance_timing: &IssuanceTimingConfig,
) -> KrillResult<api::IssuanceResponse> {
let entitlement_class = self
.entitlement_class(child_handle, class_name, issuance_timing)
.ok_or(Error::KeyUseNoIssuedCert)?;
entitlement_class
.into_issuance_response(pub_key)
.ok_or(Error::KeyUseNoIssuedCert)
}
/// Returns the EntitlementClass for this child for the given class name.
fn entitlement_class(
&self,
child_handle: &Handle,
rcn: &ResourceClassName,
issuance_timing: &IssuanceTimingConfig,
) -> Option<api::EntitlementClass> {
let my_rc = match self.resources.get(rcn) {
Some(rc) => rc,
None => return None,
};
let my_current_key = match my_rc.current_key() {
Some(key) => key,
None => return None,
};
let my_rcvd_cert = my_current_key.incoming_cert();
let issuer = SigningCert::new(my_rcvd_cert.uri().clone(), my_rcvd_cert.cert().clone());
let child = match self.get_child(child_handle) {
Ok(child) => child,
Err(_) => return None,
};
let child_resources = my_rcvd_cert.resources().intersection(child.resources());
if child_resources.is_empty() {
return None;
}
let child_keys = child.issued(rcn);
let mut issued_certs = vec![];
let mut not_after = Time::now();
for ki in child_keys {
if let Some(issued) = my_rc.issued(&ki) {
issued_certs.push(issued.clone());
let eligible_not_after = Self::child_cert_eligible_not_after(issued, issuance_timing);
if eligible_not_after > not_after {
not_after = eligible_not_after
}
}
}
Some(EntitlementClass::new(
rcn.clone(),
issuer,
child_resources,
not_after,
issued_certs,
))
}
fn child_cert_eligible_not_after(issued: &IssuedCert, issuance_timing: &IssuanceTimingConfig) -> Time {
let expiration_time = issued.validity().not_after();
if expiration_time
> Time::now() + chrono::Duration::weeks(issuance_timing.timing_child_certificate_reissue_weeks_before)
{
expiration_time
} else {
Time::now() + chrono::Duration::weeks(issuance_timing.timing_child_certificate_valid_weeks)
}
}
/// Returns a child, or an error if the child is unknown.
pub fn get_child(&self, child: &Handle) -> KrillResult<&ChildDetails> {
match self.children.get(child) {
None => Err(Error::CaChildUnknown(self.handle.clone(), child.clone())),
Some(child) => Ok(child),
}
}
/// Returns an iterator for the handles of all children under this CA.
pub fn children(&self) -> impl Iterator<Item = &ChildHandle> {
self.children.keys()
}
/// Adds the child, returns an error if the child is a duplicate,
/// or if the resources are empty, or not held by this CA.
fn child_add(&self, child: ChildHandle, id_cert: IdCert, resources: ResourceSet) -> KrillResult<Vec<CaEvt>> {
if resources.is_empty() {
Err(Error::CaChildMustHaveResources(self.handle.clone(), child))
} else if !self.all_resources().contains(&resources) {
Err(Error::CaChildExtraResources(self.handle.clone(), child))
} else if self.has_child(&child) {
Err(Error::CaChildDuplicate(self.handle.clone(), child))
} else {
info!(
"CA '{}' added child '{}' with resources '{}'",
self.handle, child, resources
);
Ok(vec![CaEvtDet::child_added(
&self.handle,
self.version,
child,
id_cert,
resources,
)])
}
}
/// Certifies a child, unless:
/// = the child is unknown,
/// = the child is not authorized,
/// = the csr is invalid,
/// = the limit exceeds the child allocation,
/// = the signer throws up..
fn child_certify(
&self,
child: Handle,
request: IssuanceRequest,
config: &Config,
signer: Arc<KrillSigner>,
) -> KrillResult<Vec<CaEvt>> {
let (rcn, limit, csr) = request.unpack();
let csr_info = CsrInfo::try_from(&csr)?;
if !csr_info.global_uris() && !test_mode_enabled() {
return Err(Error::invalid_csr(
"MUST use hostnames in URIs for certificate requests.",
));
}
let issued =
self.issue_child_certificate(&child, rcn.clone(), csr_info, limit, &config.issuance_timing, &signer)?;
let cert_name = ObjectName::from(issued.cert());
info!(
"CA '{}' issued certificate '{}' to child '{}'",
self.handle, cert_name, child
);
let issued_event = CaEvtDet::child_certificate_issued(
&self.handle,
self.version,
child,
rcn.clone(),
issued.subject_key_identifier(),
);
let mut cert_updates = ChildCertificateUpdates::default();
cert_updates.issue(issued);
let child_certs_updated =
CaEvtDet::child_certificates_updated(&self.handle, self.version + 1, rcn, cert_updates);
Ok(vec![issued_event, child_certs_updated])
}
/// Issue a new child certificate.
fn issue_child_certificate(
&self,
child: &ChildHandle,
rcn: ResourceClassName,
csr_info: CsrInfo,
limit: RequestResourceLimit,
issuance_timing: &IssuanceTimingConfig,
signer: &KrillSigner,
) -> KrillResult<IssuedCert> {
let my_rc = self.resources.get(&rcn).ok_or(Error::ResourceClassUnknown(rcn))?;
let child = self.get_child(child)?;
child.resources().apply_limit(&limit)?;
my_rc.issue_cert(csr_info, child.resources(), limit, issuance_timing, signer)
}
/// Updates child Resource entitlements.
///
/// This does not yet revoke / reissue / republish anything.
/// Also, this is a no-op if the child already has these resources.
fn child_update_resources(&self, child_handle: &Handle, resources: ResourceSet) -> KrillResult<Vec<CaEvt>> {
if !self.all_resources().contains(&resources) {
Err(Error::CaChildExtraResources(self.handle.clone(), child_handle.clone()))
} else {
let child = self.get_child(child_handle)?;
let resources_diff = resources.difference(child.resources());
if !resources_diff.is_empty() {
info!(
"CA '{}' update child '{}' resources: {}",
self.handle, child_handle, resources_diff
);
Ok(vec![CaEvtDet::child_updated_resources(
&self.handle,
self.version,
child_handle.clone(),
resources,
)])
} else {
// Using 'debug' here, because there are possible use cases where updating the child resources to some expected
// resource set should be considered a no-op without complaints. E.g. if there is a background job calling
// the API and setting entitlements.
debug!(
"CA '{}' update child '{}' resources has no effect, child already holds all resources",
self.handle, child_handle
);
Ok(vec![])
}
}
}
/// Updates child IdCert
fn child_update_id(&self, child_handle: &Handle, id_cert: IdCert) -> KrillResult<Vec<CaEvt>> {
let child = self.get_child(child_handle)?;
if &id_cert != child.id_cert() {
info!(
"CA '{}' updated child '{}' cert. New key id: {}",
self.handle,
child_handle,
id_cert.subject_public_key_info().key_identifier()
);
Ok(vec![CaEvtDet::child_updated_cert(
&self.handle,
self.version,
child_handle.clone(),
id_cert,
)])
} else {
// Using 'debug' here, because of possible no-op use cases where the API is called from a background job.
debug!(
"CA '{}' updated child '{}' cert had no effect. Child ID certificate is identical",
self.handle, child_handle
);
Ok(vec![])
}
}
/// Revokes a key for a child. So, add the last cert for the key to the CRL, and withdraw
/// the .cer file for it.
fn child_revoke_key(&self, child_handle: ChildHandle, request: RevocationRequest) -> KrillResult<Vec<CaEvt>> {
let (rcn, key) = request.unpack();
let child = self.get_child(&child_handle)?;
if !child.is_issued(&key) {
return Err(Error::KeyUseNoIssuedCert);
}
let handle = &self.handle;
let version = self.version;
let mut child_certificate_updates = ChildCertificateUpdates::default();
child_certificate_updates.remove(key);
let cert_name = ObjectName::new(&key, "cer");
info!(
"CA '{}' revoked certificate '{}' for child '{}'",
handle, cert_name, child_handle
);
let rev = CaEvtDet::child_revoke_key(handle, version, child_handle, rcn.clone(), key);
let upd = CaEvtDet::child_certificates_updated(handle, version + 1, rcn, child_certificate_updates);
Ok(vec![rev, upd])
}
fn child_remove(&self, child_handle: &ChildHandle) -> KrillResult<Vec<CaEvt>> {
let child = self.get_child(child_handle)?;
let mut version = self.version;
let handle = &self.handle;
let mut res = vec![];
// Find all the certs in all RCs for this child and revoke, and withdraw them.
for (rcn, rc) in self.resources.iter() {
let certified_keys = child.issued(rcn);
if certified_keys.is_empty() {
continue;
}
let mut issued_certs = vec![];