-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpath_roles.go
664 lines (566 loc) · 21.4 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
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
package database
import (
"context"
"fmt"
"strings"
"time"
"github.com/hashicorp/vault/sdk/database/dbplugin"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/locksutil"
"github.com/hashicorp/vault/sdk/helper/strutil"
"github.com/hashicorp/vault/sdk/logical"
"github.com/hashicorp/vault/sdk/queue"
)
func pathListRoles(b *databaseBackend) []*framework.Path {
return []*framework.Path{
&framework.Path{
Pattern: "roles/?$",
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ListOperation: b.pathRoleList,
},
HelpSynopsis: pathRoleHelpSyn,
HelpDescription: pathRoleHelpDesc,
},
&framework.Path{
Pattern: "static-roles/?$",
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ListOperation: b.pathRoleList,
},
HelpSynopsis: pathStaticRoleHelpSyn,
HelpDescription: pathStaticRoleHelpDesc,
},
}
}
func pathRoles(b *databaseBackend) []*framework.Path {
return []*framework.Path{
&framework.Path{
Pattern: "roles/" + framework.GenericNameRegex("name"),
Fields: fieldsForType(databaseRolePath),
ExistenceCheck: b.pathRoleExistenceCheck,
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: b.pathRoleRead,
logical.CreateOperation: b.pathRoleCreateUpdate,
logical.UpdateOperation: b.pathRoleCreateUpdate,
logical.DeleteOperation: b.pathRoleDelete,
},
HelpSynopsis: pathRoleHelpSyn,
HelpDescription: pathRoleHelpDesc,
},
&framework.Path{
Pattern: "static-roles/" + framework.GenericNameRegex("name"),
Fields: fieldsForType(databaseStaticRolePath),
ExistenceCheck: b.pathStaticRoleExistenceCheck,
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: b.pathStaticRoleRead,
logical.CreateOperation: b.pathStaticRoleCreateUpdate,
logical.UpdateOperation: b.pathStaticRoleCreateUpdate,
logical.DeleteOperation: b.pathStaticRoleDelete,
},
HelpSynopsis: pathStaticRoleHelpSyn,
HelpDescription: pathStaticRoleHelpDesc,
},
}
}
// fieldsForType returns a map of string/FieldSchema items for the given role
// type. The purpose is to keep the shared fields between dynamic and static
// roles consistent, and allow for each type to override or provide their own
// specific fields
func fieldsForType(roleType string) map[string]*framework.FieldSchema {
fields := map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "Name of the role.",
},
"db_name": {
Type: framework.TypeString,
Description: "Name of the database this role acts on.",
},
}
// Get the fields that are specific to the type of role, and add them to the
// common fields
var typeFields map[string]*framework.FieldSchema
switch roleType {
case databaseStaticRolePath:
typeFields = staticFields()
default:
typeFields = dynamicFields()
}
for k, v := range typeFields {
fields[k] = v
}
return fields
}
// dynamicFields returns a map of key and field schema items that are specific
// only to dynamic roles
func dynamicFields() map[string]*framework.FieldSchema {
fields := map[string]*framework.FieldSchema{
"default_ttl": {
Type: framework.TypeDurationSecond,
Description: "Default ttl for role.",
},
"max_ttl": {
Type: framework.TypeDurationSecond,
Description: "Maximum time a credential is valid for",
},
"creation_statements": {
Type: framework.TypeStringSlice,
Description: `Specifies the database statements executed to
create and configure a user. See the plugin's API page for more
information on support and formatting for this parameter.`,
},
"revocation_statements": {
Type: framework.TypeStringSlice,
Description: `Specifies the database statements to be executed
to revoke a user. See the plugin's API page for more information
on support and formatting for this parameter.`,
},
"renew_statements": {
Type: framework.TypeStringSlice,
Description: `Specifies the database statements to be executed
to renew a user. Not every plugin type will support this
functionality. See the plugin's API page for more information on
support and formatting for this parameter. `,
},
"rollback_statements": {
Type: framework.TypeStringSlice,
Description: `Specifies the database statements to be executed
rollback a create operation in the event of an error. Not every plugin
type will support this functionality. See the plugin's API page for
more information on support and formatting for this parameter.`,
},
}
return fields
}
// staticFields returns a map of key and field schema items that are specific
// only to static roles
func staticFields() map[string]*framework.FieldSchema {
fields := map[string]*framework.FieldSchema{
"username": {
Type: framework.TypeString,
Description: `Name of the static user account for Vault to manage.
Requires "rotation_period" to be specified`,
},
"rotation_period": {
Type: framework.TypeDurationSecond,
Description: `Period for automatic
credential rotation of the given username. Not valid unless used with
"username".`,
},
"rotation_statements": {
Type: framework.TypeStringSlice,
Description: `Specifies the database statements to be executed to
rotate the accounts credentials. Not every plugin type will support
this functionality. See the plugin's API page for more information on
support and formatting for this parameter.`,
},
}
return fields
}
func (b *databaseBackend) pathRoleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) {
role, err := b.Role(ctx, req.Storage, data.Get("name").(string))
if err != nil {
return false, err
}
return role != nil, nil
}
func (b *databaseBackend) pathStaticRoleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) {
role, err := b.StaticRole(ctx, req.Storage, data.Get("name").(string))
if err != nil {
return false, err
}
return role != nil, nil
}
func (b *databaseBackend) pathRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
err := req.Storage.Delete(ctx, databaseRolePath+data.Get("name").(string))
if err != nil {
return nil, err
}
return nil, nil
}
func (b *databaseBackend) pathStaticRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
name := data.Get("name").(string)
// Grab the exclusive lock
lock := locksutil.LockForKey(b.roleLocks, name)
lock.Lock()
defer lock.Unlock()
// Remove the item from the queue
_, _ = b.popFromRotationQueueByKey(name)
err := req.Storage.Delete(ctx, databaseStaticRolePath+name)
if err != nil {
return nil, err
}
return nil, nil
}
func (b *databaseBackend) pathStaticRoleRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
role, err := b.StaticRole(ctx, req.Storage, d.Get("name").(string))
if err != nil {
return nil, err
}
if role == nil {
return nil, nil
}
data := map[string]interface{}{
"db_name": role.DBName,
"rotation_statements": role.Statements.Rotation,
}
// guard against nil StaticAccount; shouldn't happen but we'll be safe
if role.StaticAccount != nil {
data["username"] = role.StaticAccount.Username
data["rotation_statements"] = role.Statements.Rotation
data["rotation_period"] = role.StaticAccount.RotationPeriod.Seconds()
if !role.StaticAccount.LastVaultRotation.IsZero() {
data["last_vault_rotation"] = role.StaticAccount.LastVaultRotation
}
}
if len(role.Statements.Rotation) == 0 {
data["rotation_statements"] = []string{}
}
return &logical.Response{
Data: data,
}, nil
}
func (b *databaseBackend) pathRoleRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
role, err := b.Role(ctx, req.Storage, d.Get("name").(string))
if err != nil {
return nil, err
}
if role == nil {
return nil, nil
}
data := map[string]interface{}{
"db_name": role.DBName,
"creation_statements": role.Statements.Creation,
"revocation_statements": role.Statements.Revocation,
"rollback_statements": role.Statements.Rollback,
"renew_statements": role.Statements.Renewal,
"default_ttl": role.DefaultTTL.Seconds(),
"max_ttl": role.MaxTTL.Seconds(),
}
if len(role.Statements.Creation) == 0 {
data["creation_statements"] = []string{}
}
if len(role.Statements.Revocation) == 0 {
data["revocation_statements"] = []string{}
}
if len(role.Statements.Rollback) == 0 {
data["rollback_statements"] = []string{}
}
if len(role.Statements.Renewal) == 0 {
data["renew_statements"] = []string{}
}
return &logical.Response{
Data: data,
}, nil
}
func (b *databaseBackend) pathRoleList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
path := databaseRolePath
if strings.HasPrefix(req.Path, "static-roles") {
path = databaseStaticRolePath
}
entries, err := req.Storage.List(ctx, path)
if err != nil {
return nil, err
}
return logical.ListResponse(entries), nil
}
func (b *databaseBackend) pathRoleCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
name := data.Get("name").(string)
if name == "" {
return logical.ErrorResponse("empty role name attribute given"), nil
}
exists, err := b.pathStaticRoleExistenceCheck(ctx, req, data)
if err != nil {
return nil, err
}
if exists {
return logical.ErrorResponse("Role and Static Role names must be unique"), nil
}
role, err := b.Role(ctx, req.Storage, name)
if err != nil {
return nil, err
}
if role == nil {
role = &roleEntry{}
}
createOperation := (req.Operation == logical.CreateOperation)
// DB Attributes
{
if dbNameRaw, ok := data.GetOk("db_name"); ok {
role.DBName = dbNameRaw.(string)
} else if createOperation {
role.DBName = data.Get("db_name").(string)
}
if role.DBName == "" {
return logical.ErrorResponse("database name is required"), nil
}
}
// Statements
{
if creationStmtsRaw, ok := data.GetOk("creation_statements"); ok {
role.Statements.Creation = creationStmtsRaw.([]string)
} else if createOperation {
role.Statements.Creation = data.Get("creation_statements").([]string)
}
if revocationStmtsRaw, ok := data.GetOk("revocation_statements"); ok {
role.Statements.Revocation = revocationStmtsRaw.([]string)
} else if createOperation {
role.Statements.Revocation = data.Get("revocation_statements").([]string)
}
if rollbackStmtsRaw, ok := data.GetOk("rollback_statements"); ok {
role.Statements.Rollback = rollbackStmtsRaw.([]string)
} else if createOperation {
role.Statements.Rollback = data.Get("rollback_statements").([]string)
}
if renewStmtsRaw, ok := data.GetOk("renew_statements"); ok {
role.Statements.Renewal = renewStmtsRaw.([]string)
} else if createOperation {
role.Statements.Renewal = data.Get("renew_statements").([]string)
}
// Do not persist deprecated statements that are populated on role read
role.Statements.CreationStatements = ""
role.Statements.RevocationStatements = ""
role.Statements.RenewStatements = ""
role.Statements.RollbackStatements = ""
}
role.Statements.Revocation = strutil.RemoveEmpty(role.Statements.Revocation)
// TTLs
{
if defaultTTLRaw, ok := data.GetOk("default_ttl"); ok {
role.DefaultTTL = time.Duration(defaultTTLRaw.(int)) * time.Second
} else if createOperation {
role.DefaultTTL = time.Duration(data.Get("default_ttl").(int)) * time.Second
}
if maxTTLRaw, ok := data.GetOk("max_ttl"); ok {
role.MaxTTL = time.Duration(maxTTLRaw.(int)) * time.Second
} else if createOperation {
role.MaxTTL = time.Duration(data.Get("max_ttl").(int)) * time.Second
}
}
// Store it
entry, err := logical.StorageEntryJSON(databaseRolePath+name, role)
if err != nil {
return nil, err
}
if err := req.Storage.Put(ctx, entry); err != nil {
return nil, err
}
return nil, nil
}
func (b *databaseBackend) pathStaticRoleCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
name := data.Get("name").(string)
if name == "" {
return logical.ErrorResponse("empty role name attribute given"), nil
}
// Grab the exclusive lock as well potentially pop and re-push the queue item
// for this role
lock := locksutil.LockForKey(b.roleLocks, name)
lock.Lock()
defer lock.Unlock()
exists, err := b.pathRoleExistenceCheck(ctx, req, data)
if err != nil {
return nil, err
}
if exists {
return logical.ErrorResponse("Role and Static Role names must be unique"), nil
}
role, err := b.StaticRole(ctx, req.Storage, data.Get("name").(string))
if err != nil {
return nil, err
}
// createRole is a boolean to indicate if this is a new role creation. This is
// can be used later by database plugins that distinguish between creating and
// updating roles, and may use seperate statements depending on the context.
createRole := (req.Operation == logical.CreateOperation)
if role == nil {
role = &roleEntry{
StaticAccount: &staticAccount{},
}
createRole = true
}
// DB Attributes
if dbNameRaw, ok := data.GetOk("db_name"); ok {
role.DBName = dbNameRaw.(string)
} else if createRole {
role.DBName = data.Get("db_name").(string)
}
if role.DBName == "" {
return logical.ErrorResponse("database name is a required field"), nil
}
username := data.Get("username").(string)
if username == "" && createRole {
return logical.ErrorResponse("username is a required field to create a static account"), nil
}
if role.StaticAccount.Username != "" && role.StaticAccount.Username != username {
return logical.ErrorResponse("cannot update static account username"), nil
}
role.StaticAccount.Username = username
// If it's a Create operation, both username and rotation_period must be included
rotationPeriodSecondsRaw, ok := data.GetOk("rotation_period")
if !ok && createRole {
return logical.ErrorResponse("rotation_period is required to create static accounts"), nil
}
if ok {
rotationPeriodSeconds := rotationPeriodSecondsRaw.(int)
if rotationPeriodSeconds < queueTickSeconds {
// If rotation frequency is specified, and this is an update, the value
// must be at least that of the constant queueTickSeconds (5 seconds at
// time of writing), otherwise we wont be able to rotate in time
return logical.ErrorResponse(fmt.Sprintf("rotation_period must be %d seconds or more", queueTickSeconds)), nil
}
role.StaticAccount.RotationPeriod = time.Duration(rotationPeriodSeconds) * time.Second
}
if rotationStmtsRaw, ok := data.GetOk("rotation_statements"); ok {
role.Statements.Rotation = rotationStmtsRaw.([]string)
} else if req.Operation == logical.CreateOperation {
role.Statements.Rotation = data.Get("rotation_statements").([]string)
}
// lvr represents the roles' LastVaultRotation
lvr := role.StaticAccount.LastVaultRotation
// Only call setStaticAccount if we're creating the role for the
// first time
switch req.Operation {
case logical.CreateOperation:
// setStaticAccount calls Storage.Put and saves the role to storage
resp, err := b.setStaticAccount(ctx, req.Storage, &setStaticAccountInput{
RoleName: name,
Role: role,
CreateUser: createRole,
})
if err != nil {
return nil, err
}
// guard against RotationTime not being set or zero-value
lvr = resp.RotationTime
case logical.UpdateOperation:
// store updated Role
entry, err := logical.StorageEntryJSON(databaseStaticRolePath+name, role)
if err != nil {
return nil, err
}
if err := req.Storage.Put(ctx, entry); err != nil {
return nil, err
}
// In case this is an update, remove any previous version of the item from
// the queue
b.popFromRotationQueueByKey(name)
}
// Add their rotation to the queue
if err := b.pushItem(&queue.Item{
Key: name,
Priority: lvr.Add(role.StaticAccount.RotationPeriod).Unix(),
}); err != nil {
return nil, err
}
return nil, nil
}
type roleEntry struct {
DBName string `json:"db_name"`
Statements dbplugin.Statements `json:"statements"`
DefaultTTL time.Duration `json:"default_ttl"`
MaxTTL time.Duration `json:"max_ttl"`
StaticAccount *staticAccount `json:"static_account" mapstructure:"static_account"`
}
type staticAccount struct {
// Username to create or assume management for static accounts
Username string `json:"username"`
// Password is the current password for static accounts. As an input, this is
// used/required when trying to assume management of an existing static
// account. Return this on credential request if it exists.
Password string `json:"password"`
// LastVaultRotation represents the last time Vault rotated the password
LastVaultRotation time.Time `json:"last_vault_rotation"`
// RotationPeriod is number in seconds between each rotation, effectively a
// "time to live". This value is compared to the LastVaultRotation to
// determine if a password needs to be rotated
RotationPeriod time.Duration `json:"rotation_period"`
// RevokeUser is a boolean flag to indicate if Vault should revoke the
// database user when the role is deleted
RevokeUserOnDelete bool `json:"revoke_user_on_delete"`
}
// NextRotationTime calculates the next rotation by adding the Rotation Period
// to the last known vault rotation
func (s *staticAccount) NextRotationTime() time.Time {
return s.LastVaultRotation.Add(s.RotationPeriod)
}
// PasswordTTL calculates the approximate time remaining until the password is
// no longer valid. This is approximate because the periodic rotation is only
// checked approximately every 5 seconds, and each rotation can take a small
// amount of time to process. This can result in a negative TTL time while the
// rotation function processes the Static Role and performs the rotation. If the
// TTL is negative, zero is returned. Users should not trust passwords with a
// Zero TTL, as they are likely in the process of being rotated and will quickly
// be invalidated.
func (s *staticAccount) PasswordTTL() time.Duration {
next := s.NextRotationTime()
ttl := next.Sub(time.Now()).Round(time.Second)
if ttl < 0 {
ttl = time.Duration(0)
}
return ttl
}
const pathRoleHelpSyn = `
Manage the roles that can be created with this backend.
`
const pathStaticRoleHelpSyn = `
Manage the static roles that can be created with this backend.
`
const pathRoleHelpDesc = `
This path lets you manage the roles that can be created with this backend.
The "db_name" parameter is required and configures the name of the database
connection to use.
The "creation_statements" parameter customizes the string used to create the
credentials. This can be a sequence of SQL queries, or other statement formats
for a particular database type. Some substitution will be done to the statement
strings for certain keys. The names of the variables must be surrounded by "{{"
and "}}" to be replaced.
* "name" - The random username generated for the DB user.
* "password" - The random password generated for the DB user.
* "expiration" - The timestamp when this user will expire.
Example of a decent creation_statements for a postgresql database plugin:
CREATE ROLE "{{name}}" WITH
LOGIN
PASSWORD '{{password}}'
VALID UNTIL '{{expiration}}';
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO "{{name}}";
The "revocation_statements" parameter customizes the statement string used to
revoke a user. Example of a decent revocation_statements for a postgresql
database plugin:
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM {{name}};
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM {{name}};
REVOKE USAGE ON SCHEMA public FROM {{name}};
DROP ROLE IF EXISTS {{name}};
The "renew_statements" parameter customizes the statement string used to renew a
user.
The "rollback_statements' parameter customizes the statement string used to
rollback a change if needed.
`
const pathStaticRoleHelpDesc = `
This path lets you manage the static roles that can be created with this
backend. Static Roles are associated with a single database user, and manage the
password based on a rotation period, automatically rotating the password.
The "db_name" parameter is required and configures the name of the database
connection to use.
The "creation_statements" parameter customizes the string used to create the
credentials. This can be a sequence of SQL queries, or other statement formats
for a particular database type. Some substitution will be done to the statement
strings for certain keys. The names of the variables must be surrounded by "{{"
and "}}" to be replaced.
* "name" - The random username generated for the DB user.
* "password" - The random password generated for the DB user.
Example of a decent creation_statements for a postgresql database plugin:
CREATE ROLE "{{name}}" WITH
LOGIN
PASSWORD '{{password}}'
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO "{{name}}";
The "revocation_statements" parameter customizes the statement string used to
revoke a user. Example of a decent revocation_statements for a postgresql
database plugin:
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM {{name}};
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM {{name}};
REVOKE USAGE ON SCHEMA public FROM {{name}};
DROP ROLE IF EXISTS {{name}};
The "renew_statements" parameter customizes the statement string used to renew a
user.
The "rollback_statements' parameter customizes the statement string used to
rollback a change if needed.
`