-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathpath_certs.go
More file actions
864 lines (727 loc) · 27.3 KB
/
Copy pathpath_certs.go
File metadata and controls
864 lines (727 loc) · 27.3 KB
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
/*
* Copyright 2026 Keyfactor
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package kfbackend
import (
"context"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"strings"
"time"
v1 "github.com/Keyfactor/keyfactor-go-client-sdk/v24/api/keyfactor/v1"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/consts"
"github.com/hashicorp/vault/sdk/helper/errutil"
"github.com/hashicorp/vault/sdk/logical"
)
const kf_revoke_path = "/Certificates/Revoke"
type revocationInfo struct {
CertificateBytes []byte `json:"certificate_bytes"`
RevocationTime int64 `json:"revocation_time"`
RevocationTimeUTC time.Time `json:"revocation_time_utc"`
}
func pathCerts(b *keyfactorBackend) []*framework.Path {
return []*framework.Path{
{ // certs list
Pattern: "certs/?$",
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ListOperation: b.pathFetchCertList,
},
HelpSynopsis: pathFetchListHelpSyn,
HelpDescription: pathFetchListHelpDesc,
},
{ // issue
Pattern: "issue/" + framework.GenericNameRegex("role"),
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathIssue,
},
HelpSynopsis: pathIssueHelpSyn,
HelpDescription: pathIssueHelpDesc,
Fields: addNonCACommonFields(map[string]*framework.FieldSchema{}),
},
{ // sign
Pattern: "sign/" + framework.GenericNameRegex("role"),
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathSign,
},
HelpSynopsis: pathSignHelpSyn,
HelpDescription: pathSignHelpDesc,
Fields: addNonCACommonFields(map[string]*framework.FieldSchema{
"csr": {
Type: framework.TypeString,
Default: "",
Description: `PEM-format CSR to be signed.`,
Required: true,
}}),
},
{ // fetch cert
Pattern: `certs/(?P<serial>[0-9A-Fa-f-:]+)`,
Fields: map[string]*framework.FieldSchema{
"serial": {
Type: framework.TypeString,
Description: `Certificate serial number, in colon- or
hyphen-separated octal`,
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: b.pathFetchCert,
},
HelpSynopsis: pathFetchHelpSyn,
HelpDescription: pathFetchHelpDesc,
},
{ // revoke
Pattern: `revoke/?$`,
Fields: map[string]*framework.FieldSchema{
"serial": {
Type: framework.TypeString,
Description: `The serial number of the certificate to revoke`,
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathRevokeCert,
logical.RevokeOperation: b.pathRevokeCert,
},
HelpSynopsis: pathRevokeHelpSyn,
HelpDescription: pathRevokeHelpDesc,
},
}
}
func (b *keyfactorBackend) pathFetchCertList(ctx context.Context, req *logical.Request, data *framework.FieldData) (response *logical.Response, retErr error) {
entries, err := req.Storage.List(ctx, "certs/")
if err != nil {
return nil, err
}
// Build a key_info map so that listing shows the common name alongside each
// serial number. The common name is parsed from the stored certificate.
keyInfo := map[string]interface{}{}
for _, serial := range entries {
entry, gErr := req.Storage.Get(ctx, "certs/"+serial)
if gErr != nil || entry == nil {
continue
}
commonName := ""
if block, _ := pem.Decode(entry.Value); block != nil {
if parsed, pErr := x509.ParseCertificate(block.Bytes); pErr == nil {
commonName = parsed.Subject.CommonName
}
}
keyInfo[serial] = map[string]interface{}{
"common_name": commonName,
}
}
return logical.ListResponseWithInfo(entries, keyInfo), nil
}
func (b *keyfactorBackend) pathFetchCert(ctx context.Context, req *logical.Request, data *framework.FieldData) (response *logical.Response, retErr error) {
var serial, contentType string
var certEntry, revokedEntry *logical.StorageEntry
var funcErr error
var certificate string
var revocationTime int64
response = &logical.Response{
Data: map[string]interface{}{},
}
// Some of these need to return raw and some non-raw;
// this is basically handled by setting contentType or not.
// Errors don't cause an immediate exit, because the raw
// paths still need to return raw output.
b.Logger().Debug("fetching cert, path = " + req.Path)
serial = data.Get("serial").(string)
if len(serial) == 0 {
response = logical.ErrorResponse("The serial number must be provided")
goto reply
}
b.Logger().Debug("fetching certificate; serial = " + serial)
certEntry, funcErr = fetchCertBySerial(ctx, req, req.Path, serial)
if funcErr != nil {
switch funcErr.(type) {
case errutil.UserError:
response = logical.ErrorResponse(funcErr.Error())
goto reply
case errutil.InternalError:
retErr = funcErr
goto reply
}
}
if certEntry == nil {
response = nil
goto reply
}
b.Logger().Debug("fetched certEntry.Value = ", certEntry.Value)
certificate = string(certEntry.Value)
revokedEntry, funcErr = fetchCertBySerial(ctx, req, "revoked/", serial)
if funcErr != nil {
switch funcErr.(type) {
case errutil.UserError:
response = logical.ErrorResponse(funcErr.Error())
goto reply
case errutil.InternalError:
retErr = funcErr
goto reply
}
}
if revokedEntry != nil {
var revInfo revocationInfo
err := revokedEntry.DecodeJSON(&revInfo)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf("Error decoding revocation entry for serial %s: %s", serial, err)), nil
}
revocationTime = revInfo.RevocationTime
}
reply:
switch {
case len(contentType) != 0:
response = &logical.Response{
Data: map[string]interface{}{
logical.HTTPContentType: contentType,
logical.HTTPRawBody: certificate,
}}
if retErr != nil {
if b.Logger().IsWarn() {
b.Logger().Warn("possible error, but cannot return in raw response. Note that an empty CA probably means none was configured, and an empty CRL is possibly correct", "error", retErr)
}
}
retErr = nil
if len(certificate) > 0 {
response.Data[logical.HTTPStatusCode] = 200
} else {
response.Data[logical.HTTPStatusCode] = 204
}
case retErr != nil:
response = nil
return
case response == nil:
return
case response.IsError():
return response, nil
default:
response.Data["serial_number"] = normalizeSerial(serial)
response.Data["certificate"] = certificate
response.Data["revocation_time"] = revocationTime
// Parse the stored certificate to surface the common name and
// expiration date. Parse failures are non-fatal; we still return what
// we have.
if block, _ := pem.Decode([]byte(certificate)); block != nil {
if parsed, pErr := x509.ParseCertificate(block.Bytes); pErr == nil {
response.Data["common_name"] = parsed.Subject.CommonName
response.Data["expiration"] = parsed.NotAfter.UTC().Format(time.RFC3339)
} else {
b.Logger().Warn("unable to parse stored certificate", "serial", serial, "error", pErr)
}
}
// Include any Command metadata stored for this certificate. Omit the
// field entirely when there is none, since most certificates won't
// have metadata.
metadata := map[string]interface{}{}
if metaEntry, mErr := req.Storage.Get(ctx, "metadata/"+normalizeSerial(serial)); mErr == nil && metaEntry != nil {
if dErr := metaEntry.DecodeJSON(&metadata); dErr != nil {
b.Logger().Warn("unable to decode stored certificate metadata", "serial", serial, "error", dErr)
}
}
if len(metadata) > 0 {
response.Data["metadata"] = metadata
}
}
return
}
// pathIssue issues a certificate and private key from given parameters,
// subject to role restrictions
func (b *keyfactorBackend) pathIssue(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := data.Get("role").(string)
b.Logger().Debug(fmt.Sprintf("got role name of %s", roleName))
// Get the role
role, err := b.getRole(ctx, req.Storage, roleName)
if err != nil {
return nil, err
}
if role == nil {
return logical.ErrorResponse(fmt.Sprintf("unknown role: %s", roleName)), nil
}
if role.KeyType == "any" {
return logical.ErrorResponse("role key type \"any\" not allowed for issuing certificates, only signing"), nil
}
return b.pathIssueSignCert(ctx, req, data, role, roleName)
}
// pathSign issues a certificate from a submitted CSR, subject to role
// restrictions
func (b *keyfactorBackend) pathSign(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := data.Get("role").(string)
csr := data.Get("csr").(string)
// Get the role
role, err := b.getRole(ctx, req.Storage, roleName)
if err != nil {
return nil, err
}
if role == nil {
return logical.ErrorResponse(fmt.Sprintf("unknown role: %s", roleName)), nil
}
if !role.NoStore && b.System().ReplicationState().HasState(consts.ReplicationPerformanceStandby) {
return nil, logical.ErrReadOnly
}
var err_resp error
var valid bool
arg, _ := json.Marshal(req.Data)
b.Logger().Debug(string(arg))
// validate DNS SANS (optional)
var dns_sans []string
b.Logger().Debug("parsing dns_sans...")
dns_sans_string, ok := data.GetOk("dns_sans")
if ok && dns_sans_string != nil && dns_sans_string.(string) != "" {
dns_sans = strings.Split(dns_sans_string.(string), ",")
b.Logger().Debug(fmt.Sprintf("dns_sans = %s", dns_sans))
b.Logger().Trace("checking to make sure all DNS SANs are allowed by role..")
// check the provided DNS sans against allowed domains
valid, err_resp = checkAllowedDomains(role, roleName, dns_sans)
if err_resp != nil && !valid {
b.Logger().Error(err_resp.Error())
return logical.ErrorResponse("DNS_SAN(s) not allowed for role: %s", err_resp.Error()), err_resp
}
} else {
b.Logger().Debug("no DNS SANs provided")
}
// ip sans (optional)
var ip_sans []string
b.Logger().Debug("parsing ip_sans...")
ip_sans_string, ok := data.GetOk("ip_sans")
if ok && ip_sans_string != nil && ip_sans_string.(string) != "" {
b.Logger().Trace(fmt.Sprintf("passed ip_sans: %s", ip_sans_string.(string)))
ip_sans = strings.Split(ip_sans_string.(string), ",")
} else {
b.Logger().Debug("no IP SANs provided")
}
// load the configuration so we can fall back to configured defaults
config, err := b.fetchConfig(ctx, req.Storage)
if err != nil {
return nil, err
}
if config == nil {
return logical.ErrorResponse("the backend is not configured; write to the config path first"), nil
}
// get the CA name
b.Logger().Debug("parsing ca...")
caName := data.Get("ca").(string)
if caName == "" {
b.Logger().Debug("no ca passed, retreiving from config")
caName = config.CertAuthority
}
if caName == "" {
return logical.ErrorResponse("no certificate authority was provided and there is no configuration entry for ca"), fmt.Errorf("CA name is required")
}
b.Logger().Debug(fmt.Sprintf("ca name = %s", caName))
// get the template name
b.Logger().Debug("parsing template name...")
templateName := data.Get("template").(string)
if templateName == "" {
b.Logger().Debug("no template name in parameters, retrieving from config")
templateName = config.CertTemplate
if templateName == "" {
return logical.ErrorResponse("no certificate template name was provided and there is no configuration entry for 'template'"), fmt.Errorf("template name is required")
}
}
b.Logger().Debug(fmt.Sprintf("template name: %s", templateName))
//check role permissions
metadata := data.Get("metadata").(string)
if metadata == "" {
metadata = "{}"
}
// verify that any passed metadata string is valid JSON
if !json.Valid([]byte(metadata)) {
err_resp = fmt.Errorf("'%s' is not a valid JSON string", metadata)
b.Logger().Error(err_resp.Error())
}
if err_resp != nil {
return nil, err_resp
}
certs, serial, errr := b.submitCSR(ctx, req, csr, caName, templateName, dns_sans, ip_sans, metadata)
if errr != nil {
return nil, fmt.Errorf("could not sign csr: %s", errr)
}
if len(certs) < 2 {
return nil, fmt.Errorf("expected a certificate and an issuing CA in the enrollment response, but got %d certificate(s)", len(certs))
}
response := &logical.Response{
Data: map[string]interface{}{
"certificate": certs[0],
"issuing_ca": certs[1],
"serial_number": serial,
},
}
// echo the submitted metadata back in the response (it was validated as
// JSON above and parsed by submitCSR); omit it entirely when empty.
metadataMap := map[string]interface{}{}
_ = json.Unmarshal([]byte(metadata), &metadataMap)
if len(metadataMap) > 0 {
response.Data["metadata"] = metadataMap
}
return response, nil
}
func (b *keyfactorBackend) pathIssueSignCert(ctx context.Context, req *logical.Request, data *framework.FieldData, role *roleEntry, roleName string) (*logical.Response, error) {
// If storing the certificate and on a performance standby, forward this request on to the primary
if !role.NoStore && b.System().ReplicationState().HasState(consts.ReplicationPerformanceStandby) {
return nil, logical.ErrReadOnly
}
var ip_sans []string
var dns_sans []string
var err_resp error
var valid bool
arg, _ := json.Marshal(req.Data)
b.Logger().Debug(string(arg))
// validate Common Name (required)
b.Logger().Debug("parsing common_name...")
cn, ok := data.GetOk("common_name")
if !ok || cn == nil || cn.(string) == "" {
return nil, fmt.Errorf("common_name must be provided to issue certificate")
}
cn = cn.(string)
b.Logger().Debug(fmt.Sprintf("common_name = %s", cn))
// check to make sure common name is allowed by role
b.Logger().Trace("checking common name" + cn.(string))
valid, err_resp = checkAllowedDomains(role, roleName, []string{cn.(string)})
if err_resp != nil && !valid {
b.Logger().Error(err_resp.Error())
return logical.ErrorResponse("disallowed common name was provided: %s", err_resp.Error()), err_resp
}
// validate DNS SANS (required)
b.Logger().Debug("parsing dns_sans...")
dns_sans_string, ok := data.GetOk("dns_sans")
if !ok || dns_sans_string == nil || dns_sans_string == "" {
return nil, fmt.Errorf("dns_sans must be provided to issue certificate")
}
dns_sans_string = dns_sans_string.(string)
dns_sans = strings.Split(dns_sans_string.(string), ",")
b.Logger().Debug(fmt.Sprintf("dns_sans = %s", dns_sans))
cnMatch := false
// make sure at least one DNS SAN matches the common name
for u := range dns_sans {
if cnMatch {
break
} // no need to check the rest if there was a match.
cnMatch = dns_sans[u] == cn.(string)
}
if !cnMatch {
err_resp = fmt.Errorf("at least one DNS SAN is required to match the supplied Common Name for RFC 2818 compliance")
b.Logger().Error(err_resp.Error())
return logical.ErrorResponse(err_resp.Error()), err_resp
}
b.Logger().Trace("checking to make sure all DNS SANs are allowed by role..")
// check the provided DNS sans against allowed domains
valid, err_resp = checkAllowedDomains(role, roleName, dns_sans)
if err_resp != nil && !valid {
b.Logger().Error(err_resp.Error())
return logical.ErrorResponse("DNS_SAN(s) not allowed for role: %s", err_resp.Error()), err_resp
}
// ip sans (optional)
b.Logger().Debug("parsing ip_sans...")
ip_sans_string, ok := data.GetOk("ip_sans")
if ok && ip_sans_string != nil && ip_sans_string.(string) != "" {
ip_sans = strings.Split(ip_sans_string.(string), ",")
}
// load the configuration so we can fall back to configured defaults
config, cfgErr := b.fetchConfig(ctx, req.Storage)
if cfgErr != nil {
return nil, cfgErr
}
if config == nil {
return logical.ErrorResponse("the backend is not configured; write to the config path first"), nil
}
// get the CA name
b.Logger().Debug("parsing ca...")
caName := data.Get("ca").(string)
if caName == "" {
b.Logger().Debug("no ca passed, retreiving from config")
caName = config.CertAuthority
}
if caName == "" {
return logical.ErrorResponse("no certificate authority was provided and there is no configuration entry for ca"), fmt.Errorf("CA name is required")
}
b.Logger().Debug(fmt.Sprintf("ca name = %s", caName))
// get the template name
b.Logger().Debug("parsing template name...")
templateName := data.Get("template").(string)
if templateName == "" {
b.Logger().Debug("no template name in parameters, retrieving from config")
templateName = config.CertTemplate
}
b.Logger().Debug(fmt.Sprintf("template name: %s", templateName))
// verify that any passed metadata string is valid JSON
metadata := data.Get("metadata").(string)
if metadata == "" {
metadata = "{}"
}
b.Logger().Debug(fmt.Sprintf("checking validity of metadata JSON... %s", metadata))
if !json.Valid([]byte(metadata)) {
err_resp = fmt.Errorf("'%s' is not a valid JSON string", metadata)
b.Logger().Error(err_resp.Error())
}
if err_resp != nil {
return nil, err_resp
}
//generate and submit CSR
b.Logger().Debug("generating the CSR...")
csr, key, csrErr := b.generateCSR(cn.(string), ip_sans, dns_sans)
if csrErr != nil {
return nil, fmt.Errorf("could not generate CSR: %w", csrErr)
}
certs, serial, errr := b.submitCSR(ctx, req, csr, caName, templateName, dns_sans, ip_sans, metadata)
if errr != nil {
return nil, fmt.Errorf("could not enroll certificate: %s", errr)
}
if len(certs) < 2 {
return nil, fmt.Errorf("expected a certificate and an issuing CA in the enrollment response, but got %d certificate(s)", len(certs))
}
// Conform response to Vault PKI API
response := &logical.Response{
Data: map[string]interface{}{
"certificate": certs[0],
"issuing_ca": certs[1],
"private_key": "-----BEGIN RSA PRIVATE KEY-----\n" + base64.StdEncoding.EncodeToString(key) + "\n-----END RSA PRIVATE KEY-----",
"private_key_type": "rsa",
"revocation_time": 0,
"serial_number": serial,
},
}
// echo the submitted metadata back in the response (it was validated as
// JSON above and parsed by submitCSR); omit it entirely when empty.
metadataMap := map[string]interface{}{}
_ = json.Unmarshal([]byte(metadata), &metadataMap)
if len(metadataMap) > 0 {
response.Data["metadata"] = metadataMap
}
return response, nil
}
func (b *keyfactorBackend) pathRevokeCert(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
serial := data.Get("serial").(string)
b.Logger().Debug("serial = " + serial)
if len(serial) == 0 {
return logical.ErrorResponse("the serial number must be provided"), fmt.Errorf("the serial number must be provided")
}
// We store and identify by lowercase colon-separated hex, but other
// utilities use dashes and/or uppercase, so normalize
serial = strings.Replace(strings.ToLower(serial), "-", ":", -1)
return revokeCert(ctx, b, req, serial, false)
}
// decodeStoredKeyfactorID decodes a Keyfactor certificate ID from its stored
// entry. It intentionally uses a plain json.Unmarshal rather than the
// compression-aware logical.StorageEntry.DecodeJSON: the ID is stored as a bare
// JSON number, and DecodeJSON inspects the leading byte for a Vault compression
// canary. An ID whose decimal form begins with a canary character (notably '4',
// the LZ4 canary) would otherwise be misread as compressed data and fail with
// "lz4: bad magic number". The value is always stored uncompressed, so a plain
// unmarshal is correct and backward-compatible.
func decodeStoredKeyfactorID(entry *logical.StorageEntry) (int32, error) {
if entry == nil {
return 0, fmt.Errorf("keyfactor ID storage entry is nil")
}
var id int32
if err := json.Unmarshal(entry.Value, &id); err != nil {
return 0, err
}
return id, nil
}
// Revokes a cert, and tries to be smart about error recovery
func revokeCert(ctx context.Context, b *keyfactorBackend, req *logical.Request, serial string, fromLease bool) (*logical.Response, error) {
if b.System().Tainted() {
return nil, nil
}
serial = strings.ToUpper(serial)
// get client
client, err := b.getClient(ctx, req.Storage)
if err != nil {
return nil, fmt.Errorf("error getting client: %w", err)
}
b.Logger().Debug(fmt.Sprintf("retreiving the keyfactor ID for cert stored at path: %s", "kfId/"+serial))
kfId, err := req.Storage.Get(ctx, "kfId/"+serial) //retrieve the keyfactor certificate ID, keyed by sn here
if err != nil {
b.Logger().Error("unable to retrieve Keyfactor certificate ID for cert with serial: "+serial, "error", err)
return nil, err
}
if kfId == nil {
return logical.ErrorResponse(fmt.Sprintf("no Keyfactor certificate ID is stored for serial %s; it cannot be revoked through this plugin", serial)), nil
}
b.Logger().Debug("retrieved the logical storage entry, decoding...")
keyfactorId, err := decodeStoredKeyfactorID(kfId)
if err != nil {
b.Logger().Error("Unable to parse stored certificate ID for cert with serial: "+serial, "error", err)
return nil, err
}
b.Logger().Debug(fmt.Sprintf("decoded keyfactor ID value: %d", keyfactorId))
// set up keyfactor api request
//url := b.cachedConfig.KeyfactorUrl + "/" + b.cachedConfig.CommandAPIPath + kf_revoke_path
certIds := []int32{keyfactorId}
revokeReason := v1.KeyfactorPKIEnumsRevokeCode(0)
effectiveDate := time.Now().UTC()
revokeComment := "via Hashicorp Vault"
collectionId := int32(0)
revokeReq := v1.CertificatesRevokeCertificateRequest{
CertificateIds: certIds,
Reason: &revokeReason,
EffectiveDate: &effectiveDate,
Comment: *v1.NewNullableString(&revokeComment),
CollectionId: *v1.NewNullableInt32(&collectionId),
}
// create the api call wrapper object
apiReq := client.V1.CertificateApi.NewCreateCertificatesRevokeRequest(ctx).CertificatesRevokeCertificateRequest(revokeReq)
// execute request
_, httpResponse, err := apiReq.Execute()
if err != nil {
b.Logger().Error(fmt.Sprintf("revocation failed: %s", err))
return nil, fmt.Errorf("revocation failed: %w", err)
}
if httpResponse == nil {
return nil, errors.New("revocation failed: no response received from Command")
}
if httpResponse.StatusCode != 204 && httpResponse.StatusCode != 200 {
b.Logger().Info("revocation failed: server returned " + httpResponse.Status)
return nil, fmt.Errorf("revocation failed: server returned %s", httpResponse.Status)
}
alreadyRevoked := false
var revInfo revocationInfo
b.Logger().Debug("revocation request was successful.")
b.Logger().Debug("updating values if previously revoked..")
revEntry, err := fetchCertBySerial(ctx, req, "revoked/", serial)
if err != nil {
switch err.(type) {
case errutil.UserError:
return logical.ErrorResponse(err.Error()), nil
case errutil.InternalError:
return nil, err
}
}
if revEntry != nil {
// Set the revocation info to the existing values
alreadyRevoked = true
err = revEntry.DecodeJSON(&revInfo)
if err != nil {
return nil, fmt.Errorf("error decoding existing revocation info")
}
}
b.Logger().Debug("updating local storage entry..")
if !alreadyRevoked {
certEntry, err := fetchCertBySerial(ctx, req, "certs/", serial)
if err != nil {
switch err.(type) {
case errutil.UserError:
return logical.ErrorResponse(err.Error()), nil
case errutil.InternalError:
return nil, err
}
}
if certEntry == nil {
return logical.ErrorResponse(fmt.Sprintf("certificate with serial %s not found", serial)), nil
}
b.Logger().Debug("certEntry key = " + certEntry.Key)
b.Logger().Debug("certEntry value = " + string(certEntry.Value))
currTime := time.Now()
revInfo.CertificateBytes = certEntry.Value
revInfo.RevocationTime = currTime.Unix()
revInfo.RevocationTimeUTC = currTime.UTC()
revEntry, err = logical.StorageEntryJSON("revoked/"+normalizeSerial(serial), revInfo)
if err != nil {
return nil, fmt.Errorf("error creating revocation entry")
}
err = req.Storage.Put(ctx, revEntry)
if err != nil {
return nil, fmt.Errorf("error saving revoked certificate to new location")
}
}
resp := &logical.Response{
Data: map[string]interface{}{
"revocation_time": revInfo.RevocationTime,
},
}
if !revInfo.RevocationTimeUTC.IsZero() {
resp.Data["revocation_time_rfc3339"] = revInfo.RevocationTimeUTC.Format(time.RFC3339)
}
return resp, nil
}
// checkAllowedDomains verifies that every requested domain is permitted by the
// role. A domain is allowed when:
// - the role allows any domain ("*" in allowed_domains), or
// - it exactly matches one of the role's allowed_domains, or
// - the role allows subdomains and the domain is a proper subdomain of an
// allowed domain (i.e. ends with "."+allowed, guarding against matches like
// "evilexample.com" against "example.com").
func checkAllowedDomains(role *roleEntry, roleName string, domains []string) (bool, error) {
var disallowed []string
for _, d := range domains {
allowed := false
for _, v := range role.AllowedDomains {
if v == "*" {
allowed = true
break
}
if strings.EqualFold(d, v) { // exact match
allowed = true
break
}
if role.AllowSubdomains && strings.HasSuffix(strings.ToLower(d), "."+strings.ToLower(v)) {
allowed = true
break
}
}
if !allowed {
disallowed = append(disallowed, d)
}
}
if len(disallowed) > 0 {
return false, fmt.Errorf(
"domain name(s) not allowed for role %s: %s. allowed domains are: %s",
roleName,
strings.Join(disallowed, ","),
strings.Join(role.AllowedDomains, ","),
)
}
return true, nil
}
const pathIssueHelpSyn = `
Request a certificate using a certain role with the provided details.
example: vault write keyfactor/issue/<role> common_name=<cn> dns_sans=<dns sans>
`
const pathIssueHelpDesc = `
This path allows requesting a certificate to be issued according to the
policy of the given role. The certificate will only be issued if the
requested details are allowed by the role policy.
This path returns a certificate and a private key. If you want a workflow
that does not expose a private key, generate a CSR locally and use the
sign path instead.
`
const pathSignHelpSyn = `
Request certificates using a certain role with the provided details.
example: vault write keyfactor/sign/<role> csr=<csr>
`
const pathSignHelpDesc = `
This path allows requesting certificates to be issued according to the
policy of the given role. The certificate will only be issued if the
requested common name is allowed by the role policy.
This path requires a CSR; if you want Vault to generate a private key
for you, use the issue path instead.
Note: the CSR must contain at least one DNS SANs entry.
`
const pathFetchHelpSyn = `
Fetch a CA, CRL, CA Chain, or non-revoked certificate.
`
const pathFetchHelpDesc = `
This allows certificates to be fetched. If using the fetch/ prefix any non-revoked certificate can be fetched.
Using "ca" or "crl" as the value fetches the appropriate information in DER encoding. Add "/pem" to either to get PEM encoding.
Using "ca_chain" as the value fetches the certificate authority trust chain in PEM encoding.
`
const pathFetchListHelpSyn = `
List all of the certificates managed by this secrets engine.
`
const pathFetchListHelpDesc = `
Use with the "list" command to display the list of certificate serial numbers for certificates managed by this secrets engine.
`
const pathRevokeHelpSyn = `
Revoke a certificate by serial number.
`
const pathRevokeHelpDesc = `
This allows certificates to be revoked using its serial number. A root token is required.
`