-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
storage.go
1517 lines (1277 loc) · 46.1 KB
/
storage.go
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
package pki
import (
"bytes"
"context"
"crypto"
"crypto/x509"
"fmt"
"sort"
"strings"
"time"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/vault/helper/constants"
"github.com/hashicorp/vault/sdk/helper/certutil"
"github.com/hashicorp/vault/sdk/helper/errutil"
"github.com/hashicorp/vault/sdk/logical"
)
const (
storageKeyConfig = "config/keys"
storageIssuerConfig = "config/issuers"
keyPrefix = "config/key/"
issuerPrefix = "config/issuer/"
storageLocalCRLConfig = "crls/config"
storageUnifiedCRLConfig = "unified-crls/config"
legacyMigrationBundleLogKey = "config/legacyMigrationBundleLog"
legacyCertBundlePath = "config/ca_bundle"
legacyCertBundleBackupPath = "config/ca_bundle.bak"
legacyCRLPath = "crl"
deltaCRLPath = "delta-crl"
deltaCRLPathSuffix = "-delta"
unifiedCRLPath = "unified-crl"
unifiedDeltaCRLPath = "unified-delta-crl"
unifiedCRLPathPrefix = "unified-"
autoTidyConfigPath = "config/auto-tidy"
clusterConfigPath = "config/cluster"
// Used as a quick sanity check for a reference id lookups...
uuidLength = 36
maxRolesToScanOnIssuerChange = 100
maxRolesToFindOnIssuerChange = 10
latestIssuerVersion = 1
)
type keyID string
func (p keyID) String() string {
return string(p)
}
type issuerID string
func (p issuerID) String() string {
return string(p)
}
type crlID string
func (p crlID) String() string {
return string(p)
}
const (
IssuerRefNotFound = issuerID("not-found")
KeyRefNotFound = keyID("not-found")
)
type keyEntry struct {
ID keyID `json:"id"`
Name string `json:"name"`
PrivateKeyType certutil.PrivateKeyType `json:"private_key_type"`
PrivateKey string `json:"private_key"`
}
func (e keyEntry) getManagedKeyUUID() (UUIDKey, error) {
if !e.isManagedPrivateKey() {
return "", errutil.InternalError{Err: "getManagedKeyId called on a key id %s (%s) "}
}
return extractManagedKeyId([]byte(e.PrivateKey))
}
func (e keyEntry) isManagedPrivateKey() bool {
return e.PrivateKeyType == certutil.ManagedPrivateKey
}
type issuerUsage uint
const (
ReadOnlyUsage issuerUsage = iota
IssuanceUsage issuerUsage = 1 << iota
CRLSigningUsage issuerUsage = 1 << iota
OCSPSigningUsage issuerUsage = 1 << iota
// When adding a new usage in the future, we'll need to create a usage
// mask field on the IssuerEntry and handle migrations to a newer mask,
// inferring a value for the new bits.
AllIssuerUsages = ReadOnlyUsage | IssuanceUsage | CRLSigningUsage | OCSPSigningUsage
)
var namedIssuerUsages = map[string]issuerUsage{
"read-only": ReadOnlyUsage,
"issuing-certificates": IssuanceUsage,
"crl-signing": CRLSigningUsage,
"ocsp-signing": OCSPSigningUsage,
}
func (i *issuerUsage) ToggleUsage(usages ...issuerUsage) {
for _, usage := range usages {
*i ^= usage
}
}
func (i issuerUsage) HasUsage(usage issuerUsage) bool {
return (i & usage) == usage
}
func (i issuerUsage) Names() string {
var names []string
var builtUsage issuerUsage
// Return the known set of usages in a sorted order to not have Terraform state files flipping
// saying values are different when it's the same list in a different order.
keys := make([]string, 0, len(namedIssuerUsages))
for k := range namedIssuerUsages {
keys = append(keys, k)
}
sort.Strings(keys)
for _, name := range keys {
usage := namedIssuerUsages[name]
if i.HasUsage(usage) {
names = append(names, name)
builtUsage.ToggleUsage(usage)
}
}
if i != builtUsage {
// Found some unknown usage, we should indicate this in the names.
names = append(names, fmt.Sprintf("unknown:%v", i^builtUsage))
}
return strings.Join(names, ",")
}
func NewIssuerUsageFromNames(names []string) (issuerUsage, error) {
var result issuerUsage
for index, name := range names {
usage, ok := namedIssuerUsages[name]
if !ok {
return ReadOnlyUsage, fmt.Errorf("unknown name for usage at index %v: %v", index, name)
}
result.ToggleUsage(usage)
}
return result, nil
}
type issuerEntry struct {
ID issuerID `json:"id"`
Name string `json:"name"`
KeyID keyID `json:"key_id"`
Certificate string `json:"certificate"`
CAChain []string `json:"ca_chain"`
ManualChain []issuerID `json:"manual_chain"`
SerialNumber string `json:"serial_number"`
LeafNotAfterBehavior certutil.NotAfterBehavior `json:"not_after_behavior"`
Usage issuerUsage `json:"usage"`
RevocationSigAlg x509.SignatureAlgorithm `json:"revocation_signature_algorithm"`
Revoked bool `json:"revoked"`
RevocationTime int64 `json:"revocation_time"`
RevocationTimeUTC time.Time `json:"revocation_time_utc"`
AIAURIs *aiaConfigEntry `json:"aia_uris,omitempty"`
LastModified time.Time `json:"last_modified"`
Version uint `json:"version"`
}
type internalCRLConfigEntry struct {
IssuerIDCRLMap map[issuerID]crlID `json:"issuer_id_crl_map"`
CRLNumberMap map[crlID]int64 `json:"crl_number_map"`
LastCompleteNumberMap map[crlID]int64 `json:"last_complete_number_map"`
CRLExpirationMap map[crlID]time.Time `json:"crl_expiration_map"`
LastModified time.Time `json:"last_modified"`
DeltaLastModified time.Time `json:"delta_last_modified"`
UseGlobalQueue bool `json:"cross_cluster_revocation"`
}
type keyConfigEntry struct {
DefaultKeyId keyID `json:"default"`
}
type issuerConfigEntry struct {
// This new fetchedDefault field allows us to detect if the default
// issuer was modified, in turn dispatching the timestamp updater
// if necessary.
fetchedDefault issuerID `json:"-"`
DefaultIssuerId issuerID `json:"default"`
DefaultFollowsLatestIssuer bool `json:"default_follows_latest_issuer"`
}
type clusterConfigEntry struct {
Path string `json:"path"`
AIAPath string `json:"aia_path"`
}
type aiaConfigEntry struct {
IssuingCertificates []string `json:"issuing_certificates"`
CRLDistributionPoints []string `json:"crl_distribution_points"`
OCSPServers []string `json:"ocsp_servers"`
EnableTemplating bool `json:"enable_templating"`
}
func (c *aiaConfigEntry) toURLEntries(sc *storageContext, issuer issuerID) (*certutil.URLEntries, error) {
if len(c.IssuingCertificates) == 0 && len(c.CRLDistributionPoints) == 0 && len(c.OCSPServers) == 0 {
return &certutil.URLEntries{}, nil
}
result := certutil.URLEntries{
IssuingCertificates: c.IssuingCertificates[:],
CRLDistributionPoints: c.CRLDistributionPoints[:],
OCSPServers: c.OCSPServers[:],
}
if c.EnableTemplating {
cfg, err := sc.getClusterConfig()
if err != nil {
return nil, fmt.Errorf("error fetching cluster-local address config: %w", err)
}
for name, source := range map[string]*[]string{
"issuing_certificates": &result.IssuingCertificates,
"crl_distribution_points": &result.CRLDistributionPoints,
"ocsp_servers": &result.OCSPServers,
} {
templated := make([]string, len(*source))
for index, uri := range *source {
if strings.Contains(uri, "{{cluster_path}}") && len(cfg.Path) == 0 {
return nil, fmt.Errorf("unable to template AIA URLs as we lack local cluster address information (path)")
}
if strings.Contains(uri, "{{cluster_aia_path}}") && len(cfg.AIAPath) == 0 {
return nil, fmt.Errorf("unable to template AIA URLs as we lack local cluster address information (aia_path)")
}
if strings.Contains(uri, "{{issuer_id}}") && len(issuer) == 0 {
// Elide issuer AIA info as we lack an issuer_id.
return nil, fmt.Errorf("unable to template AIA URLs as we lack an issuer_id for this operation")
}
uri = strings.ReplaceAll(uri, "{{cluster_path}}", cfg.Path)
uri = strings.ReplaceAll(uri, "{{cluster_aia_path}}", cfg.AIAPath)
uri = strings.ReplaceAll(uri, "{{issuer_id}}", issuer.String())
templated[index] = uri
}
if uri := validateURLs(templated); uri != "" {
return nil, fmt.Errorf("error validating templated %v; invalid URI: %v", name, uri)
}
*source = templated
}
}
return &result, nil
}
type storageContext struct {
Context context.Context
Storage logical.Storage
Backend *backend
}
func (b *backend) makeStorageContext(ctx context.Context, s logical.Storage) *storageContext {
return &storageContext{
Context: ctx,
Storage: s,
Backend: b,
}
}
func (sc *storageContext) listKeys() ([]keyID, error) {
strList, err := sc.Storage.List(sc.Context, keyPrefix)
if err != nil {
return nil, err
}
keyIds := make([]keyID, 0, len(strList))
for _, entry := range strList {
keyIds = append(keyIds, keyID(entry))
}
return keyIds, nil
}
func (sc *storageContext) fetchKeyById(keyId keyID) (*keyEntry, error) {
if len(keyId) == 0 {
return nil, errutil.InternalError{Err: "unable to fetch pki key: empty key identifier"}
}
entry, err := sc.Storage.Get(sc.Context, keyPrefix+keyId.String())
if err != nil {
return nil, errutil.InternalError{Err: fmt.Sprintf("unable to fetch pki key: %v", err)}
}
if entry == nil {
return nil, errutil.UserError{Err: fmt.Sprintf("pki key id %s does not exist", keyId.String())}
}
var key keyEntry
if err := entry.DecodeJSON(&key); err != nil {
return nil, errutil.InternalError{Err: fmt.Sprintf("unable to decode pki key with id %s: %v", keyId.String(), err)}
}
return &key, nil
}
func (sc *storageContext) writeKey(key keyEntry) error {
keyId := key.ID
json, err := logical.StorageEntryJSON(keyPrefix+keyId.String(), key)
if err != nil {
return err
}
return sc.Storage.Put(sc.Context, json)
}
func (sc *storageContext) deleteKey(id keyID) (bool, error) {
config, err := sc.getKeysConfig()
if err != nil {
return false, err
}
wasDefault := false
if config.DefaultKeyId == id {
wasDefault = true
config.DefaultKeyId = keyID("")
if err := sc.setKeysConfig(config); err != nil {
return wasDefault, err
}
}
return wasDefault, sc.Storage.Delete(sc.Context, keyPrefix+id.String())
}
func (sc *storageContext) importKey(keyValue string, keyName string, keyType certutil.PrivateKeyType) (*keyEntry, bool, error) {
// importKey imports the specified PEM-format key (from keyValue) into
// the new PKI storage format. The first return field is a reference to
// the new key; the second is whether or not the key already existed
// during import (in which case, *key points to the existing key reference
// and identifier); the last return field is whether or not an error
// occurred.
//
// Normalize whitespace before beginning. See note in importIssuer as to
// why we do this.
keyValue = strings.TrimSpace(keyValue) + "\n"
//
// Before we can import a known key, we first need to know if the key
// exists in storage already. This means iterating through all known
// keys and comparing their private value against this value.
knownKeys, err := sc.listKeys()
if err != nil {
return nil, false, err
}
// Get our public key from the current inbound key, to compare against all the other keys.
var pkForImportingKey crypto.PublicKey
if keyType == certutil.ManagedPrivateKey {
managedKeyUUID, err := extractManagedKeyId([]byte(keyValue))
if err != nil {
return nil, false, errutil.InternalError{Err: fmt.Sprintf("failed extracting managed key uuid from key: %v", err)}
}
pkForImportingKey, err = getManagedKeyPublicKey(sc.Context, sc.Backend, managedKeyUUID)
if err != nil {
return nil, false, err
}
} else {
pkForImportingKey, err = getPublicKeyFromBytes([]byte(keyValue))
if err != nil {
return nil, false, err
}
}
foundExistingKeyWithName := false
for _, identifier := range knownKeys {
existingKey, err := sc.fetchKeyById(identifier)
if err != nil {
return nil, false, err
}
areEqual, err := comparePublicKey(sc, existingKey, pkForImportingKey)
if err != nil {
return nil, false, err
}
if areEqual {
// Here, we don't need to stitch together the issuer entries,
// because the last run should've done that for us (or, when
// importing an issuer).
return existingKey, true, nil
}
// Allow us to find an existing matching key with a different name before erroring out
if keyName != "" && existingKey.Name == keyName {
foundExistingKeyWithName = true
}
}
// Another key with a different value is using the keyName so reject this request.
if foundExistingKeyWithName {
return nil, false, errutil.UserError{Err: fmt.Sprintf("an existing key is using the requested key name value: %s", keyName)}
}
// Haven't found a key, so we've gotta create it and write it into storage.
var result keyEntry
result.ID = genKeyId()
result.Name = keyName
result.PrivateKey = keyValue
result.PrivateKeyType = keyType
// Finally, we can write the key to storage.
if err := sc.writeKey(result); err != nil {
return nil, false, err
}
// Before we return below, we need to iterate over _all_ issuers and see if
// one of them has a missing KeyId link, and if so, point it back to
// ourselves. We fetch the list of issuers up front, even when don't need
// it, to give ourselves a better chance of succeeding below.
knownIssuers, err := sc.listIssuers()
if err != nil {
return nil, false, err
}
issuerDefaultSet, err := sc.isDefaultIssuerSet()
if err != nil {
return nil, false, err
}
// Now, for each issuer, try and compute the issuer<->key link if missing.
for _, identifier := range knownIssuers {
existingIssuer, err := sc.fetchIssuerById(identifier)
if err != nil {
return nil, false, err
}
// If the KeyID value is already present, we can skip it.
if len(existingIssuer.KeyID) > 0 {
continue
}
// Otherwise, compare public values. Note that there might be multiple
// certificates (e.g., cross-signed) with the same key.
cert, err := existingIssuer.GetCertificate()
if err != nil {
// Malformed issuer.
return nil, false, err
}
equal, err := certutil.ComparePublicKeysAndType(cert.PublicKey, pkForImportingKey)
if err != nil {
return nil, false, err
}
if equal {
// These public keys are equal, so this key entry must be the
// corresponding private key to this issuer; update it accordingly.
existingIssuer.KeyID = result.ID
if err := sc.writeIssuer(existingIssuer); err != nil {
return nil, false, err
}
// If there was no prior default value set and/or we had no known
// issuers when we started, set this issuer as default.
if !issuerDefaultSet {
err = sc.updateDefaultIssuerId(existingIssuer.ID)
if err != nil {
return nil, false, err
}
issuerDefaultSet = true
}
}
}
// If there was no prior default value set and/or we had no known
// keys when we started, set this key as default.
keyDefaultSet, err := sc.isDefaultKeySet()
if err != nil {
return nil, false, err
}
if len(knownKeys) == 0 || !keyDefaultSet {
if err = sc.updateDefaultKeyId(result.ID); err != nil {
return nil, false, err
}
}
// All done; return our new key reference.
return &result, false, nil
}
func (i issuerEntry) GetCertificate() (*x509.Certificate, error) {
cert, err := parseCertificateFromBytes([]byte(i.Certificate))
if err != nil {
return nil, errutil.InternalError{Err: fmt.Sprintf("unable to parse certificate from issuer: %s: %v", err.Error(), i.ID)}
}
return cert, nil
}
func (i issuerEntry) EnsureUsage(usage issuerUsage) error {
// We want to spit out a nice error message about missing usages.
if i.Usage.HasUsage(usage) {
return nil
}
issuerRef := fmt.Sprintf("id:%v", i.ID)
if len(i.Name) > 0 {
issuerRef = fmt.Sprintf("%v / name:%v", issuerRef, i.Name)
}
// These usages differ at some point in time. We've gotta find the first
// usage that differs and return a logical-sounding error message around
// that difference.
for name, candidate := range namedIssuerUsages {
if usage.HasUsage(candidate) && !i.Usage.HasUsage(candidate) {
return fmt.Errorf("requested usage %v for issuer [%v] but only had usage %v", name, issuerRef, i.Usage.Names())
}
}
// Maybe we have an unnamed usage that's requested.
return fmt.Errorf("unknown delta between usages: %v -> %v / for issuer [%v]", usage.Names(), i.Usage.Names(), issuerRef)
}
func (i issuerEntry) CanMaybeSignWithAlgo(algo x509.SignatureAlgorithm) error {
// Hack: Go isn't kind enough expose its lovely signatureAlgorithmDetails
// informational struct for our usage. However, we don't want to actually
// fetch the private key and attempt a signature with this algo (as we'll
// mint new, previously unsigned material in the process that could maybe
// be potentially abused if it leaks).
//
// So...
//
// ...we maintain our own mapping of cert.PKI<->sigAlgos. Notably, we
// exclude DSA support as the PKI engine has never supported DSA keys.
if algo == x509.UnknownSignatureAlgorithm {
// Special cased to indicate upgrade and letting Go automatically
// chose the correct value.
return nil
}
cert, err := i.GetCertificate()
if err != nil {
return fmt.Errorf("unable to parse issuer's potential signature algorithm types: %w", err)
}
switch cert.PublicKeyAlgorithm {
case x509.RSA:
switch algo {
case x509.SHA256WithRSA, x509.SHA384WithRSA, x509.SHA512WithRSA,
x509.SHA256WithRSAPSS, x509.SHA384WithRSAPSS,
x509.SHA512WithRSAPSS:
return nil
}
case x509.ECDSA:
switch algo {
case x509.ECDSAWithSHA256, x509.ECDSAWithSHA384, x509.ECDSAWithSHA512:
return nil
}
case x509.Ed25519:
switch algo {
case x509.PureEd25519:
return nil
}
}
return fmt.Errorf("unable to use issuer of type %v to sign with %v key type", cert.PublicKeyAlgorithm.String(), algo.String())
}
func (i issuerEntry) GetAIAURLs(sc *storageContext) (*certutil.URLEntries, error) {
// Default to the per-issuer AIA URLs.
entries := i.AIAURIs
// If none are set (either due to a nil entry or because no URLs have
// been provided), fall back to the global AIA URL config.
if entries == nil || (len(entries.IssuingCertificates) == 0 && len(entries.CRLDistributionPoints) == 0 && len(entries.OCSPServers) == 0) {
var err error
entries, err = getGlobalAIAURLs(sc.Context, sc.Storage)
if err != nil {
return nil, err
}
}
if entries == nil {
return &certutil.URLEntries{}, nil
}
return entries.toURLEntries(sc, i.ID)
}
func (sc *storageContext) listIssuers() ([]issuerID, error) {
strList, err := sc.Storage.List(sc.Context, issuerPrefix)
if err != nil {
return nil, err
}
issuerIds := make([]issuerID, 0, len(strList))
for _, entry := range strList {
issuerIds = append(issuerIds, issuerID(entry))
}
return issuerIds, nil
}
func (sc *storageContext) resolveKeyReference(reference string) (keyID, error) {
if reference == defaultRef {
// Handle fetching the default key.
config, err := sc.getKeysConfig()
if err != nil {
return keyID("config-error"), err
}
if len(config.DefaultKeyId) == 0 {
return KeyRefNotFound, fmt.Errorf("no default key currently configured")
}
return config.DefaultKeyId, nil
}
// Lookup by a direct get first to see if our reference is an ID, this is quick and cached.
if len(reference) == uuidLength {
entry, err := sc.Storage.Get(sc.Context, keyPrefix+reference)
if err != nil {
return keyID("key-read"), err
}
if entry != nil {
return keyID(reference), nil
}
}
// ... than to pull all keys from storage.
keys, err := sc.listKeys()
if err != nil {
return keyID("list-error"), err
}
for _, keyId := range keys {
key, err := sc.fetchKeyById(keyId)
if err != nil {
return keyID("key-read"), err
}
if key.Name == reference {
return key.ID, nil
}
}
// Otherwise, we must not have found the key.
return KeyRefNotFound, errutil.UserError{Err: fmt.Sprintf("unable to find PKI key for reference: %v", reference)}
}
// fetchIssuerById returns an issuerEntry based on issuerId, if none found an error is returned.
func (sc *storageContext) fetchIssuerById(issuerId issuerID) (*issuerEntry, error) {
if len(issuerId) == 0 {
return nil, errutil.InternalError{Err: "unable to fetch pki issuer: empty issuer identifier"}
}
entry, err := sc.Storage.Get(sc.Context, issuerPrefix+issuerId.String())
if err != nil {
return nil, errutil.InternalError{Err: fmt.Sprintf("unable to fetch pki issuer: %v", err)}
}
if entry == nil {
return nil, errutil.UserError{Err: fmt.Sprintf("pki issuer id %s does not exist", issuerId.String())}
}
var issuer issuerEntry
if err := entry.DecodeJSON(&issuer); err != nil {
return nil, errutil.InternalError{Err: fmt.Sprintf("unable to decode pki issuer with id %s: %v", issuerId.String(), err)}
}
return sc.upgradeIssuerIfRequired(&issuer), nil
}
func (sc *storageContext) upgradeIssuerIfRequired(issuer *issuerEntry) *issuerEntry {
// *NOTE*: Don't attempt to write out the issuer here as it may cause ErrReadOnly that will direct the
// request all the way up to the primary cluster which would be horrible for local cluster operations such
// as generating a leaf cert or a revoke.
// Also even though we could tell if we are the primary cluster's active node, we can't tell if we have the
// a full rw issuer lock, so it might not be safe to write.
if issuer.Version == latestIssuerVersion {
return issuer
}
if issuer.Version == 0 {
// Upgrade at this step requires interrogating the certificate itself;
// if this decode fails, it indicates internal problems and the
// request will subsequently fail elsewhere. However, decoding this
// certificate is mildly expensive, so we only do it in the event of
// a Version 0 certificate.
cert, err := issuer.GetCertificate()
if err != nil {
return issuer
}
hadCRL := issuer.Usage.HasUsage(CRLSigningUsage)
// Remove CRL signing usage if it exists on the issuer but doesn't
// exist in the KU of the x509 certificate.
if hadCRL && (cert.KeyUsage&x509.KeyUsageCRLSign) == 0 {
issuer.Usage.ToggleUsage(CRLSigningUsage)
}
// Handle our new OCSPSigning usage flag for earlier versions. If we
// had it (prior to removing it in this upgrade), we'll add the OCSP
// flag since EKUs don't matter.
if hadCRL && !issuer.Usage.HasUsage(OCSPSigningUsage) {
issuer.Usage.ToggleUsage(OCSPSigningUsage)
}
}
issuer.Version = latestIssuerVersion
return issuer
}
func (sc *storageContext) writeIssuer(issuer *issuerEntry) error {
issuerId := issuer.ID
if issuer.LastModified.IsZero() {
issuer.LastModified = time.Now().UTC()
}
json, err := logical.StorageEntryJSON(issuerPrefix+issuerId.String(), issuer)
if err != nil {
return err
}
return sc.Storage.Put(sc.Context, json)
}
func (sc *storageContext) deleteIssuer(id issuerID) (bool, error) {
config, err := sc.getIssuersConfig()
if err != nil {
return false, err
}
wasDefault := false
if config.DefaultIssuerId == id {
wasDefault = true
// Overwrite the fetched default issuer as we're going to remove this
// entry.
config.fetchedDefault = issuerID("")
config.DefaultIssuerId = issuerID("")
if err := sc.setIssuersConfig(config); err != nil {
return wasDefault, err
}
}
return wasDefault, sc.Storage.Delete(sc.Context, issuerPrefix+id.String())
}
func (sc *storageContext) importIssuer(certValue string, issuerName string) (*issuerEntry, bool, error) {
// importIssuers imports the specified PEM-format certificate (from
// certValue) into the new PKI storage format. The first return field is a
// reference to the new issuer; the second is whether or not the issuer
// already existed during import (in which case, *issuer points to the
// existing issuer reference and identifier); the last return field is
// whether or not an error occurred.
// Before we begin, we need to ensure the PEM formatted certificate looks
// good. Restricting to "just" `CERTIFICATE` entries is a little
// restrictive, as it could be a `X509 CERTIFICATE` entry or a custom
// value wrapping an actual DER cert. So validating the contents of the
// PEM header is out of the question (and validating the contents of the
// PEM block is left to our GetCertificate call below).
//
// However, we should trim all leading and trailing spaces and add a
// single new line. This allows callers to blindly concatenate PEM
// blobs from the API and get roughly what they'd expect.
//
// Discussed further in #11960 and RFC 7468.
certValue = strings.TrimSpace(certValue) + "\n"
// Extracting the certificate is necessary for two reasons: first, it lets
// us fetch the serial number; second, for the public key comparison with
// known keys.
issuerCert, err := parseCertificateFromBytes([]byte(certValue))
if err != nil {
return nil, false, err
}
// Ensure this certificate is a usable as a CA certificate.
if !issuerCert.BasicConstraintsValid || !issuerCert.IsCA {
return nil, false, errutil.UserError{Err: "Refusing to import non-CA certificate"}
}
// Ensure this certificate has a parsed public key. Otherwise, we've
// likely been given a bad certificate.
if issuerCert.PublicKeyAlgorithm == x509.UnknownPublicKeyAlgorithm || issuerCert.PublicKey == nil {
return nil, false, errutil.UserError{Err: "Refusing to import CA certificate with empty PublicKey. This usually means the SubjectPublicKeyInfo field has an OID not recognized by Go, such as 1.2.840.113549.1.1.10 for rsaPSS."}
}
// Before we can import a known issuer, we first need to know if the issuer
// exists in storage already. This means iterating through all known
// issuers and comparing their private value against this value.
knownIssuers, err := sc.listIssuers()
if err != nil {
return nil, false, err
}
foundExistingIssuerWithName := false
for _, identifier := range knownIssuers {
existingIssuer, err := sc.fetchIssuerById(identifier)
if err != nil {
return nil, false, err
}
existingIssuerCert, err := existingIssuer.GetCertificate()
if err != nil {
return nil, false, err
}
if areCertificatesEqual(existingIssuerCert, issuerCert) {
// Here, we don't need to stitch together the key entries,
// because the last run should've done that for us (or, when
// importing a key).
return existingIssuer, true, nil
}
// Allow us to find an existing matching issuer with a different name before erroring out
if issuerName != "" && existingIssuer.Name == issuerName {
foundExistingIssuerWithName = true
}
}
if foundExistingIssuerWithName {
return nil, false, errutil.UserError{Err: fmt.Sprintf("another issuer is using the requested name: %s", issuerName)}
}
// Haven't found an issuer, so we've gotta create it and write it into
// storage.
var result issuerEntry
result.ID = genIssuerId()
result.Name = issuerName
result.Certificate = certValue
result.LeafNotAfterBehavior = certutil.ErrNotAfterBehavior
result.Usage.ToggleUsage(AllIssuerUsages)
result.Version = latestIssuerVersion
// If we lack relevant bits for CRL, prohibit it from being set
// on the usage side.
if (issuerCert.KeyUsage&x509.KeyUsageCRLSign) == 0 && result.Usage.HasUsage(CRLSigningUsage) {
result.Usage.ToggleUsage(CRLSigningUsage)
}
// We shouldn't add CSRs or multiple certificates in this
countCertificates := strings.Count(result.Certificate, "-BEGIN ")
if countCertificates != 1 {
return nil, false, fmt.Errorf("bad issuer: potentially multiple PEM blobs in one certificate storage entry:\n%v", result.Certificate)
}
result.SerialNumber = serialFromCert(issuerCert)
// Before we return below, we need to iterate over _all_ keys and see if
// one of them a public key matching this certificate, and if so, update our
// link accordingly. We fetch the list of keys up front, even may not need
// it, to give ourselves a better chance of succeeding below.
knownKeys, err := sc.listKeys()
if err != nil {
return nil, false, err
}
// Now, for each key, try and compute the issuer<->key link. We delay
// writing issuer to storage as we won't need to update the key, only
// the issuer.
for _, identifier := range knownKeys {
existingKey, err := sc.fetchKeyById(identifier)
if err != nil {
return nil, false, err
}
equal, err := comparePublicKey(sc, existingKey, issuerCert.PublicKey)
if err != nil {
return nil, false, err
}
if equal {
result.KeyID = existingKey.ID
// Here, there's exactly one stored key with the same public key
// as us, per guarantees in importKey; as we're importing an
// issuer, there's no other keys or issuers we'd need to read or
// update, so exit.
break
}
}
// Finally, rebuild the chains. In this process, because the provided
// reference issuer is non-nil, we'll save this issuer to storage.
if err := sc.rebuildIssuersChains(&result); err != nil {
return nil, false, err
}
// If there was no prior default value set and/or we had no known
// issuers when we started, set this issuer as default.
issuerDefaultSet, err := sc.isDefaultIssuerSet()
if err != nil {
return nil, false, err
}
if (len(knownIssuers) == 0 || !issuerDefaultSet) && len(result.KeyID) != 0 {
if err = sc.updateDefaultIssuerId(result.ID); err != nil {
return nil, false, err
}
}
// All done; return our new key reference.
return &result, false, nil
}
func areCertificatesEqual(cert1 *x509.Certificate, cert2 *x509.Certificate) bool {
return bytes.Equal(cert1.Raw, cert2.Raw)
}
func (sc *storageContext) _cleanupInternalCRLMapping(mapping *internalCRLConfigEntry, path string) error {
// Track which CRL IDs are presently referred to by issuers; any other CRL
// IDs are subject to cleanup.
//
// Unused IDs both need to be removed from this map (cleaning up the size
// of this storage entry) but also the full CRLs removed from disk.
presentMap := make(map[crlID]bool)
for _, id := range mapping.IssuerIDCRLMap {
presentMap[id] = true
}
// Identify which CRL IDs exist and are candidates for removal;
// theoretically these three maps should be in sync, but were added
// at different times.
toRemove := make(map[crlID]bool)
for id := range mapping.CRLNumberMap {
if !presentMap[id] {
toRemove[id] = true
}
}
for id := range mapping.LastCompleteNumberMap {
if !presentMap[id] {
toRemove[id] = true
}
}
for id := range mapping.CRLExpirationMap {
if !presentMap[id] {
toRemove[id] = true
}
}
// Depending on which path we're writing this config to, we need to
// remove CRLs from the relevant folder too.
isLocal := path == storageLocalCRLConfig
baseCRLPath := "crls/"
if !isLocal {
baseCRLPath = "unified-crls/"
}
for id := range toRemove {
// Clean up space in this mapping...
delete(mapping.CRLNumberMap, id)
delete(mapping.LastCompleteNumberMap, id)
delete(mapping.CRLExpirationMap, id)
// And clean up space on disk from the fat CRL mapping.
crlPath := baseCRLPath + string(id)
deltaCRLPath := crlPath + "-delta"
if err := sc.Storage.Delete(sc.Context, crlPath); err != nil {
return fmt.Errorf("failed to delete unreferenced CRL %v: %w", id, err)
}
if err := sc.Storage.Delete(sc.Context, deltaCRLPath); err != nil {
return fmt.Errorf("failed to delete unreferenced delta CRL %v: %w", id, err)
}
}
// Lastly, some CRLs could've been partially removed from the map but
// not from disk. Check to see if we have any dangling CRLs and remove
// them too.
list, err := sc.Storage.List(sc.Context, baseCRLPath)
if err != nil {
return fmt.Errorf("failed listing all CRLs: %w", err)
}
for _, crl := range list {
if crl == "config" || strings.HasSuffix(crl, "/") {
continue
}
if presentMap[crlID(crl)] {
continue
}
if err := sc.Storage.Delete(sc.Context, baseCRLPath+"/"+crl); err != nil {
return fmt.Errorf("failed cleaning up orphaned CRL %v: %w", crl, err)
}
}
return nil
}
func (sc *storageContext) _setInternalCRLConfig(mapping *internalCRLConfigEntry, path string) error {
if err := sc._cleanupInternalCRLMapping(mapping, path); err != nil {
return fmt.Errorf("failed to clean up internal CRL mapping: %w", err)