-
Notifications
You must be signed in to change notification settings - Fork 9
/
path_venafi_policy.go
899 lines (779 loc) · 29.8 KB
/
path_venafi_policy.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
package pki
import (
"context"
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"encoding/json"
"fmt"
"github.com/Venafi/vcert/pkg/certificate"
"github.com/Venafi/vcert/pkg/endpoint"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
"log"
"strings"
)
const (
venafiRolePolicyMapStorage = "venafi-role-policy-map"
venafiPolicyPath = "venafi-policy/"
defaultVenafiPolicyName = "default"
policyFieldEnforcementRoles = "enforcement_roles"
policyFieldDefaultsRoles = "defaults_roles"
policyFieldImportRoles = "import_roles"
policyFieldCreateRole = "create_role"
venafiRolePolicyMapPath = "show-venafi-role-policy-map"
errPolicyMapDoesNotExists = "policy map does not exists"
)
func pathVenafiPolicy(b *backend) *framework.Path {
ret := &framework.Path{
Pattern: venafiPolicyPath + framework.GenericNameRegex("name"),
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "Name of the Venafi policy config",
},
"tpp_url": {
Type: framework.TypeString,
Description: `URL of Venafi Platform. Example: https://tpp.venafi.example/vedsdk`,
Required: true,
},
"zone": {
Type: framework.TypeString,
Description: `Name of Venafi Platform or Cloud policy.
Example for Platform: testpolicy\\vault
Example for Venafi Cloud: Default`,
Default: `Default`,
},
"tpp_user": {
Type: framework.TypeString,
Description: `web API user for Venafi Platform Example: admin`,
Required: true,
},
"tpp_password": {
Type: framework.TypeString,
Description: `Password for web API user Example: password`,
Required: true,
DisplayAttrs: &framework.DisplayAttributes{
Sensitive: true,
},
},
"trust_bundle_file": {
Type: framework.TypeString,
Description: `Use to specify a PEM formatted file with certificates to be used as trust anchors when communicating with the remote server.
Example:
trust_bundle_file = "/full/path/to/chain.pem""`,
},
"apikey": {
Type: framework.TypeString,
Description: `API key for Venafi Cloud. Example: 142231b7-cvb0-412e-886b-6aeght0bc93d`,
DisplayAttrs: &framework.DisplayAttributes{
Sensitive: true,
},
},
"cloud_url": {
Type: framework.TypeString,
Description: `URL for Venafi Cloud. Set it only if you want to use non production Cloud`,
},
"ext_key_usage": {
Type: framework.TypeCommaStringSlice,
Default: []string{},
Description: `A comma-separated string or list of allowed extended key usages. Valid values can be found at
https://golang.org/pkg/crypto/x509/#ExtKeyUsage
-- simply drop the "ExtKeyUsage" part of the name.
Also you can use constants from this module (like 1, 5,8) direct or use OIDs (like 1.3.6.1.5.5.7.3.4)`,
},
"auto_refresh_interval": {
Type: framework.TypeInt,
Default: 0,
Description: `Interval of policy update from Venafi in seconds. Set it to 0 to disable automatic policy update`,
},
policyFieldEnforcementRoles: {
Type: framework.TypeCommaStringSlice,
Default: []string{},
Description: "Roles list for policy check",
},
policyFieldDefaultsRoles: {
Type: framework.TypeCommaStringSlice,
Default: []string{},
Description: "Roles list for filing with default values from Venafi",
},
policyFieldImportRoles: {
Type: framework.TypeCommaStringSlice,
Default: []string{},
Description: "Roles list for import to Venafi",
},
"import_timeout": {
Type: framework.TypeInt,
Default: 15,
Description: `Timeout in second to rerun import queue`,
},
"import_workers": {
Type: framework.TypeInt,
Default: 5,
Description: `Max amount of simultaneously working instances of vcert import`,
},
policyFieldCreateRole: {
Type: framework.TypeBool,
Default: false,
Description: `Automatically create empty role for polic if it does not exists`,
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathUpdateVenafiPolicy,
logical.ReadOperation: b.pathReadVenafiPolicy,
logical.DeleteOperation: b.pathDeleteVenafiPolicy,
},
HelpSynopsis: pathVenafiPolicySyn,
HelpDescription: pathVenafiPolicyDesc,
}
return ret
}
func pathVenafiPolicyContent(b *backend) *framework.Path {
ret := &framework.Path{
Pattern: venafiPolicyPath + framework.GenericNameRegex("name") + "/policy",
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "Name of the Venafi policy config",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: b.pathReadVenafiPolicyContent,
logical.UpdateOperation: b.pathUpdateVenafiPolicyContent,
},
HelpSynopsis: pathVenafiPolicySyn,
HelpDescription: pathVenafiPolicyDesc,
}
return ret
}
func pathVenafiPolicyList(b *backend) *framework.Path {
ret := &framework.Path{
Pattern: venafiPolicyPath,
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ListOperation: b.pathListVenafiPolicy,
},
HelpSynopsis: pathImportQueueSyn,
HelpDescription: pathImportQueueDesc,
}
return ret
}
func pathVenafiPolicyMap(b *backend) *framework.Path {
ret := &framework.Path{
Pattern: venafiRolePolicyMapPath,
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: b.pathShowVenafiPolicyMap,
},
HelpSynopsis: pathImportQueueSyn,
HelpDescription: pathImportQueueDesc,
}
return ret
}
func (b *backend) refreshVenafiPolicyEnforcementContent(storage logical.Storage, policyName string) (err error) {
ctx := context.Background()
venafiPolicyConfig, err := b.getVenafiPolicyConfig(ctx, storage, policyName)
if err != nil {
return fmt.Errorf("Error getting policy config %s: %s", policyName, err)
}
if venafiPolicyConfig == nil {
return fmt.Errorf("Policy config for %s is empty", policyName)
}
if venafiPolicyConfig.AutoRefreshInterval > 0 {
log.Printf("%s Auto refresh enabled for policy %s. Getting policy from Venafi", logPrefixVenafiPolicyEnforcement, policyName)
} else {
return nil
}
policy, err := b.getPolicyFromVenafi(ctx, storage, policyName)
if err != nil {
return fmt.Errorf("Error getting policy %s from Venafi: %s", policyName, err)
}
log.Printf("%s Saving policy %s", logPrefixVenafiPolicyEnforcement, policyName)
_, err = savePolicyEntry(policy, policyName, ctx, storage)
if err != nil {
return fmt.Errorf("%s Error saving policy: %s", logPrefixVenafiPolicyEnforcement, err)
}
jsonEntry, err := logical.StorageEntryJSON(venafiPolicyPath+policyName, venafiPolicyConfig)
if err != nil {
return fmt.Errorf("%s Error converting policy config into JSON: %s", logPrefixVenafiPolicyEnforcement, err)
}
if err := storage.Put(ctx, jsonEntry); err != nil {
return fmt.Errorf("Error saving policy last update time: %s", err)
}
return nil
}
func (b *backend) pathReadVenafiPolicyContent(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
name := data.Get("name").(string)
log.Printf("%s Trying to read policy for config %s", logPrefixVenafiPolicyEnforcement, name)
if len(name) == 0 {
return logical.ErrorResponse("Non config specified or wrong config path name"), nil
}
entry, err := req.Storage.Get(ctx, venafiPolicyPath+name+"/policy")
if err != nil {
return nil, err
}
if entry == nil {
return logical.ErrorResponse("policy data is nil. Looks like it doesn't exists."), nil
}
var policy venafiPolicyEntry
if err := entry.DecodeJSON(&policy); err != nil {
log.Printf("%s error reading Venafi policy configuration: %s", logPrefixVenafiPolicyEnforcement, err)
return nil, err
}
//Send policy to the user output
respData := formPolicyRespData(policy)
return &logical.Response{
Data: respData,
}, nil
}
func (b *backend) pathUpdateVenafiPolicyContent(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
name := data.Get("name").(string)
policy, err := b.getPolicyFromVenafi(ctx, req.Storage, name)
if err != nil {
return nil, err
}
policyEntry, err := savePolicyEntry(policy, name, ctx, req.Storage)
if err != nil {
return nil, err
}
respData := formPolicyRespData(*policyEntry)
return &logical.Response{
Data: respData,
}, nil
}
func (b *backend) pathUpdateVenafiPolicy(ctx context.Context, req *logical.Request, data *framework.FieldData) (response *logical.Response, err error) {
name := data.Get("name").(string)
log.Printf("%s Write policy endpoint configuration into storage", logPrefixVenafiPolicyEnforcement)
venafiPolicyConfig := &venafiPolicyConfigEntry{
venafiConnectionConfig: venafiConnectionConfig{
TPPURL: data.Get("tpp_url").(string),
CloudURL: data.Get("cloud_url").(string),
Zone: data.Get("zone").(string),
TPPPassword: data.Get("tpp_password").(string),
Apikey: data.Get("apikey").(string),
TPPUser: data.Get("tpp_user").(string),
TrustBundleFile: data.Get("trust_bundle_file").(string),
},
AutoRefreshInterval: int64(data.Get("auto_refresh_interval").(int)),
VenafiImportTimeout: data.Get("import_timeout").(int),
VenafiImportWorkers: data.Get("import_workers").(int),
CreateRole: data.Get(policyFieldCreateRole).(bool),
}
unparsedKeyUsage := data.Get("ext_key_usage").([]string)
venafiPolicyConfig.ExtKeyUsage, err = parseExtKeyUsageParameter(unparsedKeyUsage)
if err != nil {
return
}
if venafiPolicyConfig.Apikey == "" && (venafiPolicyConfig.TPPURL == "" || venafiPolicyConfig.TPPUser == "" || venafiPolicyConfig.TPPPassword == "") {
return logical.ErrorResponse("Invalid mode. apikey or tpp credentials required"), nil
}
jsonEntry, err := logical.StorageEntryJSON(venafiPolicyPath+name, venafiPolicyConfig)
if err != nil {
return nil, err
}
if err := req.Storage.Put(ctx, jsonEntry); err != nil {
return nil, err
}
log.Printf("%s Geting policy from zone %s", logPrefixVenafiPolicyEnforcement, data.Get("zone").(string))
policy, err := b.getPolicyFromVenafi(ctx, req.Storage, name)
if err != nil {
return nil, err
}
policyEntry, err := savePolicyEntry(policy, name, ctx, req.Storage)
if err != nil {
return nil, err
}
log.Printf("%s Updating roles policy attributes", logPrefixVenafiPolicyEnforcement)
err = b.updateRolesPolicyAttributes(ctx, req, data, name)
if err != nil {
return nil, err
}
//Send policy to the user output
respData := formPolicyRespData(*policyEntry)
return &logical.Response{
Data: respData,
}, nil
}
type policyTypes struct {
ImportPolicy string `json:"import_policy"`
DefaultsPolicy string `json:"defaults_policy"`
EnforcementPolicy string `json:"enforcement_policy"`
}
type policyRoleMap struct {
Roles map[string]policyTypes `json:"roles"`
}
func getPolicyRoleMap(ctx context.Context, storage logical.Storage) (policyMap policyRoleMap, err error) {
//TODO: write test for it
policyMap.Roles = make(map[string]policyTypes)
entry, err := storage.Get(ctx, venafiRolePolicyMapStorage)
if err != nil {
return policyMap, err
}
if entry == nil {
return policyMap, fmt.Errorf(errPolicyMapDoesNotExists)
}
err = json.Unmarshal(entry.Value, &policyMap)
if err != nil {
return policyMap, err
}
return policyMap, err
}
func (b *backend) updateRolesPolicyAttributes(ctx context.Context, req *logical.Request, data *framework.FieldData, name string) error {
//TODO: write test for it
policyMap, err := getPolicyRoleMap(ctx, req.Storage)
if err != nil {
if err.Error() == errPolicyMapDoesNotExists {
log.Println(errPolicyMapDoesNotExists + " will create new")
} else {
return err
}
}
for _, roleType := range []string{policyFieldEnforcementRoles, policyFieldDefaultsRoles, policyFieldImportRoles} {
for _, roleName := range data.Get(roleType).([]string) {
role, err := b.getRole(ctx, req.Storage, roleName)
if err != nil {
return err
}
if role == nil {
if data.Get(policyFieldCreateRole).(bool) {
return fmt.Errorf("role %s does not exists. can not add it to the attributes of policy %s", roleName, name)
} else {
//TODO: create role here
log.Println("Creating role", roleName)
}
}
r := policyTypes{}
//copy policy values before setting new value
r.EnforcementPolicy = policyMap.Roles[roleName].EnforcementPolicy
r.DefaultsPolicy = policyMap.Roles[roleName].DefaultsPolicy
r.ImportPolicy = policyMap.Roles[roleName].ImportPolicy
switch roleType {
case policyFieldEnforcementRoles:
r.EnforcementPolicy = name
case policyFieldDefaultsRoles:
r.DefaultsPolicy = name
case policyFieldImportRoles:
r.ImportPolicy = name
}
policyMap.Roles[roleName] = r
jsonEntry, err := logical.StorageEntryJSON("role/"+roleName, role)
if err != nil {
return err
}
if err := req.Storage.Put(ctx, jsonEntry); err != nil {
return err
}
}
}
jsonEntry, err := logical.StorageEntryJSON(venafiRolePolicyMapStorage, policyMap)
if err != nil {
return err
}
if err := req.Storage.Put(ctx, jsonEntry); err != nil {
return err
}
return nil
}
func savePolicyEntry(policy *endpoint.Policy, name string, ctx context.Context, storage logical.Storage) (policyEntry *venafiPolicyEntry, err error) {
//Form policy entry for storage
policyEntry = &venafiPolicyEntry{
SubjectCNRegexes: policy.SubjectCNRegexes,
SubjectORegexes: policy.SubjectORegexes,
SubjectOURegexes: policy.SubjectOURegexes,
SubjectSTRegexes: policy.SubjectSTRegexes,
SubjectLRegexes: policy.SubjectLRegexes,
SubjectCRegexes: policy.SubjectCRegexes,
AllowedKeyConfigurations: policy.AllowedKeyConfigurations,
DnsSanRegExs: policy.DnsSanRegExs,
IpSanRegExs: policy.IpSanRegExs,
EmailSanRegExs: policy.EmailSanRegExs,
UriSanRegExs: policy.UriSanRegExs,
UpnSanRegExs: policy.UpnSanRegExs,
AllowWildcards: policy.AllowWildcards,
AllowKeyReuse: policy.AllowKeyReuse,
}
log.Printf("%s Saving policy into Vault storage", logPrefixVenafiPolicyEnforcement)
jsonEntry, err := logical.StorageEntryJSON(venafiPolicyPath+name+"/policy", policyEntry)
if err != nil {
return nil, err
}
if err := storage.Put(ctx, jsonEntry); err != nil {
return nil, err
}
return policyEntry, nil
}
func formPolicyRespData(policy venafiPolicyEntry) (respData map[string]interface{}) {
type printKeyConfig struct {
KeyType string
KeySizes []int `json:",omitempty"`
KeyCurves []string `json:",omitempty"`
}
keyConfigs := make([]string, len(policy.AllowedKeyConfigurations))
for i, akc := range policy.AllowedKeyConfigurations {
kc := printKeyConfig{akc.KeyType.String(), akc.KeySizes, nil}
if akc.KeyType == certificate.KeyTypeECDSA {
kc.KeyCurves = make([]string, len(akc.KeyCurves))
for i, c := range akc.KeyCurves {
kc.KeyCurves[i] = c.String()
}
}
kb, _ := json.Marshal(kc)
keyConfigs[i] = string(kb)
}
return map[string]interface{}{
"subject_cn_regexes": policy.SubjectCNRegexes,
"subject_o_regexes": policy.SubjectORegexes,
"subject_ou_regexes": policy.SubjectOURegexes,
"subject_st_regexes": policy.SubjectSTRegexes,
"subject_l_regexes": policy.SubjectLRegexes,
"subject_c_regexes": policy.SubjectCRegexes,
"allowed_key_configurations": keyConfigs,
"dns_san_regexes": policy.DnsSanRegExs,
"ip_san_regexes": policy.IpSanRegExs,
"email_san_regexes": policy.EmailSanRegExs,
"uri_san_regexes": policy.UriSanRegExs,
"upn_san_regexes": policy.UpnSanRegExs,
"allow_wildcards": policy.AllowWildcards,
"allow_key_reuse": policy.AllowKeyReuse,
}
}
func (b *backend) getPolicyFromVenafi(ctx context.Context, storage logical.Storage, policyConfig string) (policy *endpoint.Policy, err error) {
log.Printf("%s Creating Venafi client", logPrefixVenafiPolicyEnforcement)
cl, err := b.ClientVenafi(ctx, storage, policyConfig)
if err != nil {
return
}
log.Printf("%s Getting policy from Venafi endpoint", logPrefixVenafiPolicyEnforcement)
policy, err = cl.ReadPolicyConfiguration()
if err != nil {
return
}
if policy == nil {
err = fmt.Errorf("expected policy but got nil from Venafi endpoint %v", policy)
return
}
return
}
func (b *backend) pathReadVenafiPolicy(ctx context.Context, req *logical.Request, data *framework.FieldData) (response *logical.Response, retErr error) {
name := data.Get("name").(string)
log.Printf("%s Trying to read policy for config %s", logPrefixVenafiPolicyEnforcement, name)
if len(name) == 0 {
return logical.ErrorResponse("No config specified or wrong config path name"), nil
}
entry, err := req.Storage.Get(ctx, venafiPolicyPath+name)
if err != nil {
return nil, err
}
if entry == nil {
return logical.ErrorResponse("policy config is nil. Looks like it doesn't exists."), nil
}
var config venafiPolicyConfigEntry
if err := entry.DecodeJSON(&config); err != nil {
log.Printf("%s error reading Venafi policy configuration: %s", logPrefixVenafiPolicyEnforcement, err)
return nil, err
}
rolesList, err := b.getRolesListForVenafiPolicy(ctx, req.Storage, name)
if err != nil {
return nil, err
}
//Send config to the user output
respData := map[string]interface{}{
"tpp_url": config.TPPURL,
"zone": config.Zone,
"tpp_user": config.TPPUser,
"trust_bundle_file": config.TrustBundleFile,
"cloud_url": config.CloudURL,
policyFieldImportRoles: rolesList.importRoles,
policyFieldDefaultsRoles: rolesList.defaultsRoles,
policyFieldEnforcementRoles: rolesList.enforceRoles,
"auto_refresh_interval": config.AutoRefreshInterval,
"last_policy_update_time": config.LastPolicyUpdateTime,
"import_timeout": config.VenafiImportTimeout,
"import_workers": config.VenafiImportWorkers,
"create_role": config.CreateRole,
}
return &logical.Response{
Data: respData,
}, nil
}
type rolesListForVenafiPolicy struct {
importRoles []string
enforceRoles []string
defaultsRoles []string
}
func (b *backend) getRolesListForVenafiPolicy(ctx context.Context, storage logical.Storage, policyName string) (rolesList rolesListForVenafiPolicy, err error) {
//In this function we're getting a role list for Venafi policy.
//Each role have three hidden attributes: VenafiImportPolicy, VenafiEnforcementPolicy and VenafiDefaultsPolicy
roles, err := storage.List(ctx, "role/")
if err != nil {
return
}
policyMap, err := getPolicyRoleMap(ctx, storage)
if err != nil {
return
}
for _, roleName := range roles {
//If policy name is in one of role policy attributes append it to the roleList structure
if policyMap.Roles[roleName].ImportPolicy == policyName {
rolesList.importRoles = append(rolesList.importRoles, roleName)
}
if policyMap.Roles[roleName].EnforcementPolicy == policyName {
rolesList.enforceRoles = append(rolesList.enforceRoles, roleName)
}
if policyMap.Roles[roleName].DefaultsPolicy == policyName {
rolesList.defaultsRoles = append(rolesList.defaultsRoles, roleName)
}
}
return rolesList, err
}
func (b *backend) pathDeleteVenafiPolicy(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
var err error
name := data.Get("name").(string)
rawEntry, err := req.Storage.List(ctx, venafiPolicyPath+name+"/")
if err != nil {
return nil, err
}
//Deleting all content of the policy
for _, e := range rawEntry {
err = req.Storage.Delete(ctx, venafiPolicyPath+name+"/"+e)
if err != nil {
return nil, err
}
}
//Deleting policy path
err = req.Storage.Delete(ctx, venafiPolicyPath+name)
if err != nil {
return nil, err
}
return nil, nil
}
func (b *backend) pathListVenafiPolicy(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
policies, err := req.Storage.List(ctx, venafiPolicyPath)
var entries []string
if err != nil {
return nil, err
}
for _, policy := range policies {
//Removing from policy list repeated policy name with / at the end
if !strings.Contains(policy, "/") {
entries = append(entries, policy)
}
}
return logical.ListResponse(entries), nil
}
func (b *backend) pathShowVenafiPolicyMap(ctx context.Context, req *logical.Request, data *framework.FieldData) (response *logical.Response, err error) {
//TODO: test it!
entry, err := req.Storage.Get(ctx, venafiRolePolicyMapStorage)
if err != nil {
return nil, err
}
response = &logical.Response{
Data: map[string]interface{}{},
}
response.Data["policy_map_json"] = entry.Value
return response, nil
}
func checkAgainstVenafiPolicy(
req *logical.Request,
role *roleEntry,
isCA bool,
csr *x509.CertificateRequest,
cn string,
ipAddresses, email, sans []string) error {
ctx := context.Background()
policyMap, err := getPolicyRoleMap(ctx, req.Storage)
if err != nil {
return err
}
venafiEnforcementPolicy := policyMap.Roles[role.Name].EnforcementPolicy
if venafiEnforcementPolicy == "" {
venafiEnforcementPolicy = defaultVenafiPolicyName
}
entry, err := req.Storage.Get(ctx, venafiPolicyPath+venafiEnforcementPolicy+"/policy")
if err != nil {
return err
}
if entry == nil {
if venafiPolicyDenyAll {
//TODO: Can not understand why I added this if here. Probably should be removed
//if strings.Contains(req.Path, "root/generate") {
// log.Println("policy data is nil. You need configure Venafi policy to proceed")
//}
return fmt.Errorf("policy data is nil. You need configure Venafi policy to proceed")
} else {
return nil
}
}
var policy venafiPolicyEntry
if err := entry.DecodeJSON(&policy); err != nil {
log.Printf("%s error reading Venafi policy configuration: %s", logPrefixVenafiPolicyEnforcement, err)
return err
}
entry, err = req.Storage.Get(ctx, venafiPolicyPath+venafiEnforcementPolicy)
if err != nil {
return err
}
var policyConfig venafiPolicyConfigEntry
if err := entry.DecodeJSON(&policyConfig); err != nil {
log.Printf("%s error reading Venafi policy configuration: %s", logPrefixVenafiPolicyEnforcement, err)
return err
}
if csr != nil {
log.Printf("%s Checking CSR against policy %s", logPrefixVenafiPolicyEnforcement, venafiEnforcementPolicy)
if isCA {
if len(csr.EmailAddresses) != 0 || len(csr.DNSNames) != 0 || len(csr.IPAddresses) != 0 || len(csr.URIs) != 0 {
//workaround for setting SAN if CA have normal domain in CN
if csr.DNSNames[0] != csr.Subject.CommonName {
return fmt.Errorf("CA doesn`t allowed to have any SANs: %v, %v, %v, %v", csr.EmailAddresses, csr.DNSNames, csr.IPAddresses, csr.URIs)
}
}
} else {
if !checkStringByRegexp(csr.Subject.CommonName, policy.SubjectCNRegexes) {
return fmt.Errorf("common name %s doesn't match regexps: %v", cn, policy.SubjectCNRegexes)
}
if !checkStringArrByRegexp(csr.EmailAddresses, policy.EmailSanRegExs, true) {
return fmt.Errorf("emails %v doesn't match regexps: %v", email, policy.EmailSanRegExs)
}
if !checkStringArrByRegexp(csr.DNSNames, policy.DnsSanRegExs, true) {
return fmt.Errorf("DNS sans %v doesn't match regexps: %v", csr.DNSNames, policy.DnsSanRegExs)
}
ips := make([]string, len(csr.IPAddresses))
for i, ip := range csr.IPAddresses {
ips[i] = ip.String()
}
if !checkStringArrByRegexp(ips, policy.IpSanRegExs, true) {
return fmt.Errorf("IPs %v doesn't match regexps: %v", ipAddresses, policy.IpSanRegExs)
}
uris := make([]string, len(csr.URIs))
for i, uri := range csr.URIs {
uris[i] = uri.String()
}
if !checkStringArrByRegexp(uris, policy.UriSanRegExs, true) {
return fmt.Errorf("URIs %v doesn't match regexps: %v", uris, policy.UriSanRegExs)
}
}
if !checkStringArrByRegexp(csr.Subject.Organization, policy.SubjectORegexes, false) {
return fmt.Errorf("Organization %v doesn't match regexps: %v", role.Organization, policy.SubjectORegexes)
}
if !checkStringArrByRegexp(csr.Subject.OrganizationalUnit, policy.SubjectOURegexes, false) {
return fmt.Errorf("Organization Unit %v doesn't match regexps: %v", csr.Subject.OrganizationalUnit, policy.SubjectOURegexes)
}
if !checkStringArrByRegexp(csr.Subject.Country, policy.SubjectCRegexes, false) {
return fmt.Errorf("Country %v doesn't match regexps: %v", csr.Subject.Country, policy.SubjectCRegexes)
}
if !checkStringArrByRegexp(csr.Subject.Locality, policy.SubjectLRegexes, false) {
return fmt.Errorf("Location %v doesn't match regexps: %v", csr.Subject.Locality, policy.SubjectLRegexes)
}
if !checkStringArrByRegexp(csr.Subject.Province, policy.SubjectSTRegexes, false) {
return fmt.Errorf("State (Province) %v doesn't match regexps: %v", csr.Subject.Province, policy.SubjectSTRegexes)
}
keyValid := true
if csr.PublicKeyAlgorithm == x509.RSA {
pubkey, ok := csr.PublicKey.(*rsa.PublicKey)
if ok {
keyValid = checkKey("rsa", pubkey.Size()*8, "", policy.AllowedKeyConfigurations)
} else {
log.Printf("%s invalid key in csr", logPrefixVenafiPolicyEnforcement)
}
} else if csr.PublicKeyAlgorithm == x509.ECDSA {
pubkey, ok := csr.PublicKey.(*ecdsa.PublicKey)
if ok {
keyValid = checkKey("ecdsa", 0, pubkey.Curve.Params().Name, policy.AllowedKeyConfigurations)
}
}
if !keyValid {
return fmt.Errorf("key type not compatible vith Venafi policies")
}
} else {
log.Printf("%s Checking creation bundle against policy %s", logPrefixVenafiPolicyEnforcement, venafiEnforcementPolicy)
if isCA {
if len(email) != 0 || len(sans) != 0 || len(ipAddresses) != 0 {
//workaround for setting SAN if CA have normal domain in CN
if sans[0] != cn {
return fmt.Errorf("CA doesn`t allowed to have any SANs: %v, %v, %v", email, sans, ipAddresses)
}
}
} else {
if !checkStringByRegexp(cn, policy.SubjectCNRegexes) {
return fmt.Errorf("common name %s doesn't match regexps: %v", cn, policy.SubjectCNRegexes)
}
if !checkStringArrByRegexp(email, policy.EmailSanRegExs, true) {
return fmt.Errorf("emails %v doesn't match regexps: %v", email, policy.EmailSanRegExs)
}
if !checkStringArrByRegexp(sans, policy.DnsSanRegExs, true) {
return fmt.Errorf("DNS sans %v doesn't match regexps: %v", sans, policy.DnsSanRegExs)
}
if !checkStringArrByRegexp(ipAddresses, policy.IpSanRegExs, true) {
return fmt.Errorf("IPs %v doesn't match regexps: %v", ipAddresses, policy.IpSanRegExs)
}
}
if !checkStringArrByRegexp(role.Organization, policy.SubjectORegexes, false) {
return fmt.Errorf("Organization %v doesn't match regexps: %v", role.Organization, policy.SubjectORegexes)
}
if !checkStringArrByRegexp(role.OU, policy.SubjectOURegexes, false) {
return fmt.Errorf("Organization Unit %v doesn't match regexps: %v", role.OU, policy.SubjectOURegexes)
}
if !checkStringArrByRegexp(role.Country, policy.SubjectCRegexes, false) {
return fmt.Errorf("Country %v doesn't match regexps: %v", role.Country, policy.SubjectCRegexes)
}
if !checkStringArrByRegexp(role.Locality, policy.SubjectLRegexes, false) {
return fmt.Errorf("Location %v doesn't match regexps: %v", role.Locality, policy.SubjectLRegexes)
}
if !checkStringArrByRegexp(role.Province, policy.SubjectSTRegexes, false) {
return fmt.Errorf("State (Province) %v doesn't match regexps: %v", role.Province, policy.SubjectSTRegexes)
}
if !checkKey(role.KeyType, role.KeyBits, ecdsaCurvesSizesToName(role.KeyBits), policy.AllowedKeyConfigurations) {
return fmt.Errorf("key type not compatible vith Venafi policies")
}
}
//TODO: check against upn_san_regexes
extKeyUsage, err := parseExtKeyUsageParameter(role.ExtKeyUsage)
if err != nil {
return err
}
if !isCA {
if !compareEkuList(extKeyUsage, policyConfig.ExtKeyUsage) {
return fmt.Errorf("different eku in Venafi policy config and role")
}
}
return nil
}
func (b *backend) getVenafiPolicyConfig(ctx context.Context, s logical.Storage, n string) (*venafiPolicyConfigEntry, error) {
entry, err := s.Get(ctx, venafiPolicyPath+n)
if err != nil {
return nil, err
}
if entry == nil {
return nil, nil
}
var result venafiPolicyConfigEntry
if err := entry.DecodeJSON(&result); err != nil {
return nil, err
}
return &result, nil
}
type venafiPolicyConfigEntry struct {
venafiConnectionConfig
ExtKeyUsage []x509.ExtKeyUsage `json:"ext_key_usage"`
AutoRefreshInterval int64 `json:"auto_refresh_interval"`
LastPolicyUpdateTime int64 `json:"last_policy_update_time"`
VenafiImportTimeout int `json:"import_timeout"`
VenafiImportWorkers int `json:"import_workers"`
CreateRole bool `json:"create_role"`
}
type venafiPolicyEntry struct {
SubjectCNRegexes []string `json:"subject_cn_regexes"`
SubjectORegexes []string `json:"subject_o_regexes"`
SubjectOURegexes []string `json:"subject_ou_regexes"`
SubjectSTRegexes []string `json:"subject_st_regexes"`
SubjectLRegexes []string `json:"subject_l_regexes"`
SubjectCRegexes []string `json:"subject_c_regexes"`
AllowedKeyConfigurations []endpoint.AllowedKeyConfiguration `json:"allowed_key_configurations"`
DnsSanRegExs []string `json:"dns_san_regexes"`
IpSanRegExs []string `json:"ip_san_regexes"`
EmailSanRegExs []string `json:"email_san_regexes"`
UriSanRegExs []string `json:"uri_san_regexes"`
UpnSanRegExs []string `json:"upn_san_regexes"`
AllowWildcards bool `json:"allow_wildcards"`
AllowKeyReuse bool `json:"allow_key_reuse"`
}
const pathVenafiPolicySyn = `help here`
const pathVenafiPolicyDesc = `description here`