forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 1
/
path_roles.go
578 lines (514 loc) · 18.6 KB
/
path_roles.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
package pki
import (
"crypto/x509"
"fmt"
"strings"
"time"
"github.com/hashicorp/vault/helper/parseutil"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
)
func pathListRoles(b *backend) *framework.Path {
return &framework.Path{
Pattern: "roles/?$",
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ListOperation: b.pathRoleList,
},
HelpSynopsis: pathListRolesHelpSyn,
HelpDescription: pathListRolesHelpDesc,
}
}
func pathRoles(b *backend) *framework.Path {
return &framework.Path{
Pattern: "roles/" + framework.GenericNameRegex("name"),
Fields: map[string]*framework.FieldSchema{
"name": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Name of the role",
},
"ttl": &framework.FieldSchema{
Type: framework.TypeDurationSecond,
Default: "",
Description: `The lease duration if no specific lease duration is
requested. The lease duration controls the expiration
of certificates issued by this backend. Defaults to
the value of max_ttl.`,
},
"max_ttl": &framework.FieldSchema{
Type: framework.TypeString,
Default: "",
Description: "The maximum allowed lease duration",
},
"allow_localhost": &framework.FieldSchema{
Type: framework.TypeBool,
Default: true,
Description: `Whether to allow "localhost" as a valid common
name in a request`,
},
"allowed_domains": &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Description: `If set, clients can request certificates for
subdomains directly beneath these domains, including
the wildcard subdomains. See the documentation for more
information. This parameter accepts a comma-separated
string or list of domains.`,
},
"allow_bare_domains": &framework.FieldSchema{
Type: framework.TypeBool,
Default: false,
Description: `If set, clients can request certificates
for the base domains themselves, e.g. "example.com".
This is a separate option as in some cases this can
be considered a security threat.`,
},
"allow_subdomains": &framework.FieldSchema{
Type: framework.TypeBool,
Default: false,
Description: `If set, clients can request certificates for
subdomains of the CNs allowed by the other role options,
including wildcard subdomains. See the documentation for
more information.`,
},
"allow_glob_domains": &framework.FieldSchema{
Type: framework.TypeBool,
Default: false,
Description: `If set, domains specified in "allowed_domains"
can include glob patterns, e.g. "ftp*.example.com". See
the documentation for more information.`,
},
"allow_any_name": &framework.FieldSchema{
Type: framework.TypeBool,
Default: false,
Description: `If set, clients can request certificates for
any CN they like. See the documentation for more
information.`,
},
"enforce_hostnames": &framework.FieldSchema{
Type: framework.TypeBool,
Default: true,
Description: `If set, only valid host names are allowed for
CN and SANs. Defaults to true.`,
},
"allow_ip_sans": &framework.FieldSchema{
Type: framework.TypeBool,
Default: true,
Description: `If set, IP Subject Alternative Names are allowed.
Any valid IP is accepted.`,
},
"server_flag": &framework.FieldSchema{
Type: framework.TypeBool,
Default: true,
Description: `If set, certificates are flagged for server auth use.
Defaults to true.`,
},
"client_flag": &framework.FieldSchema{
Type: framework.TypeBool,
Default: true,
Description: `If set, certificates are flagged for client auth use.
Defaults to true.`,
},
"code_signing_flag": &framework.FieldSchema{
Type: framework.TypeBool,
Default: false,
Description: `If set, certificates are flagged for code signing
use. Defaults to false.`,
},
"email_protection_flag": &framework.FieldSchema{
Type: framework.TypeBool,
Default: false,
Description: `If set, certificates are flagged for email
protection use. Defaults to false.`,
},
"key_type": &framework.FieldSchema{
Type: framework.TypeString,
Default: "rsa",
Description: `The type of key to use; defaults to RSA. "rsa"
and "ec" are the only valid values.`,
},
"key_bits": &framework.FieldSchema{
Type: framework.TypeInt,
Default: 2048,
Description: `The number of bits to use. You will almost
certainly want to change this if you adjust
the key_type.`,
},
"key_usage": &framework.FieldSchema{
Type: framework.TypeCommaStringSlice,
Default: []string{"DigitalSignature", "KeyAgreement", "KeyEncipherment"},
Description: `A comma-separated string or list of key usages (not extended
key usages). Valid values can be found at
https://golang.org/pkg/crypto/x509/#KeyUsage
-- simply drop the "KeyUsage" part of the name.
To remove all key usages from being set, set
this value to an empty list.`,
},
"use_csr_common_name": &framework.FieldSchema{
Type: framework.TypeBool,
Default: true,
Description: `If set, when used with a signing profile,
the common name in the CSR will be used. This
does *not* include any requested Subject Alternative
Names. Defaults to true.`,
},
"use_csr_sans": &framework.FieldSchema{
Type: framework.TypeBool,
Default: true,
Description: `If set, when used with a signing profile,
the SANs in the CSR will be used. This does *not*
include the Common Name (cn). Defaults to true.`,
},
"ou": &framework.FieldSchema{
Type: framework.TypeString,
Default: "",
Description: `If set, the OU (OrganizationalUnit) will be set to
this value in certificates issued by this role.`,
},
"organization": &framework.FieldSchema{
Type: framework.TypeString,
Default: "",
Description: `If set, the O (Organization) will be set to
this value in certificates issued by this role.`,
},
"generate_lease": &framework.FieldSchema{
Type: framework.TypeBool,
Default: false,
Description: `
If set, certificates issued/signed against this role will have Vault leases
attached to them. Defaults to "false". Certificates can be added to the CRL by
"vault revoke <lease_id>" when certificates are associated with leases. It can
also be done using the "pki/revoke" endpoint. However, when lease generation is
disabled, invoking "pki/revoke" would be the only way to add the certificates
to the CRL. When large number of certificates are generated with long
lifetimes, it is recommended that lease generation be disabled, as large amount of
leases adversely affect the startup time of Vault.`,
},
"no_store": &framework.FieldSchema{
Type: framework.TypeBool,
Default: false,
Description: `
If set, certificates issued/signed against this role will not be stored in the
storage backend. This can improve performance when issuing large numbers of
certificates. However, certificates issued in this way cannot be enumerated
or revoked, so this option is recommended only for certificates that are
non-sensitive, or extremely short-lived. This option implies a value of "false"
for "generate_lease".`,
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: b.pathRoleRead,
logical.UpdateOperation: b.pathRoleCreate,
logical.DeleteOperation: b.pathRoleDelete,
},
HelpSynopsis: pathRoleHelpSyn,
HelpDescription: pathRoleHelpDesc,
}
}
func (b *backend) getRole(s logical.Storage, n string) (*roleEntry, error) {
entry, err := s.Get("role/" + n)
if err != nil {
return nil, err
}
if entry == nil {
return nil, nil
}
var result roleEntry
if err := entry.DecodeJSON(&result); err != nil {
return nil, err
}
// Migrate existing saved entries and save back if changed
modified := false
if len(result.TTL) == 0 && len(result.Lease) != 0 {
result.TTL = result.Lease
result.Lease = ""
modified = true
}
if len(result.MaxTTL) == 0 && len(result.LeaseMax) != 0 {
result.MaxTTL = result.LeaseMax
result.LeaseMax = ""
modified = true
}
if result.AllowBaseDomain {
result.AllowBaseDomain = false
result.AllowBareDomains = true
modified = true
}
if result.AllowedDomainsOld != "" {
result.AllowedDomains = strings.Split(result.AllowedDomainsOld, ",")
result.AllowedDomainsOld = ""
modified = true
}
if result.AllowedBaseDomain != "" {
found := false
for _, v := range result.AllowedDomains {
if v == result.AllowedBaseDomain {
found = true
break
}
}
if !found {
result.AllowedDomains = append(result.AllowedDomains, result.AllowedBaseDomain)
}
result.AllowedBaseDomain = ""
modified = true
}
// Upgrade generate_lease in role
if result.GenerateLease == nil {
// All the new roles will have GenerateLease always set to a value. A
// nil value indicates that this role needs an upgrade. Set it to
// `true` to not alter its current behavior.
result.GenerateLease = new(bool)
*result.GenerateLease = true
modified = true
}
// Upgrade key usages
if result.KeyUsageOld != "" {
result.KeyUsage = strings.Split(result.KeyUsageOld, ",")
result.KeyUsageOld = ""
modified = true
}
if modified {
jsonEntry, err := logical.StorageEntryJSON("role/"+n, &result)
if err != nil {
return nil, err
}
if err := s.Put(jsonEntry); err != nil {
// Only perform upgrades on replication primary
if !strings.Contains(err.Error(), logical.ErrReadOnly.Error()) {
return nil, err
}
}
}
return &result, nil
}
func (b *backend) pathRoleDelete(
req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
err := req.Storage.Delete("role/" + data.Get("name").(string))
if err != nil {
return nil, err
}
return nil, nil
}
func (b *backend) pathRoleRead(
req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := data.Get("name").(string)
if roleName == "" {
return logical.ErrorResponse("missing role name"), nil
}
role, err := b.getRole(req.Storage, roleName)
if err != nil {
return nil, err
}
if role == nil {
return nil, nil
}
hasMax := true
if len(role.MaxTTL) == 0 {
role.MaxTTL = "(system default)"
hasMax = false
}
if len(role.TTL) == 0 {
if hasMax {
role.TTL = "(system default, capped to role max)"
} else {
role.TTL = "(system default)"
}
}
resp := &logical.Response{
Data: role.ToResponseData(),
}
return resp, nil
}
func (b *backend) pathRoleList(
req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
entries, err := req.Storage.List("role/")
if err != nil {
return nil, err
}
return logical.ListResponse(entries), nil
}
func (b *backend) pathRoleCreate(
req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
var err error
name := data.Get("name").(string)
entry := &roleEntry{
MaxTTL: data.Get("max_ttl").(string),
TTL: (time.Duration(data.Get("ttl").(int)) * time.Second).String(),
AllowLocalhost: data.Get("allow_localhost").(bool),
AllowedDomains: data.Get("allowed_domains").([]string),
AllowBareDomains: data.Get("allow_bare_domains").(bool),
AllowSubdomains: data.Get("allow_subdomains").(bool),
AllowGlobDomains: data.Get("allow_glob_domains").(bool),
AllowAnyName: data.Get("allow_any_name").(bool),
EnforceHostnames: data.Get("enforce_hostnames").(bool),
AllowIPSANs: data.Get("allow_ip_sans").(bool),
ServerFlag: data.Get("server_flag").(bool),
ClientFlag: data.Get("client_flag").(bool),
CodeSigningFlag: data.Get("code_signing_flag").(bool),
EmailProtectionFlag: data.Get("email_protection_flag").(bool),
KeyType: data.Get("key_type").(string),
KeyBits: data.Get("key_bits").(int),
UseCSRCommonName: data.Get("use_csr_common_name").(bool),
UseCSRSANs: data.Get("use_csr_sans").(bool),
KeyUsage: data.Get("key_usage").([]string),
OU: data.Get("ou").(string),
Organization: data.Get("organization").(string),
GenerateLease: new(bool),
NoStore: data.Get("no_store").(bool),
}
// no_store implies generate_lease := false
if entry.NoStore {
*entry.GenerateLease = false
} else {
*entry.GenerateLease = data.Get("generate_lease").(bool)
}
if entry.KeyType == "rsa" && entry.KeyBits < 2048 {
return logical.ErrorResponse("RSA keys < 2048 bits are unsafe and not supported"), nil
}
var maxTTL time.Duration
maxSystemTTL := b.System().MaxLeaseTTL()
if len(entry.MaxTTL) == 0 {
maxTTL = maxSystemTTL
} else {
maxTTL, err = parseutil.ParseDurationSecond(entry.MaxTTL)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf(
"Invalid max ttl: %s", err)), nil
}
}
if maxTTL > maxSystemTTL {
return logical.ErrorResponse("Requested max TTL is higher than backend maximum"), nil
}
ttl := b.System().DefaultLeaseTTL()
if len(entry.TTL) != 0 {
ttl, err = parseutil.ParseDurationSecond(entry.TTL)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf(
"Invalid ttl: %s", err)), nil
}
}
if ttl > maxTTL {
// If they are using the system default, cap it to the role max;
// if it was specified on the command line, make it an error
if len(entry.TTL) == 0 {
ttl = maxTTL
} else {
return logical.ErrorResponse(
`"ttl" value must be less than "max_ttl" and/or backend default max lease TTL value`,
), nil
}
}
// Persist clamped TTLs
entry.TTL = ttl.String()
entry.MaxTTL = maxTTL.String()
if errResp := validateKeyTypeLength(entry.KeyType, entry.KeyBits); errResp != nil {
return errResp, nil
}
// Store it
jsonEntry, err := logical.StorageEntryJSON("role/"+name, entry)
if err != nil {
return nil, err
}
if err := req.Storage.Put(jsonEntry); err != nil {
return nil, err
}
return nil, nil
}
func parseKeyUsages(input []string) int {
var parsedKeyUsages x509.KeyUsage
for _, k := range input {
switch strings.ToLower(strings.TrimSpace(k)) {
case "digitalsignature":
parsedKeyUsages |= x509.KeyUsageDigitalSignature
case "contentcommitment":
parsedKeyUsages |= x509.KeyUsageContentCommitment
case "keyencipherment":
parsedKeyUsages |= x509.KeyUsageKeyEncipherment
case "dataencipherment":
parsedKeyUsages |= x509.KeyUsageDataEncipherment
case "keyagreement":
parsedKeyUsages |= x509.KeyUsageKeyAgreement
case "certsign":
parsedKeyUsages |= x509.KeyUsageCertSign
case "crlsign":
parsedKeyUsages |= x509.KeyUsageCRLSign
case "encipheronly":
parsedKeyUsages |= x509.KeyUsageEncipherOnly
case "decipheronly":
parsedKeyUsages |= x509.KeyUsageDecipherOnly
}
}
return int(parsedKeyUsages)
}
type roleEntry struct {
LeaseMax string `json:"lease_max"`
Lease string `json:"lease"`
MaxTTL string `json:"max_ttl" mapstructure:"max_ttl"`
TTL string `json:"ttl" mapstructure:"ttl"`
AllowLocalhost bool `json:"allow_localhost" mapstructure:"allow_localhost"`
AllowedBaseDomain string `json:"allowed_base_domain" mapstructure:"allowed_base_domain"`
AllowedDomainsOld string `json:"allowed_domains,omit_empty"`
AllowedDomains []string `json:"allowed_domains_list" mapstructure:"allowed_domains"`
AllowBaseDomain bool `json:"allow_base_domain"`
AllowBareDomains bool `json:"allow_bare_domains" mapstructure:"allow_bare_domains"`
AllowTokenDisplayName bool `json:"allow_token_displayname" mapstructure:"allow_token_displayname"`
AllowSubdomains bool `json:"allow_subdomains" mapstructure:"allow_subdomains"`
AllowGlobDomains bool `json:"allow_glob_domains" mapstructure:"allow_glob_domains"`
AllowAnyName bool `json:"allow_any_name" mapstructure:"allow_any_name"`
EnforceHostnames bool `json:"enforce_hostnames" mapstructure:"enforce_hostnames"`
AllowIPSANs bool `json:"allow_ip_sans" mapstructure:"allow_ip_sans"`
ServerFlag bool `json:"server_flag" mapstructure:"server_flag"`
ClientFlag bool `json:"client_flag" mapstructure:"client_flag"`
CodeSigningFlag bool `json:"code_signing_flag" mapstructure:"code_signing_flag"`
EmailProtectionFlag bool `json:"email_protection_flag" mapstructure:"email_protection_flag"`
UseCSRCommonName bool `json:"use_csr_common_name" mapstructure:"use_csr_common_name"`
UseCSRSANs bool `json:"use_csr_sans" mapstructure:"use_csr_sans"`
KeyType string `json:"key_type" mapstructure:"key_type"`
KeyBits int `json:"key_bits" mapstructure:"key_bits"`
MaxPathLength *int `json:",omitempty" mapstructure:"max_path_length"`
KeyUsageOld string `json:"key_usage,omitempty"`
KeyUsage []string `json:"key_usage_list" mapstructure:"key_usage"`
OU string `json:"ou" mapstructure:"ou"`
Organization string `json:"organization" mapstructure:"organization"`
GenerateLease *bool `json:"generate_lease,omitempty"`
NoStore bool `json:"no_store" mapstructure:"no_store"`
// Used internally for signing intermediates
AllowExpirationPastCA bool
}
func (r *roleEntry) ToResponseData() map[string]interface{} {
responseData := map[string]interface{}{
"ttl": r.TTL,
"max_ttl": r.MaxTTL,
"allow_localhost": r.AllowLocalhost,
"allowed_domains": r.AllowedDomains,
"allow_bare_domains": r.AllowBareDomains,
"allow_token_displayname": r.AllowTokenDisplayName,
"allow_subdomains": r.AllowSubdomains,
"allow_glob_domains": r.AllowGlobDomains,
"allow_any_name": r.AllowAnyName,
"enforce_hostnames": r.EnforceHostnames,
"allow_ip_sans": r.AllowIPSANs,
"server_flag": r.ServerFlag,
"client_flag": r.ClientFlag,
"code_signing_flag": r.CodeSigningFlag,
"email_protection_flag": r.EmailProtectionFlag,
"use_csr_common_name": r.UseCSRCommonName,
"use_csr_sans": r.UseCSRSANs,
"key_type": r.KeyType,
"key_bits": r.KeyBits,
"key_usage": r.KeyUsage,
"ou": r.OU,
"organization": r.Organization,
"no_store": r.NoStore,
}
if r.MaxPathLength != nil {
responseData["max_path_length"] = r.MaxPathLength
}
if r.GenerateLease != nil {
responseData["generate_lease"] = r.GenerateLease
}
return responseData
}
const pathListRolesHelpSyn = `List the existing roles in this backend`
const pathListRolesHelpDesc = `Roles will be listed by the role name.`
const pathRoleHelpSyn = `Manage the roles that can be created with this backend.`
const pathRoleHelpDesc = `This path lets you manage the roles that can be created with this backend.`