-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
crl_util.go
2212 lines (1905 loc) · 80.2 KB
/
crl_util.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package pki
import (
"bytes"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"fmt"
"math/big"
"strings"
"sync"
"time"
"github.com/hashicorp/go-secure-stdlib/parseutil"
"github.com/hashicorp/vault/sdk/helper/certutil"
"github.com/hashicorp/vault/sdk/helper/consts"
"github.com/hashicorp/vault/sdk/helper/errutil"
"github.com/hashicorp/vault/sdk/logical"
atomic2 "go.uber.org/atomic"
)
const (
revokedPath = "revoked/"
crossRevocationPrefix = "cross-revocation-queue/"
crossRevocationPath = crossRevocationPrefix + "{{clusterId}}/"
deltaWALLastBuildSerialName = "last-build-serial"
deltaWALLastRevokedSerialName = "last-revoked-serial"
localDeltaWALPath = "delta-wal/"
localDeltaWALLastBuildSerial = localDeltaWALPath + deltaWALLastBuildSerialName
localDeltaWALLastRevokedSerial = localDeltaWALPath + deltaWALLastRevokedSerialName
unifiedDeltaWALPrefix = "unified-delta-wal/"
unifiedDeltaWALPath = "unified-delta-wal/{{clusterId}}/"
unifiedDeltaWALLastBuildSerial = unifiedDeltaWALPath + deltaWALLastBuildSerialName
unifiedDeltaWALLastRevokedSerial = unifiedDeltaWALPath + deltaWALLastRevokedSerialName
)
type revocationInfo struct {
CertificateBytes []byte `json:"certificate_bytes"`
RevocationTime int64 `json:"revocation_time"`
RevocationTimeUTC time.Time `json:"revocation_time_utc"`
CertificateIssuer issuerID `json:"issuer_id"`
}
type revocationRequest struct {
RequestedAt time.Time `json:"requested_at"`
}
type revocationConfirmed struct {
RevokedAt string `json:"revoked_at"`
Source string `json:"source"`
}
type revocationQueueEntry struct {
Cluster string
Serial string
}
type (
// Placeholder in case of migrations needing more data. Currently
// we use the path name to store the serial number that was revoked.
deltaWALInfo struct{}
lastWALInfo struct {
// Info to write about the last WAL entry. This is the serial number
// of the last revoked certificate.
//
// We write this below in revokedCert(...) and read it in
// rebuildDeltaCRLsIfForced(...).
Serial string `json:"serial"`
}
lastDeltaInfo struct {
// Info to write about the last built delta CRL. This is the serial
// number of the last revoked certificate that we saw prior to delta
// CRL building.
//
// We write this below in buildAnyCRLs(...) and read it in
// rebuildDeltaCRLsIfForced(...).
Serial string `json:"serial"`
}
)
// crlBuilder is gatekeeper for controlling various read/write operations to the storage of the CRL.
// The extra complexity arises from secondary performance clusters seeing various writes to its storage
// without the actual API calls. During the storage invalidation process, we do not have the required state
// to actually rebuild the CRLs, so we need to schedule it in a deferred fashion. This allows either
// read or write calls to perform the operation if required, or have the flag reset upon a write operation
//
// The CRL builder also tracks the revocation configuration.
type crlBuilder struct {
_builder sync.Mutex
forceRebuild *atomic2.Bool
canRebuild bool
lastDeltaRebuildCheck time.Time
_config sync.RWMutex
dirty *atomic2.Bool
config crlConfig
haveInitializedConfig bool
// Whether to invalidate our LastModifiedTime due to write on the
// global issuance config.
invalidate *atomic2.Bool
// Global revocation queue entries get accepted by the invalidate func
// and passed to the crlBuilder for processing.
haveInitializedQueue *atomic2.Bool
revQueue *revocationQueue
removalQueue *revocationQueue
crossQueue *revocationQueue
}
const (
_ignoreForceFlag = true
_enforceForceFlag = false
)
func newCRLBuilder(canRebuild bool) *crlBuilder {
return &crlBuilder{
forceRebuild: atomic2.NewBool(false),
canRebuild: canRebuild,
// Set the last delta rebuild window to now, delaying the first delta
// rebuild by the first rebuild period to give us some time on startup
// to stabilize.
lastDeltaRebuildCheck: time.Now(),
dirty: atomic2.NewBool(true),
config: defaultCrlConfig,
invalidate: atomic2.NewBool(false),
haveInitializedQueue: atomic2.NewBool(false),
revQueue: newRevocationQueue(),
removalQueue: newRevocationQueue(),
crossQueue: newRevocationQueue(),
}
}
func (cb *crlBuilder) markConfigDirty() {
cb.dirty.Store(true)
}
func (cb *crlBuilder) reloadConfigIfRequired(sc *storageContext) error {
if cb.dirty.Load() {
// Acquire a write lock.
cb._config.Lock()
defer cb._config.Unlock()
if !cb.dirty.Load() {
// Someone else might've been reloading the config; no need
// to do it twice.
return nil
}
config, err := sc.getRevocationConfig()
if err != nil {
return err
}
previousConfig := cb.config
// Set the default config if none was returned to us.
if config != nil {
cb.config = *config
} else {
cb.config = defaultCrlConfig
}
// Updated the config; unset dirty.
cb.dirty.Store(false)
triggerChangeNotification := true
if !cb.haveInitializedConfig {
cb.haveInitializedConfig = true
triggerChangeNotification = false // do not trigger on the initial loading of configuration.
}
// Certain things need to be triggered on all server types when crlConfig is loaded.
if triggerChangeNotification {
cb.notifyOnConfigChange(sc, previousConfig, cb.config)
}
}
return nil
}
func (cb *crlBuilder) notifyOnConfigChange(sc *storageContext, priorConfig crlConfig, newConfig crlConfig) {
// If you need to hook into a CRL configuration change across different server types
// such as primary clusters as well as performance replicas, it is easier to do here than
// in two places (API layer and in invalidateFunc)
if priorConfig.UnifiedCRL != newConfig.UnifiedCRL && newConfig.UnifiedCRL {
sc.Backend.unifiedTransferStatus.forceRun()
}
if priorConfig.UseGlobalQueue != newConfig.UseGlobalQueue && newConfig.UseGlobalQueue {
cb.haveInitializedQueue.Store(false)
}
}
func (cb *crlBuilder) getConfigWithUpdate(sc *storageContext) (*crlConfig, error) {
// Config may mutate immediately after accessing, but will be freshly
// fetched if necessary.
if err := cb.reloadConfigIfRequired(sc); err != nil {
return nil, err
}
cb._config.RLock()
defer cb._config.RUnlock()
configCopy := cb.config
return &configCopy, nil
}
func (cb *crlBuilder) checkForAutoRebuild(sc *storageContext) error {
cfg, err := cb.getConfigWithUpdate(sc)
if err != nil {
return err
}
if cfg.Disable || !cfg.AutoRebuild || cb.forceRebuild.Load() {
// Not enabled, not on auto-rebuilder, or we're already scheduled to
// rebuild so there's no point to interrogate CRL values...
return nil
}
// Auto-Rebuild is enabled. We need to check each issuer's CRL and see
// if its about to expire. If it is, we've gotta rebuild it (and well,
// every other CRL since we don't have a fine-toothed rebuilder).
//
// We store a list of all (unique) CRLs in the cluster-local CRL
// configuration along with their expiration dates.
internalCRLConfig, err := sc.getLocalCRLConfig()
if err != nil {
return fmt.Errorf("error checking for auto-rebuild status: unable to fetch cluster-local CRL configuration: %w", err)
}
// If there's no config, assume we've gotta rebuild it to get this
// information.
if internalCRLConfig == nil {
cb.forceRebuild.Store(true)
return nil
}
// If the map is empty, assume we need to upgrade and schedule a
// rebuild.
if len(internalCRLConfig.CRLExpirationMap) == 0 {
cb.forceRebuild.Store(true)
return nil
}
// Otherwise, check CRL's expirations and see if its zero or within
// the grace period and act accordingly.
now := time.Now()
period, err := parseutil.ParseDurationSecond(cfg.AutoRebuildGracePeriod)
if err != nil {
// This may occur if the duration is empty; in that case
// assume the default. The default should be valid and shouldn't
// error.
defaultPeriod, defaultErr := parseutil.ParseDurationSecond(defaultCrlConfig.AutoRebuildGracePeriod)
if defaultErr != nil {
return fmt.Errorf("error checking for auto-rebuild status: unable to parse duration from both config's grace period (%v) and default grace period (%v):\n- config: %v\n- default: %w\n", cfg.AutoRebuildGracePeriod, defaultCrlConfig.AutoRebuildGracePeriod, err, defaultErr)
}
period = defaultPeriod
}
for _, value := range internalCRLConfig.CRLExpirationMap {
if value.IsZero() || now.After(value.Add(-1*period)) {
cb.forceRebuild.Store(true)
return nil
}
}
return nil
}
// Mark the internal LastModifiedTime tracker invalid.
func (cb *crlBuilder) invalidateCRLBuildTime() {
cb.invalidate.Store(true)
}
// Update the config to mark the modified CRL. See note in
// updateDefaultIssuerId about why this is necessary.
func (cb *crlBuilder) flushCRLBuildTimeInvalidation(sc *storageContext) error {
if cb.invalidate.CAS(true, false) {
// Flush out our invalidation.
cfg, err := sc.getLocalCRLConfig()
if err != nil {
cb.invalidate.Store(true)
return fmt.Errorf("unable to update local CRL config's modification time: error fetching: %w", err)
}
cfg.LastModified = time.Now().UTC()
cfg.DeltaLastModified = time.Now().UTC()
err = sc.setLocalCRLConfig(cfg)
if err != nil {
cb.invalidate.Store(true)
return fmt.Errorf("unable to update local CRL config's modification time: error persisting: %w", err)
}
}
return nil
}
// rebuildIfForced is to be called by readers or periodic functions that might need to trigger
// a refresh of the CRL before the read occurs.
func (cb *crlBuilder) rebuildIfForced(sc *storageContext) ([]string, error) {
if cb.forceRebuild.Load() {
return cb._doRebuild(sc, true, _enforceForceFlag)
}
return nil, nil
}
// rebuild is to be called by various write apis that know the CRL is to be updated and can be now.
func (cb *crlBuilder) rebuild(sc *storageContext, forceNew bool) ([]string, error) {
return cb._doRebuild(sc, forceNew, _ignoreForceFlag)
}
// requestRebuildIfActiveNode will schedule a rebuild of the CRL from the next read or write api call assuming we are the active node of a cluster
func (cb *crlBuilder) requestRebuildIfActiveNode(b *backend) {
// Only schedule us on active nodes, as the active node is the only node that can rebuild/write the CRL.
// Note 1: The CRL is cluster specific, so this does need to run on the active node of a performance secondary cluster.
// Note 2: This is called by the storage invalidation function, so it should not block.
if !cb.canRebuild {
b.Logger().Debug("Ignoring request to schedule a CRL rebuild, not on active node.")
return
}
b.Logger().Info("Scheduling PKI CRL rebuild.")
// Set the flag to 1, we don't care if we aren't the ones that actually swap it to 1.
cb.forceRebuild.Store(true)
}
func (cb *crlBuilder) _doRebuild(sc *storageContext, forceNew bool, ignoreForceFlag bool) ([]string, error) {
cb._builder.Lock()
defer cb._builder.Unlock()
// Re-read the lock in case someone beat us to the punch between the previous load op.
forceBuildFlag := cb.forceRebuild.Load()
if forceBuildFlag || ignoreForceFlag {
// Reset our original flag back to 0 before we start the rebuilding. This may lead to another round of
// CRL building, but we want to avoid the race condition caused by clearing the flag after we completed (An
// update/revocation occurred attempting to set the flag, after we listed the certs but before we wrote
// the CRL, so we missed the update and cleared the flag.)
cb.forceRebuild.Store(false)
// if forceRebuild was requested, that should force a complete rebuild even if requested not too by forceNew
myForceNew := forceBuildFlag || forceNew
return buildCRLs(sc, myForceNew)
}
return nil, nil
}
func (cb *crlBuilder) _getPresentDeltaWALForClearing(sc *storageContext, path string) ([]string, error) {
// Clearing of the delta WAL occurs after a new complete CRL has been built.
walSerials, err := sc.Storage.List(sc.Context, path)
if err != nil {
return nil, fmt.Errorf("error fetching list of delta WAL certificates to clear: %w", err)
}
// We _should_ remove the special WAL entries here, but we don't really
// want to traverse the list again (and also below in clearDeltaWAL). So
// trust the latter does the right thing.
return walSerials, nil
}
func (cb *crlBuilder) getPresentLocalDeltaWALForClearing(sc *storageContext) ([]string, error) {
return cb._getPresentDeltaWALForClearing(sc, localDeltaWALPath)
}
func (cb *crlBuilder) getPresentUnifiedDeltaWALForClearing(sc *storageContext) ([]string, error) {
walClusters, err := sc.Storage.List(sc.Context, unifiedDeltaWALPrefix)
if err != nil {
return nil, fmt.Errorf("error fetching list of clusters with delta WAL entries: %w", err)
}
var allPaths []string
for index, cluster := range walClusters {
prefix := unifiedDeltaWALPrefix + cluster
clusterPaths, err := cb._getPresentDeltaWALForClearing(sc, prefix)
if err != nil {
return nil, fmt.Errorf("error fetching delta WAL entries for cluster (%v / %v): %w", index, cluster, err)
}
// Here, we don't want to include the unifiedDeltaWALPrefix because
// clearUnifiedDeltaWAL handles that for us. Instead, just include
// the cluster identifier.
for _, clusterPath := range clusterPaths {
allPaths = append(allPaths, cluster+clusterPath)
}
}
return allPaths, nil
}
func (cb *crlBuilder) _clearDeltaWAL(sc *storageContext, walSerials []string, path string) error {
// Clearing of the delta WAL occurs after a new complete CRL has been built.
for _, serial := range walSerials {
// Don't remove our special entries!
if strings.HasSuffix(serial, deltaWALLastBuildSerialName) || strings.HasSuffix(serial, deltaWALLastRevokedSerialName) {
continue
}
if err := sc.Storage.Delete(sc.Context, path+serial); err != nil {
return fmt.Errorf("error clearing delta WAL certificate: %w", err)
}
}
return nil
}
func (cb *crlBuilder) clearLocalDeltaWAL(sc *storageContext, walSerials []string) error {
return cb._clearDeltaWAL(sc, walSerials, localDeltaWALPath)
}
func (cb *crlBuilder) clearUnifiedDeltaWAL(sc *storageContext, walSerials []string) error {
return cb._clearDeltaWAL(sc, walSerials, unifiedDeltaWALPrefix)
}
func (cb *crlBuilder) rebuildDeltaCRLsIfForced(sc *storageContext, override bool) ([]string, error) {
// Delta CRLs use the same expiry duration as the complete CRL. Because
// we always rebuild the complete CRL and then the delta CRL, we can
// be assured that the delta CRL always expires after a complete CRL,
// and that rebuilding the complete CRL will trigger a fresh delta CRL
// build of its own.
//
// This guarantee means we can avoid checking delta CRL expiry. Thus,
// we only need to rebuild the delta CRL when we have new revocations,
// within our time window for updating it.
cfg, err := cb.getConfigWithUpdate(sc)
if err != nil {
return nil, err
}
if !cfg.EnableDelta {
// We explicitly do not update the last check time here, as we
// want to persist the last rebuild window if it hasn't been set.
return nil, nil
}
deltaRebuildDuration, err := parseutil.ParseDurationSecond(cfg.DeltaRebuildInterval)
if err != nil {
return nil, err
}
// Acquire CRL building locks before we get too much further.
cb._builder.Lock()
defer cb._builder.Unlock()
// Last is setup during newCRLBuilder(...), so we don't need to deal with
// a zero condition.
now := time.Now()
last := cb.lastDeltaRebuildCheck
nextRebuildCheck := last.Add(deltaRebuildDuration)
if !override && now.Before(nextRebuildCheck) {
// If we're still before the time of our next rebuild check, we can
// safely return here even if we have certs. We'll wait for a bit,
// retrigger this check, and then do the rebuild.
return nil, nil
}
// Update our check time. If we bail out below (due to storage errors
// or whatever), we'll delay the next CRL check (hopefully allowing
// things to stabilize). Otherwise, we might not build a new Delta CRL
// until our next complete CRL build.
cb.lastDeltaRebuildCheck = now
rebuildLocal, err := cb._shouldRebuildLocalCRLs(sc, override)
if err != nil {
return nil, fmt.Errorf("error determining if local CRLs should be rebuilt: %w", err)
}
rebuildUnified, err := cb._shouldRebuildUnifiedCRLs(sc, override)
if err != nil {
return nil, fmt.Errorf("error determining if unified CRLs should be rebuilt: %w", err)
}
if !rebuildLocal && !rebuildUnified {
return nil, nil
}
// Finally, we must've needed to do the rebuild. Execute!
return cb.rebuildDeltaCRLsHoldingLock(sc, false)
}
func (cb *crlBuilder) _shouldRebuildLocalCRLs(sc *storageContext, override bool) (bool, error) {
// Fetch two storage entries to see if we actually need to do this
// rebuild, given we're within the window.
lastWALEntry, err := sc.Storage.Get(sc.Context, localDeltaWALLastRevokedSerial)
if err != nil || !override && (lastWALEntry == nil || lastWALEntry.Value == nil) {
// If this entry does not exist, we don't need to rebuild the
// delta WAL due to the expiration assumption above. There must
// not have been any new revocations. Since err should be nil
// in this case, we can safely return it.
return false, err
}
lastBuildEntry, err := sc.Storage.Get(sc.Context, localDeltaWALLastBuildSerial)
if err != nil {
return false, err
}
if !override && lastBuildEntry != nil && lastBuildEntry.Value != nil {
// If the last build entry doesn't exist, we still want to build a
// new delta WAL, since this could be our very first time doing so.
//
// Otherwise, here, now that we know it exists, we want to check this
// value against the other value. Since we previously guarded the WAL
// entry being non-empty, we're good to decode everything within this
// guard.
var walInfo lastWALInfo
if err := lastWALEntry.DecodeJSON(&walInfo); err != nil {
return false, err
}
var deltaInfo lastDeltaInfo
if err := lastBuildEntry.DecodeJSON(&deltaInfo); err != nil {
return false, err
}
// Here, everything decoded properly and we know that no new certs
// have been revoked since we built this last delta CRL. We can exit
// without rebuilding then.
if walInfo.Serial == deltaInfo.Serial {
return false, nil
}
}
return true, nil
}
func (cb *crlBuilder) _shouldRebuildUnifiedCRLs(sc *storageContext, override bool) (bool, error) {
// Unified CRL can only be built by the main cluster.
b := sc.Backend
if b.System().ReplicationState().HasState(consts.ReplicationDRSecondary|consts.ReplicationPerformanceStandby) ||
(!b.System().LocalMount() && b.System().ReplicationState().HasState(consts.ReplicationPerformanceSecondary)) {
return false, nil
}
// If we're overriding whether we should build Delta CRLs, always return
// true, even if storage errors might've happen.
if override {
return true, nil
}
// Fetch two storage entries to see if we actually need to do this
// rebuild, given we're within the window. We need to fetch these
// two entries per cluster.
clusters, err := sc.Storage.List(sc.Context, unifiedDeltaWALPrefix)
if err != nil {
return false, fmt.Errorf("failed to get the list of clusters having written Delta WALs: %w", err)
}
// If any cluster tells us to rebuild, we should rebuild.
shouldRebuild := false
for index, cluster := range clusters {
prefix := unifiedDeltaWALPrefix + cluster
clusterUnifiedLastRevokedWALEntry := prefix + deltaWALLastRevokedSerialName
clusterUnifiedLastBuiltWALEntry := prefix + deltaWALLastBuildSerialName
lastWALEntry, err := sc.Storage.Get(sc.Context, clusterUnifiedLastRevokedWALEntry)
if err != nil {
return false, fmt.Errorf("failed fetching last revoked WAL entry for cluster (%v / %v): %w", index, cluster, err)
}
if lastWALEntry == nil || lastWALEntry.Value == nil {
continue
}
lastBuildEntry, err := sc.Storage.Get(sc.Context, clusterUnifiedLastBuiltWALEntry)
if err != nil {
return false, fmt.Errorf("failed fetching last built CRL WAL entry for cluster (%v / %v): %w", index, cluster, err)
}
if lastBuildEntry == nil || lastBuildEntry.Value == nil {
// If the last build entry doesn't exist, we still want to build a
// new delta WAL, since this could be our very first time doing so.
shouldRebuild = true
break
}
// Otherwise, here, now that we know it exists, we want to check this
// value against the other value. Since we previously guarded the WAL
// entry being non-empty, we're good to decode everything within this
// guard.
var walInfo lastWALInfo
if err := lastWALEntry.DecodeJSON(&walInfo); err != nil {
return false, fmt.Errorf("failed decoding last revoked WAL entry for cluster (%v / %v): %w", index, cluster, err)
}
var deltaInfo lastDeltaInfo
if err := lastBuildEntry.DecodeJSON(&deltaInfo); err != nil {
return false, fmt.Errorf("failed decoding last built CRL WAL entry for cluster (%v / %v): %w", index, cluster, err)
}
if walInfo.Serial != deltaInfo.Serial {
shouldRebuild = true
break
}
}
// No errors occurred, so return the result.
return shouldRebuild, nil
}
func (cb *crlBuilder) rebuildDeltaCRLs(sc *storageContext, forceNew bool) ([]string, error) {
cb._builder.Lock()
defer cb._builder.Unlock()
return cb.rebuildDeltaCRLsHoldingLock(sc, forceNew)
}
func (cb *crlBuilder) rebuildDeltaCRLsHoldingLock(sc *storageContext, forceNew bool) ([]string, error) {
return buildAnyCRLs(sc, forceNew, true /* building delta */)
}
func (cb *crlBuilder) addCertForRevocationCheck(cluster, serial string) {
entry := &revocationQueueEntry{
Cluster: cluster,
Serial: serial,
}
cb.revQueue.Add(entry)
}
func (cb *crlBuilder) addCertForRevocationRemoval(cluster, serial string) {
entry := &revocationQueueEntry{
Cluster: cluster,
Serial: serial,
}
cb.removalQueue.Add(entry)
}
func (cb *crlBuilder) addCertFromCrossRevocation(cluster, serial string) {
entry := &revocationQueueEntry{
Cluster: cluster,
Serial: serial,
}
cb.crossQueue.Add(entry)
}
func (cb *crlBuilder) maybeGatherQueueForFirstProcess(sc *storageContext, isNotPerfPrimary bool) error {
// Assume holding lock.
if cb.haveInitializedQueue.Load() {
return nil
}
sc.Backend.Logger().Debug(fmt.Sprintf("gathering first time existing revocations"))
clusters, err := sc.Storage.List(sc.Context, crossRevocationPrefix)
if err != nil {
return fmt.Errorf("failed to list cross-cluster revocation queue participating clusters: %w", err)
}
sc.Backend.Logger().Debug(fmt.Sprintf("found %v clusters: %v", len(clusters), clusters))
for cIndex, cluster := range clusters {
cluster = cluster[0 : len(cluster)-1]
cPath := crossRevocationPrefix + cluster + "/"
serials, err := sc.Storage.List(sc.Context, cPath)
if err != nil {
return fmt.Errorf("failed to list cross-cluster revocation queue entries for cluster %v (%v): %w", cluster, cIndex, err)
}
sc.Backend.Logger().Debug(fmt.Sprintf("found %v serials for cluster %v: %v", len(serials), cluster, serials))
for _, serial := range serials {
if serial[len(serial)-1] == '/' {
serial = serial[0 : len(serial)-1]
}
ePath := cPath + serial
eConfirmPath := ePath + "/confirmed"
removalEntry, err := sc.Storage.Get(sc.Context, eConfirmPath)
entry := &revocationQueueEntry{
Cluster: cluster,
Serial: serial,
}
// No removal entry yet; add to regular queue. Otherwise, slate it
// for removal if we're a perfPrimary.
if err != nil || removalEntry == nil {
cb.revQueue.Add(entry)
} else if !isNotPerfPrimary {
cb.removalQueue.Add(entry)
} // Else, this is a confirmation but we're on a perf secondary so ignore it.
// Overwrite the error; we don't really care about its contents
// at this step.
err = nil
}
}
return nil
}
func (cb *crlBuilder) processRevocationQueue(sc *storageContext) error {
sc.Backend.Logger().Debug(fmt.Sprintf("starting to process revocation requests"))
isNotPerfPrimary := sc.Backend.System().ReplicationState().HasState(consts.ReplicationDRSecondary|consts.ReplicationPerformanceStandby) ||
(!sc.Backend.System().LocalMount() && sc.Backend.System().ReplicationState().HasState(consts.ReplicationPerformanceSecondary))
if err := cb.maybeGatherQueueForFirstProcess(sc, isNotPerfPrimary); err != nil {
return fmt.Errorf("failed to gather first queue: %w", err)
}
revQueue := cb.revQueue.Iterate()
removalQueue := cb.removalQueue.Iterate()
sc.Backend.Logger().Debug(fmt.Sprintf("gathered %v revocations and %v confirmation entries", len(revQueue), len(removalQueue)))
crlConfig, err := cb.getConfigWithUpdate(sc)
if err != nil {
return err
}
ourClusterId, err := sc.Backend.System().ClusterID(sc.Context)
if err != nil {
return fmt.Errorf("unable to fetch clusterID to ignore local revocation entries: %w", err)
}
for _, req := range revQueue {
// Regardless of whether we're on the perf primary or a secondary
// cluster, we can safely ignore revocation requests originating
// from our node, because we've already checked them once (when
// they were created).
if ourClusterId != "" && ourClusterId == req.Cluster {
continue
}
// Fetch the revocation entry to ensure it exists.
rPath := crossRevocationPrefix + req.Cluster + "/" + req.Serial
entry, err := sc.Storage.Get(sc.Context, rPath)
if err != nil {
return fmt.Errorf("failed to read cross-cluster revocation queue entry: %w", err)
}
if entry == nil {
// Skipping this entry; it was likely an incorrect invalidation
// caused by the primary cluster removing the confirmation.
cb.revQueue.Remove(req)
continue
}
resp, err := tryRevokeCertBySerial(sc, crlConfig, req.Serial)
if err == nil && resp != nil && !resp.IsError() && resp.Data != nil && resp.Data["state"].(string) == "revoked" {
if isNotPerfPrimary {
// Write a revocation queue removal entry.
confirmed := revocationConfirmed{
RevokedAt: resp.Data["revocation_time_rfc3339"].(string),
Source: req.Cluster,
}
path := crossRevocationPath + req.Serial + "/confirmed"
confirmedEntry, err := logical.StorageEntryJSON(path, confirmed)
if err != nil {
return fmt.Errorf("failed to create storage entry for cross-cluster revocation confirmed response: %w", err)
}
if err := sc.Storage.Put(sc.Context, confirmedEntry); err != nil {
return fmt.Errorf("error persisting cross-cluster revocation confirmation: %w", err)
}
} else {
// Since we're the active node of the primary cluster, go ahead
// and just remove it.
path := crossRevocationPrefix + req.Cluster + "/" + req.Serial
if err := sc.Storage.Delete(sc.Context, path); err != nil {
return fmt.Errorf("failed to delete processed revocation request: %w", err)
}
}
} else if err != nil {
// Because we fake being from a lease, we get the guarantee that
// err == nil == resp if the cert was already revoked; this means
// this err should actually be fatal.
return err
}
cb.revQueue.Remove(req)
}
if isNotPerfPrimary {
sc.Backend.Logger().Debug(fmt.Sprintf("not on perf primary so ignoring any revocation confirmations"))
// See note in pki/backend.go; this should be empty.
cb.removalQueue.RemoveAll()
cb.haveInitializedQueue.Store(true)
return nil
}
clusters, err := sc.Storage.List(sc.Context, crossRevocationPrefix)
if err != nil {
return err
}
for _, entry := range removalQueue {
// First remove the revocation request.
for cIndex, cluster := range clusters {
eEntry := crossRevocationPrefix + cluster + entry.Serial
if err := sc.Storage.Delete(sc.Context, eEntry); err != nil {
return fmt.Errorf("failed to delete potential cross-cluster revocation entry for cluster %v (%v) and serial %v: %w", cluster, cIndex, entry.Serial, err)
}
}
// Then remove the confirmation.
if err := sc.Storage.Delete(sc.Context, crossRevocationPrefix+entry.Cluster+"/"+entry.Serial+"/confirmed"); err != nil {
return fmt.Errorf("failed to delete cross-cluster revocation confirmation entry for cluster %v and serial %v: %w", entry.Cluster, entry.Serial, err)
}
cb.removalQueue.Remove(entry)
}
cb.haveInitializedQueue.Store(true)
return nil
}
func (cb *crlBuilder) processCrossClusterRevocations(sc *storageContext) error {
sc.Backend.Logger().Debug(fmt.Sprintf("starting to process unified revocations"))
crlConfig, err := cb.getConfigWithUpdate(sc)
if err != nil {
return err
}
if !crlConfig.UnifiedCRL {
cb.crossQueue.RemoveAll()
return nil
}
crossQueue := cb.crossQueue.Iterate()
sc.Backend.Logger().Debug(fmt.Sprintf("gathered %v unified revocations entries", len(crossQueue)))
ourClusterId, err := sc.Backend.System().ClusterID(sc.Context)
if err != nil {
return fmt.Errorf("unable to fetch clusterID to ignore local unified revocation entries: %w", err)
}
for _, req := range crossQueue {
// Regardless of whether we're on the perf primary or a secondary
// cluster, we can safely ignore revocation requests originating
// from our node, because we've already checked them once (when
// they were created).
if ourClusterId != "" && ourClusterId == req.Cluster {
continue
}
// Fetch the revocation entry to ensure it exists and this wasn't
// a delete.
rPath := unifiedRevocationReadPathPrefix + req.Cluster + "/" + req.Serial
entry, err := sc.Storage.Get(sc.Context, rPath)
if err != nil {
return fmt.Errorf("failed to read unified revocation entry: %w", err)
}
if entry == nil {
// Skip this entry: it was likely caused by the deletion of this
// record during tidy.
cb.crossQueue.Remove(req)
continue
}
resp, err := tryRevokeCertBySerial(sc, crlConfig, req.Serial)
if err == nil && resp != nil && !resp.IsError() && resp.Data != nil && resp.Data["state"].(string) == "revoked" {
// We could theoretically save ourselves from writing a global
// revocation entry during the above certificate revocation, as
// we don't really need it to appear on either the unified CRL
// or its delta CRL, but this would require more plumbing.
cb.crossQueue.Remove(req)
} else if err != nil {
// Because we fake being from a lease, we get the guarantee that
// err == nil == resp if the cert was already revoked; this means
// this err should actually be fatal.
return err
}
}
return nil
}
// Helper function to fetch a map of issuerID->parsed cert for revocation
// usage. Unlike other paths, this needs to handle the legacy bundle
// more gracefully than rejecting it outright.
func fetchIssuerMapForRevocationChecking(sc *storageContext) (map[issuerID]*x509.Certificate, error) {
var err error
var issuers []issuerID
if !sc.Backend.useLegacyBundleCaStorage() {
issuers, err = sc.listIssuers()
if err != nil {
return nil, fmt.Errorf("could not fetch issuers list: %w", err)
}
} else {
// Hack: this isn't a real issuerID, but it works for fetchCAInfo
// since it resolves the reference.
issuers = []issuerID{legacyBundleShimID}
}
issuerIDCertMap := make(map[issuerID]*x509.Certificate, len(issuers))
for _, issuer := range issuers {
_, bundle, caErr := sc.fetchCertBundleByIssuerId(issuer, false)
if caErr != nil {
return nil, fmt.Errorf("error fetching CA certificate for issuer id %v: %w", issuer, caErr)
}
if bundle == nil {
return nil, fmt.Errorf("faulty reference: %v - CA info not found", issuer)
}
parsedBundle, err := parseCABundle(sc.Context, sc.Backend, bundle)
if err != nil {
return nil, errutil.InternalError{Err: err.Error()}
}
if parsedBundle.Certificate == nil {
return nil, errutil.InternalError{Err: "stored CA information not able to be parsed"}
}
issuerIDCertMap[issuer] = parsedBundle.Certificate
}
return issuerIDCertMap, nil
}
// Revoke a certificate from a given serial number if it is present in local
// storage.
func tryRevokeCertBySerial(sc *storageContext, config *crlConfig, serial string) (*logical.Response, error) {
// revokeCert requires us to hold these locks before calling it.
sc.Backend.revokeStorageLock.Lock()
defer sc.Backend.revokeStorageLock.Unlock()
certEntry, err := fetchCertBySerial(sc, "certs/", serial)
if err != nil {
switch err.(type) {
case errutil.UserError:
return logical.ErrorResponse(err.Error()), nil
default:
return nil, err
}
}
if certEntry == nil {
return nil, nil
}
cert, err := x509.ParseCertificate(certEntry.Value)
if err != nil {
return nil, fmt.Errorf("error parsing certificate: %w", err)
}
return revokeCert(sc, config, cert)
}
// Revokes a cert, and tries to be smart about error recovery
func revokeCert(sc *storageContext, config *crlConfig, cert *x509.Certificate) (*logical.Response, error) {
// As this backend is self-contained and this function does not hook into
// third parties to manage users or resources, if the mount is tainted,
// revocation doesn't matter anyways -- the CRL that would be written will
// be immediately blown away by the view being cleared. So we can simply
// fast path a successful exit.
if sc.Backend.System().Tainted() {
return nil, nil
}
colonSerial := serialFromCert(cert)
hyphenSerial := normalizeSerial(colonSerial)
// Validate that no issuers match the serial number to be revoked. We need
// to gracefully degrade to the legacy cert bundle when it is required, as
// secondary PR clusters might not have been upgraded, but still need to
// handle revoking certs.
issuerIDCertMap, err := fetchIssuerMapForRevocationChecking(sc)
if err != nil {
return nil, err
}
// Ensure we don't revoke an issuer via this API; use /issuer/:issuer_ref/revoke
// instead.
for issuer, certificate := range issuerIDCertMap {
if colonSerial == serialFromCert(certificate) {
return logical.ErrorResponse(fmt.Sprintf("adding issuer (id: %v) to its own CRL is not allowed", issuer)), nil
}
}
curRevInfo, err := sc.fetchRevocationInfo(colonSerial)
if err != nil {
return nil, err
}
if curRevInfo != nil {
resp := &logical.Response{
Data: map[string]interface{}{
"revocation_time": curRevInfo.RevocationTime,
"state": "revoked",
},
}
if !curRevInfo.RevocationTimeUTC.IsZero() {
resp.Data["revocation_time_rfc3339"] = curRevInfo.RevocationTimeUTC.Format(time.RFC3339Nano)
}
return resp, nil
}
// Add a little wiggle room because leases are stored with a second
// granularity
if cert.NotAfter.Before(time.Now().Add(2 * time.Second)) {
response := &logical.Response{}
response.AddWarning(fmt.Sprintf("certificate with serial %s already expired; refusing to add to CRL", colonSerial))