-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
path_fetch_issuers.go
1338 lines (1170 loc) · 41.8 KB
/
path_fetch_issuers.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 (
"context"
"crypto/x509"
"encoding/pem"
"fmt"
"net/http"
"strings"
"time"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/certutil"
"github.com/hashicorp/vault/sdk/logical"
)
func pathListIssuers(b *backend) *framework.Path {
return &framework.Path{
Pattern: "issuers/?$",
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixPKI,
OperationSuffix: "issuers",
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ListOperation: &framework.PathOperation{
Callback: b.pathListIssuersHandler,
Responses: map[int][]framework.Response{
http.StatusOK: {{
Description: "OK",
Fields: map[string]*framework.FieldSchema{
"keys": {
Type: framework.TypeStringSlice,
Description: `A list of keys`,
Required: true,
},
"key_info": {
Type: framework.TypeMap,
Description: `Key info with issuer name`,
Required: false,
},
},
}},
},
},
},
HelpSynopsis: pathListIssuersHelpSyn,
HelpDescription: pathListIssuersHelpDesc,
}
}
func (b *backend) pathListIssuersHandler(ctx context.Context, req *logical.Request, _ *framework.FieldData) (*logical.Response, error) {
if b.useLegacyBundleCaStorage() {
return logical.ErrorResponse("Can not list issuers until migration has completed"), nil
}
var responseKeys []string
responseInfo := make(map[string]interface{})
sc := b.makeStorageContext(ctx, req.Storage)
entries, err := sc.listIssuers()
if err != nil {
return nil, err
}
config, err := sc.getIssuersConfig()
if err != nil {
return nil, err
}
// For each issuer, we need not only the identifier (as returned by
// listIssuers), but also the name of the issuer. This means we have to
// fetch the actual issuer object as well.
for _, identifier := range entries {
issuer, err := sc.fetchIssuerById(identifier)
if err != nil {
return nil, err
}
responseKeys = append(responseKeys, string(identifier))
responseInfo[string(identifier)] = map[string]interface{}{
"issuer_name": issuer.Name,
"is_default": identifier == config.DefaultIssuerId,
"serial_number": issuer.SerialNumber,
// While nominally this could be considered sensitive information
// to be returned on an unauthed endpoint, there's two mitigating
// circumstances:
//
// 1. Key IDs are purely random numbers generated by Vault and
// have no relationship to the actual key material.
// 2. They also don't _do_ anything by themselves. There is no
// modification of KeyIDs allowed, you need to be authenticated
// to Vault to understand what they mean, you _essentially_
// get the same information from looking at/comparing various
// cert's SubjectPublicKeyInfo field, and there's the `default`
// reference that anyone with issuer generation capabilities
// can use even if they can't access any of the other /key/*
// endpoints.
//
// So all in all, exposing this value is not a security risk and
// is otherwise beneficial for the UI, hence its inclusion.
"key_id": issuer.KeyID,
}
}
return logical.ListResponseWithInfo(responseKeys, responseInfo), nil
}
const (
pathListIssuersHelpSyn = `Fetch a list of CA certificates.`
pathListIssuersHelpDesc = `
This endpoint allows listing of known issuing certificates, returning
their identifier and their name (if set).
`
)
func pathGetIssuer(b *backend) *framework.Path {
pattern := "issuer/" + framework.GenericNameRegex(issuerRefParam) + "$"
displayAttrs := &framework.DisplayAttributes{
OperationPrefix: operationPrefixPKI,
OperationSuffix: "issuer",
}
return buildPathIssuer(b, pattern, displayAttrs)
}
func pathGetUnauthedIssuer(b *backend) *framework.Path {
pattern := "issuer/" + framework.GenericNameRegex(issuerRefParam) + "/(json|der|pem)$"
displayAttrs := &framework.DisplayAttributes{
OperationPrefix: operationPrefixPKI,
OperationSuffix: "issuer-json|issuer-der|issuer-pem",
}
return buildPathGetIssuer(b, pattern, displayAttrs)
}
func buildPathIssuer(b *backend, pattern string, displayAttrs *framework.DisplayAttributes) *framework.Path {
fields := map[string]*framework.FieldSchema{}
fields = addIssuerRefNameFields(fields)
// Fields for updating issuer.
fields["manual_chain"] = &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: `Chain of issuer references to use to build this
issuer's computed CAChain field, when non-empty.`,
}
fields["leaf_not_after_behavior"] = &framework.FieldSchema{
Type: framework.TypeString,
Description: `Behavior of leaf's NotAfter fields: "err" to error
if the computed NotAfter date exceeds that of this issuer; "truncate" to
silently truncate to that of this issuer; or "permit" to allow this
issuance to succeed (with NotAfter exceeding that of an issuer). Note that
not all values will results in certificates that can be validated through
the entire validity period. It is suggested to use "truncate" for
intermediate CAs and "permit" only for root CAs.`,
Default: "err",
}
fields["usage"] = &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: `Comma-separated list (or string slice) of usages for
this issuer; valid values are "read-only", "issuing-certificates",
"crl-signing", and "ocsp-signing". Multiple values may be specified. Read-only
is implicit and always set.`,
Default: []string{"read-only", "issuing-certificates", "crl-signing", "ocsp-signing"},
}
fields["revocation_signature_algorithm"] = &framework.FieldSchema{
Type: framework.TypeString,
Description: `Which x509.SignatureAlgorithm name to use for
signing CRLs. This parameter allows differentiation between PKCS#1v1.5
and PSS keys and choice of signature hash algorithm. The default (empty
string) value is for Go to select the signature algorithm. This can fail
if the underlying key does not support the requested signature algorithm,
which may not be known at modification time (such as with PKCS#11 managed
RSA keys).`,
Default: "",
}
fields["issuing_certificates"] = &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: `Comma-separated list of URLs to be used
for the issuing certificate attribute. See also RFC 5280 Section 4.2.2.1.`,
}
fields["crl_distribution_points"] = &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: `Comma-separated list of URLs to be used
for the CRL distribution points attribute. See also RFC 5280 Section 4.2.1.13.`,
}
fields["ocsp_servers"] = &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: `Comma-separated list of URLs to be used
for the OCSP servers attribute. See also RFC 5280 Section 4.2.2.1.`,
}
fields["enable_aia_url_templating"] = &framework.FieldSchema{
Type: framework.TypeBool,
Description: `Whether or not to enabling templating of the
above AIA fields. When templating is enabled the special values '{{issuer_id}}',
'{{cluster_path}}', '{{cluster_aia_path}}' are available, but the addresses are
not checked for URL validity until issuance time. Using '{{cluster_path}}'
requires /config/cluster's 'path' member to be set on all PR Secondary clusters
and using '{{cluster_aia_path}}' requires /config/cluster's 'aia_path' member
to be set on all PR secondary clusters.`,
Default: false,
}
updateIssuerSchema := map[int][]framework.Response{
http.StatusOK: {{
Description: "OK",
Fields: map[string]*framework.FieldSchema{
"issuer_id": {
Type: framework.TypeString,
Description: `Issuer Id`,
Required: false,
},
"issuer_name": {
Type: framework.TypeString,
Description: `Issuer Name`,
Required: false,
},
"key_id": {
Type: framework.TypeString,
Description: `Key Id`,
Required: false,
},
"certificate": {
Type: framework.TypeString,
Description: `Certificate`,
Required: false,
},
"manual_chain": {
Type: framework.TypeStringSlice,
Description: `Manual Chain`,
Required: false,
},
"ca_chain": {
Type: framework.TypeStringSlice,
Description: `CA Chain`,
Required: false,
},
"leaf_not_after_behavior": {
Type: framework.TypeString,
Description: `Leaf Not After Behavior`,
Required: false,
},
"usage": {
Type: framework.TypeString,
Description: `Usage`,
Required: false,
},
"revocation_signature_algorithm": {
Type: framework.TypeString,
Description: `Revocation Signature Alogrithm`,
Required: false,
},
"revoked": {
Type: framework.TypeBool,
Description: `Revoked`,
Required: false,
},
"revocation_time": {
Type: framework.TypeInt,
Required: false,
},
"revocation_time_rfc3339": {
Type: framework.TypeString,
Required: false,
},
"issuing_certificates": {
Type: framework.TypeStringSlice,
Description: `Issuing Certificates`,
Required: false,
},
"crl_distribution_points": {
Type: framework.TypeStringSlice,
Description: `CRL Distribution Points`,
Required: false,
},
"ocsp_servers": {
Type: framework.TypeStringSlice,
Description: `OSCP Servers`,
Required: false,
},
"enable_aia_url_templating": {
Type: framework.TypeBool,
Description: `Whether or not templating is enabled for AIA fields`,
Required: false,
},
},
}},
}
return &framework.Path{
// Returns a JSON entry.
Pattern: pattern,
DisplayAttrs: displayAttrs,
Fields: fields,
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathGetIssuer,
Responses: updateIssuerSchema,
},
logical.UpdateOperation: &framework.PathOperation{
Callback: b.pathUpdateIssuer,
Responses: updateIssuerSchema,
// Read more about why these flags are set in backend.go.
ForwardPerformanceStandby: true,
ForwardPerformanceSecondary: true,
},
logical.DeleteOperation: &framework.PathOperation{
Callback: b.pathDeleteIssuer,
Responses: map[int][]framework.Response{
http.StatusNoContent: {{
Description: "No Content",
}},
},
// Read more about why these flags are set in backend.go.
ForwardPerformanceStandby: true,
ForwardPerformanceSecondary: true,
},
logical.PatchOperation: &framework.PathOperation{
Callback: b.pathPatchIssuer,
Responses: updateIssuerSchema,
// Read more about why these flags are set in backend.go.
ForwardPerformanceStandby: true,
ForwardPerformanceSecondary: true,
},
},
HelpSynopsis: pathGetIssuerHelpSyn,
HelpDescription: pathGetIssuerHelpDesc,
}
}
func buildPathGetIssuer(b *backend, pattern string, displayAttrs *framework.DisplayAttributes) *framework.Path {
fields := map[string]*framework.FieldSchema{}
fields = addIssuerRefField(fields)
getIssuerSchema := map[int][]framework.Response{
http.StatusNotModified: {{
Description: "Not Modified",
}},
http.StatusOK: {{
Description: "OK",
Fields: map[string]*framework.FieldSchema{
"issuer_id": {
Type: framework.TypeString,
Description: `Issuer Id`,
Required: true,
},
"issuer_name": {
Type: framework.TypeString,
Description: `Issuer Name`,
Required: true,
},
"certificate": {
Type: framework.TypeString,
Description: `Certificate`,
Required: true,
},
"ca_chain": {
Type: framework.TypeStringSlice,
Description: `CA Chain`,
Required: true,
},
},
}},
}
return &framework.Path{
// Returns a JSON entry.
Pattern: pattern,
DisplayAttrs: displayAttrs,
Fields: fields,
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathGetIssuer,
Responses: getIssuerSchema,
},
},
HelpSynopsis: pathGetIssuerHelpSyn,
HelpDescription: pathGetIssuerHelpDesc,
}
}
func (b *backend) pathGetIssuer(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
// Handle raw issuers first.
if strings.HasSuffix(req.Path, "/der") || strings.HasSuffix(req.Path, "/pem") || strings.HasSuffix(req.Path, "/json") {
return b.pathGetRawIssuer(ctx, req, data)
}
if b.useLegacyBundleCaStorage() {
return logical.ErrorResponse("Can not get issuer until migration has completed"), nil
}
issuerName := getIssuerRef(data)
if len(issuerName) == 0 {
return logical.ErrorResponse("missing issuer reference"), nil
}
sc := b.makeStorageContext(ctx, req.Storage)
ref, err := sc.resolveIssuerReference(issuerName)
if err != nil {
return nil, err
}
if ref == "" {
return logical.ErrorResponse("unable to resolve issuer id for reference: " + issuerName), nil
}
issuer, err := sc.fetchIssuerById(ref)
if err != nil {
return nil, err
}
return respondReadIssuer(issuer)
}
func respondReadIssuer(issuer *issuerEntry) (*logical.Response, error) {
var respManualChain []string
for _, entity := range issuer.ManualChain {
respManualChain = append(respManualChain, string(entity))
}
revSigAlgStr, present := certutil.InvSignatureAlgorithmNames[issuer.RevocationSigAlg]
if !present {
revSigAlgStr = issuer.RevocationSigAlg.String()
if issuer.RevocationSigAlg == x509.UnknownSignatureAlgorithm {
revSigAlgStr = ""
}
}
data := map[string]interface{}{
"issuer_id": issuer.ID,
"issuer_name": issuer.Name,
"key_id": issuer.KeyID,
"certificate": issuer.Certificate,
"manual_chain": respManualChain,
"ca_chain": issuer.CAChain,
"leaf_not_after_behavior": issuer.LeafNotAfterBehavior.String(),
"usage": issuer.Usage.Names(),
"revocation_signature_algorithm": revSigAlgStr,
"revoked": issuer.Revoked,
"issuing_certificates": []string{},
"crl_distribution_points": []string{},
"ocsp_servers": []string{},
}
if issuer.Revoked {
data["revocation_time"] = issuer.RevocationTime
data["revocation_time_rfc3339"] = issuer.RevocationTimeUTC.Format(time.RFC3339Nano)
}
if issuer.AIAURIs != nil {
data["issuing_certificates"] = issuer.AIAURIs.IssuingCertificates
data["crl_distribution_points"] = issuer.AIAURIs.CRLDistributionPoints
data["ocsp_servers"] = issuer.AIAURIs.OCSPServers
data["enable_aia_url_templating"] = issuer.AIAURIs.EnableTemplating
}
response := &logical.Response{
Data: data,
}
if issuer.RevocationSigAlg == x509.SHA256WithRSAPSS || issuer.RevocationSigAlg == x509.SHA384WithRSAPSS || issuer.RevocationSigAlg == x509.SHA512WithRSAPSS {
response.AddWarning("Issuer uses a PSS Revocation Signature Algorithm. This algorithm will be downgraded to PKCS#1v1.5 signature scheme on OCSP responses, due to limitations in the OCSP library.")
}
return response, nil
}
func (b *backend) pathUpdateIssuer(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
// Since we're planning on updating issuers here, grab the lock so we've
// got a consistent view.
b.issuersLock.Lock()
defer b.issuersLock.Unlock()
if b.useLegacyBundleCaStorage() {
return logical.ErrorResponse("Can not update issuer until migration has completed"), nil
}
issuerName := getIssuerRef(data)
if len(issuerName) == 0 {
return logical.ErrorResponse("missing issuer reference"), nil
}
sc := b.makeStorageContext(ctx, req.Storage)
ref, err := sc.resolveIssuerReference(issuerName)
if err != nil {
return nil, err
}
if ref == "" {
return logical.ErrorResponse("unable to resolve issuer id for reference: " + issuerName), nil
}
issuer, err := sc.fetchIssuerById(ref)
if err != nil {
return nil, err
}
newName, err := getIssuerName(sc, data)
if err != nil && err != errIssuerNameInUse {
// If the error is name already in use, and the new name is the
// old name for this issuer, we're not actually updating the
// issuer name (or causing a conflict) -- so don't err out. Other
// errs should still be surfaced, however.
return logical.ErrorResponse(err.Error()), nil
}
if err == errIssuerNameInUse && issuer.Name != newName {
// When the new name is in use but isn't this name, throw an error.
return logical.ErrorResponse(err.Error()), nil
}
if len(newName) > 0 && !nameMatcher.MatchString(newName) {
return logical.ErrorResponse("new key name outside of valid character limits"), nil
}
newPath := data.Get("manual_chain").([]string)
rawLeafBehavior := data.Get("leaf_not_after_behavior").(string)
var newLeafBehavior certutil.NotAfterBehavior
switch rawLeafBehavior {
case "err":
newLeafBehavior = certutil.ErrNotAfterBehavior
case "truncate":
newLeafBehavior = certutil.TruncateNotAfterBehavior
case "permit":
newLeafBehavior = certutil.PermitNotAfterBehavior
default:
return logical.ErrorResponse("Unknown value for field `leaf_not_after_behavior`. Possible values are `err`, `truncate`, and `permit`."), nil
}
rawUsage := data.Get("usage").([]string)
newUsage, err := NewIssuerUsageFromNames(rawUsage)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf("Unable to parse specified usages: %v - valid values are %v", rawUsage, AllIssuerUsages.Names())), nil
}
// Revocation signature algorithm changes
revSigAlgStr := data.Get("revocation_signature_algorithm").(string)
revSigAlg, present := certutil.SignatureAlgorithmNames[strings.ToLower(revSigAlgStr)]
if !present && revSigAlgStr != "" {
var knownAlgos []string
for algoName := range certutil.SignatureAlgorithmNames {
knownAlgos = append(knownAlgos, algoName)
}
return logical.ErrorResponse(fmt.Sprintf("Unknown signature algorithm value: %v - valid values are %v", revSigAlg, strings.Join(knownAlgos, ", "))), nil
} else if revSigAlgStr == "" {
revSigAlg = x509.UnknownSignatureAlgorithm
}
if err := issuer.CanMaybeSignWithAlgo(revSigAlg); err != nil {
return nil, err
}
// AIA access changes
enableTemplating := data.Get("enable_aia_url_templating").(bool)
issuerCertificates := data.Get("issuing_certificates").([]string)
if badURL := validateURLs(issuerCertificates); !enableTemplating && badURL != "" {
return logical.ErrorResponse(fmt.Sprintf("invalid URL found in Authority Information Access (AIA) parameter issuing_certificates: %s", badURL)), nil
}
crlDistributionPoints := data.Get("crl_distribution_points").([]string)
if badURL := validateURLs(crlDistributionPoints); !enableTemplating && badURL != "" {
return logical.ErrorResponse(fmt.Sprintf("invalid URL found in Authority Information Access (AIA) parameter crl_distribution_points: %s", badURL)), nil
}
ocspServers := data.Get("ocsp_servers").([]string)
if badURL := validateURLs(ocspServers); !enableTemplating && badURL != "" {
return logical.ErrorResponse(fmt.Sprintf("invalid URL found in Authority Information Access (AIA) parameter ocsp_servers: %s", badURL)), nil
}
modified := false
var oldName string
if newName != issuer.Name {
oldName = issuer.Name
issuer.Name = newName
issuer.LastModified = time.Now().UTC()
// See note in updateDefaultIssuerId about why this is necessary.
b.crlBuilder.invalidateCRLBuildTime()
b.crlBuilder.flushCRLBuildTimeInvalidation(sc)
modified = true
}
if newLeafBehavior != issuer.LeafNotAfterBehavior {
issuer.LeafNotAfterBehavior = newLeafBehavior
modified = true
}
if newUsage != issuer.Usage {
if issuer.Revoked && newUsage.HasUsage(IssuanceUsage) {
// Forbid allowing cert signing on its usage.
return logical.ErrorResponse("This issuer was revoked; unable to modify its usage to include certificate signing again. Reissue this certificate (preferably with a new key) and modify that entry instead."), nil
}
// Ensure we deny adding CRL usage if the bits are missing from the
// cert itself.
cert, err := issuer.GetCertificate()
if err != nil {
return nil, fmt.Errorf("unable to parse issuer's certificate: %w", err)
}
if (cert.KeyUsage&x509.KeyUsageCRLSign) == 0 && newUsage.HasUsage(CRLSigningUsage) {
return logical.ErrorResponse("This issuer's underlying certificate lacks the CRLSign KeyUsage value; unable to set CRLSigningUsage on this issuer as a result."), nil
}
issuer.Usage = newUsage
modified = true
}
if revSigAlg != issuer.RevocationSigAlg {
issuer.RevocationSigAlg = revSigAlg
modified = true
}
if issuer.AIAURIs == nil && (len(issuerCertificates) > 0 || len(crlDistributionPoints) > 0 || len(ocspServers) > 0) {
issuer.AIAURIs = &aiaConfigEntry{}
}
if issuer.AIAURIs != nil {
// Associative mapping from data source to destination on the
// backing issuer object.
type aiaPair struct {
Source *[]string
Dest *[]string
}
pairs := []aiaPair{
{
Source: &issuerCertificates,
Dest: &issuer.AIAURIs.IssuingCertificates,
},
{
Source: &crlDistributionPoints,
Dest: &issuer.AIAURIs.CRLDistributionPoints,
},
{
Source: &ocspServers,
Dest: &issuer.AIAURIs.OCSPServers,
},
}
// For each pair, if it is different on the object, update it.
for _, pair := range pairs {
if isStringArrayDifferent(*pair.Source, *pair.Dest) {
*pair.Dest = *pair.Source
modified = true
}
}
if enableTemplating != issuer.AIAURIs.EnableTemplating {
issuer.AIAURIs.EnableTemplating = enableTemplating
modified = true
}
// If no AIA URLs exist on the issuer, set the AIA URLs entry to nil
// to ease usage later.
if len(issuer.AIAURIs.IssuingCertificates) == 0 && len(issuer.AIAURIs.CRLDistributionPoints) == 0 && len(issuer.AIAURIs.OCSPServers) == 0 {
issuer.AIAURIs = nil
}
}
// Updating the chain should be the last modification as there's a chance
// it'll write it out to disk for us. We'd hate to then modify the issuer
// again and write it a second time.
var updateChain bool
var constructedChain []issuerID
for index, newPathRef := range newPath {
// Allow self for the first entry.
if index == 0 && newPathRef == "self" {
newPathRef = string(ref)
}
resolvedId, err := sc.resolveIssuerReference(newPathRef)
if err != nil {
return nil, err
}
if index == 0 && resolvedId != ref {
return logical.ErrorResponse(fmt.Sprintf("expected first cert in chain to be a self-reference, but was: %v/%v", newPathRef, resolvedId)), nil
}
constructedChain = append(constructedChain, resolvedId)
if len(issuer.ManualChain) < len(constructedChain) || constructedChain[index] != issuer.ManualChain[index] {
updateChain = true
}
}
if len(issuer.ManualChain) != len(constructedChain) {
updateChain = true
}
if updateChain {
issuer.ManualChain = constructedChain
// Building the chain will write the issuer to disk; no need to do it
// twice.
modified = false
err := sc.rebuildIssuersChains(issuer)
if err != nil {
return nil, err
}
}
if modified {
err := sc.writeIssuer(issuer)
if err != nil {
return nil, err
}
}
response, err := respondReadIssuer(issuer)
if newName != oldName {
addWarningOnDereferencing(sc, oldName, response)
}
if issuer.AIAURIs != nil && issuer.AIAURIs.EnableTemplating {
_, aiaErr := issuer.AIAURIs.toURLEntries(sc, issuer.ID)
if aiaErr != nil {
response.AddWarning(fmt.Sprintf("issuance may fail: %v\n\nConsider setting the cluster-local address if it is not already set.", aiaErr))
}
}
return response, err
}
func (b *backend) pathPatchIssuer(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
// Since we're planning on updating issuers here, grab the lock so we've
// got a consistent view.
b.issuersLock.Lock()
defer b.issuersLock.Unlock()
if b.useLegacyBundleCaStorage() {
return logical.ErrorResponse("Can not patch issuer until migration has completed"), nil
}
// First we fetch the issuer
issuerName := getIssuerRef(data)
if len(issuerName) == 0 {
return logical.ErrorResponse("missing issuer reference"), nil
}
sc := b.makeStorageContext(ctx, req.Storage)
ref, err := sc.resolveIssuerReference(issuerName)
if err != nil {
return nil, err
}
if ref == "" {
return logical.ErrorResponse("unable to resolve issuer id for reference: " + issuerName), nil
}
issuer, err := sc.fetchIssuerById(ref)
if err != nil {
return nil, err
}
// Now We are Looking at What (Might) Have Changed
modified := false
// Name Changes First
_, ok := data.GetOk("issuer_name") // Don't check for conflicts if we aren't updating the name
var oldName string
var newName string
if ok {
newName, err = getIssuerName(sc, data)
if err != nil && err != errIssuerNameInUse && err != errIssuerNameIsEmpty {
// If the error is name already in use, and the new name is the
// old name for this issuer, we're not actually updating the
// issuer name (or causing a conflict) -- so don't err out. Other
// errs should still be surfaced, however.
return logical.ErrorResponse(err.Error()), nil
}
if err == errIssuerNameInUse && issuer.Name != newName {
// When the new name is in use but isn't this name, throw an error.
return logical.ErrorResponse(err.Error()), nil
}
if len(newName) > 0 && !nameMatcher.MatchString(newName) {
return logical.ErrorResponse("new key name outside of valid character limits"), nil
}
if newName != issuer.Name {
oldName = issuer.Name
issuer.Name = newName
issuer.LastModified = time.Now().UTC()
// See note in updateDefaultIssuerId about why this is necessary.
b.crlBuilder.invalidateCRLBuildTime()
b.crlBuilder.flushCRLBuildTimeInvalidation(sc)
modified = true
}
}
// Leaf Not After Changes
rawLeafBehaviorData, ok := data.GetOk("leaf_not_after_behavior")
if ok {
rawLeafBehavior := rawLeafBehaviorData.(string)
var newLeafBehavior certutil.NotAfterBehavior
switch rawLeafBehavior {
case "err":
newLeafBehavior = certutil.ErrNotAfterBehavior
case "truncate":
newLeafBehavior = certutil.TruncateNotAfterBehavior
case "permit":
newLeafBehavior = certutil.PermitNotAfterBehavior
default:
return logical.ErrorResponse("Unknown value for field `leaf_not_after_behavior`. Possible values are `err`, `truncate`, and `permit`."), nil
}
if newLeafBehavior != issuer.LeafNotAfterBehavior {
issuer.LeafNotAfterBehavior = newLeafBehavior
modified = true
}
}
// Usage Changes
rawUsageData, ok := data.GetOk("usage")
if ok {
rawUsage := rawUsageData.([]string)
newUsage, err := NewIssuerUsageFromNames(rawUsage)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf("Unable to parse specified usages: %v - valid values are %v", rawUsage, AllIssuerUsages.Names())), nil
}
if newUsage != issuer.Usage {
if issuer.Revoked && newUsage.HasUsage(IssuanceUsage) {
// Forbid allowing cert signing on its usage.
return logical.ErrorResponse("This issuer was revoked; unable to modify its usage to include certificate signing again. Reissue this certificate (preferably with a new key) and modify that entry instead."), nil
}
cert, err := issuer.GetCertificate()
if err != nil {
return nil, fmt.Errorf("unable to parse issuer's certificate: %w", err)
}
if (cert.KeyUsage&x509.KeyUsageCRLSign) == 0 && newUsage.HasUsage(CRLSigningUsage) {
return logical.ErrorResponse("This issuer's underlying certificate lacks the CRLSign KeyUsage value; unable to set CRLSigningUsage on this issuer as a result."), nil
}
issuer.Usage = newUsage
modified = true
}
}
// Revocation signature algorithm changes
rawRevSigAlg, ok := data.GetOk("revocation_signature_algorithm")
if ok {
revSigAlgStr := rawRevSigAlg.(string)
revSigAlg, present := certutil.SignatureAlgorithmNames[strings.ToLower(revSigAlgStr)]
if !present && revSigAlgStr != "" {
var knownAlgos []string
for algoName := range certutil.SignatureAlgorithmNames {
knownAlgos = append(knownAlgos, algoName)
}
return logical.ErrorResponse(fmt.Sprintf("Unknown signature algorithm value: %v - valid values are %v", revSigAlg, strings.Join(knownAlgos, ", "))), nil
} else if revSigAlgStr == "" {
revSigAlg = x509.UnknownSignatureAlgorithm
}
if err := issuer.CanMaybeSignWithAlgo(revSigAlg); err != nil {
return nil, err
}
if revSigAlg != issuer.RevocationSigAlg {
issuer.RevocationSigAlg = revSigAlg
modified = true
}
}
// AIA access changes.
if issuer.AIAURIs == nil {
issuer.AIAURIs = &aiaConfigEntry{}
}
// Associative mapping from data source to destination on the
// backing issuer object. For PATCH requests, we use the source
// data parameter as we still need to validate them and process
// it into a string list.
type aiaPair struct {
Source string
Dest *[]string
}
pairs := []aiaPair{
{
Source: "issuing_certificates",
Dest: &issuer.AIAURIs.IssuingCertificates,
},
{
Source: "crl_distribution_points",
Dest: &issuer.AIAURIs.CRLDistributionPoints,
},
{
Source: "ocsp_servers",
Dest: &issuer.AIAURIs.OCSPServers,
},
}
if enableTemplatingRaw, ok := data.GetOk("enable_aia_url_templating"); ok {
enableTemplating := enableTemplatingRaw.(bool)
if enableTemplating != issuer.AIAURIs.EnableTemplating {
issuer.AIAURIs.EnableTemplating = true
modified = true
}
}
// For each pair, if it is different on the object, update it.
for _, pair := range pairs {
rawURLsValue, ok := data.GetOk(pair.Source)
if ok {
urlsValue := rawURLsValue.([]string)
if badURL := validateURLs(urlsValue); !issuer.AIAURIs.EnableTemplating && badURL != "" {
return logical.ErrorResponse(fmt.Sprintf("invalid URL found in Authority Information Access (AIA) parameter %v: %s", pair.Source, badURL)), nil
}
if isStringArrayDifferent(urlsValue, *pair.Dest) {
modified = true
*pair.Dest = urlsValue
}
}
}
// If no AIA URLs exist on the issuer, set the AIA URLs entry to nil to
// ease usage later.
if len(issuer.AIAURIs.IssuingCertificates) == 0 && len(issuer.AIAURIs.CRLDistributionPoints) == 0 && len(issuer.AIAURIs.OCSPServers) == 0 {
issuer.AIAURIs = nil
}
// Manual Chain Changes
newPathData, ok := data.GetOk("manual_chain")
if ok {
newPath := newPathData.([]string)
var updateChain bool
var constructedChain []issuerID
for index, newPathRef := range newPath {
// Allow self for the first entry.
if index == 0 && newPathRef == "self" {
newPathRef = string(ref)
}
resolvedId, err := sc.resolveIssuerReference(newPathRef)
if err != nil {
return nil, err
}
if index == 0 && resolvedId != ref {
return logical.ErrorResponse(fmt.Sprintf("expected first cert in chain to be a self-reference, but was: %v/%v", newPathRef, resolvedId)), nil
}
constructedChain = append(constructedChain, resolvedId)
if len(issuer.ManualChain) < len(constructedChain) || constructedChain[index] != issuer.ManualChain[index] {
updateChain = true
}
}
if len(issuer.ManualChain) != len(constructedChain) {
updateChain = true
}
if updateChain {
issuer.ManualChain = constructedChain
// Building the chain will write the issuer to disk; no need to do it
// twice.
modified = false
err := sc.rebuildIssuersChains(issuer)
if err != nil {
return nil, err
}
}
}
if modified {
err := sc.writeIssuer(issuer)
if err != nil {
return nil, err
}
}
response, err := respondReadIssuer(issuer)
if newName != oldName {
addWarningOnDereferencing(sc, oldName, response)
}
if issuer.AIAURIs != nil && issuer.AIAURIs.EnableTemplating {
_, aiaErr := issuer.AIAURIs.toURLEntries(sc, issuer.ID)
if aiaErr != nil {
response.AddWarning(fmt.Sprintf("issuance may fail: %v\n\nConsider setting the cluster-local address if it is not already set.", aiaErr))
}
}
return response, err
}
func (b *backend) pathGetRawIssuer(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
if b.useLegacyBundleCaStorage() {
return logical.ErrorResponse("Can not get issuer until migration has completed"), nil
}
issuerName := getIssuerRef(data)
if len(issuerName) == 0 {
return logical.ErrorResponse("missing issuer reference"), nil
}
sc := b.makeStorageContext(ctx, req.Storage)
ref, err := sc.resolveIssuerReference(issuerName)
if err != nil {