-
Notifications
You must be signed in to change notification settings - Fork 6
/
path_static_roles.go
403 lines (347 loc) · 12.4 KB
/
path_static_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
package openldap
import (
"context"
"fmt"
"time"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/locksutil"
"github.com/hashicorp/vault/sdk/logical"
"github.com/hashicorp/vault/sdk/queue"
)
const (
staticRolePath = "static-role/"
)
func (b *backend) pathListStaticRoles() []*framework.Path {
return []*framework.Path{
{
Pattern: staticRolePath + "?$",
Operations: map[logical.Operation]framework.OperationHandler{
logical.ListOperation: &framework.PathOperation{
Callback: b.pathStaticRoleList,
},
},
HelpSynopsis: staticRolesListHelpSynopsis,
HelpDescription: staticRolesListHelpDescription,
},
}
}
func (b *backend) pathStaticRoles() []*framework.Path {
return []*framework.Path{
{
Pattern: staticRolePath + framework.GenericNameRegex("name"),
Fields: fieldsForType(staticRolePath),
ExistenceCheck: b.pathStaticRoleExistenceCheck,
Operations: map[logical.Operation]framework.OperationHandler{
logical.UpdateOperation: &framework.PathOperation{
Callback: b.pathStaticRoleCreateUpdate,
},
logical.CreateOperation: &framework.PathOperation{
Callback: b.pathStaticRoleCreateUpdate,
},
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathStaticRoleRead,
},
logical.DeleteOperation: &framework.PathOperation{
Callback: b.pathStaticRoleDelete,
ForwardPerformanceStandby: true,
ForwardPerformanceSecondary: true,
},
},
HelpSynopsis: staticRoleHelpSynopsis,
HelpDescription: staticRoleHelpDescription,
},
}
}
// 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.TypeLowerCaseString,
Description: "Name of the role",
},
"username": {
Type: framework.TypeString,
Description: "The username/logon name for the entry with which this role will be associated.",
},
"dn": {
Type: framework.TypeString,
Description: "The distinguished name of the entry to manage.",
},
"ttl": {
Type: framework.TypeDurationSecond,
Description: "The time-to-live for the password.",
},
}
// Get the fields that are specific to the type of role, and add them to the
// common fields. In the future we can add additional for dynamic roles.
var typeFields map[string]*framework.FieldSchema
switch roleType {
case staticRolePath:
typeFields = staticFields()
}
for k, v := range typeFields {
fields[k] = v
}
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{
"rotation_period": {
Type: framework.TypeDurationSecond,
Description: "Period for automatic credential rotation of the given entry.",
},
}
return fields
}
func (b *backend) 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 *backend) 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()
//TODO: Add retry logic
// Remove the item from the queue
_, err := b.popFromRotationQueueByKey(name)
if err != nil {
return nil, err
}
role, err := b.staticRole(ctx, req.Storage, name)
if err != nil {
return nil, err
}
if role == nil {
return nil, nil
}
err = req.Storage.Delete(ctx, staticRolePath+name)
if err != nil {
return nil, err
}
walIDs, err := framework.ListWAL(ctx, req.Storage)
if err != nil {
return nil, err
}
var merr *multierror.Error
for _, walID := range walIDs {
wal, err := b.findStaticWAL(ctx, req.Storage, walID)
if err != nil {
merr = multierror.Append(merr, err)
continue
}
if wal != nil && name == wal.RoleName {
b.Logger().Debug("deleting WAL for deleted role", "WAL ID", walID, "role", name)
err = framework.DeleteWAL(ctx, req.Storage, walID)
if err != nil {
b.Logger().Debug("failed to delete WAL for deleted role", "WAL ID", walID, "error", err)
merr = multierror.Append(merr, err)
}
}
}
return nil, merr.ErrorOrNil()
}
func (b *backend) 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{}{
"dn": role.StaticAccount.DN,
"username": role.StaticAccount.Username,
}
data["rotation_period"] = role.StaticAccount.RotationPeriod.Seconds()
if !role.StaticAccount.LastVaultRotation.IsZero() {
data["last_vault_rotation"] = role.StaticAccount.LastVaultRotation
}
return &logical.Response{Data: data}, nil
}
func (b *backend) pathStaticRoleCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
name := data.Get("name").(string)
// 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()
role, err := b.staticRole(ctx, req.Storage, data.Get("name").(string))
if err != nil {
return nil, err
}
if role == nil {
role = &roleEntry{
StaticAccount: &staticAccount{},
}
}
dn := data.Get("dn").(string)
if dn == "" {
return logical.ErrorResponse("dn is a required field to manage a static account"), nil
}
role.StaticAccount.DN = dn
username := data.Get("username").(string)
if username == "" {
return logical.ErrorResponse("username is a required field to manage a static account"), nil
}
role.StaticAccount.Username = username
rotationPeriodSecondsRaw, ok := data.GetOk("rotation_period")
if !ok {
return logical.ErrorResponse("rotation_period is required for static accounts"), nil
}
rotationPeriodSeconds := rotationPeriodSecondsRaw.(int)
if rotationPeriodSeconds < queueTickSeconds {
// If rotation frequency is specified 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("rotation_period must be %d seconds or more", queueTickSeconds), nil
}
role.StaticAccount.RotationPeriod = time.Duration(rotationPeriodSeconds) * time.Second
// lvr represents the role's LastVaultRotation
lvr := role.StaticAccount.LastVaultRotation
// Only call setStaticAccountPassword if we're creating the role for the
// first time
var item *queue.Item
switch req.Operation {
case logical.CreateOperation:
// setStaticAccountPassword calls Storage.Put and saves the role to storage
resp, err := b.setStaticAccountPassword(ctx, req.Storage, &setStaticAccountInput{
RoleName: name,
Role: role,
})
if err != nil {
if resp != nil && resp.WALID != "" {
b.Logger().Debug("deleting WAL for failed role creation", "WAL ID", resp.WALID, "role", name)
walDeleteErr := framework.DeleteWAL(ctx, req.Storage, resp.WALID)
if walDeleteErr != nil {
b.Logger().Debug("failed to delete WAL for failed role creation", "WAL ID", resp.WALID, "error", walDeleteErr)
var merr *multierror.Error
merr = multierror.Append(merr, err)
merr = multierror.Append(merr, fmt.Errorf("failed to clean up WAL from failed role creation: %w", walDeleteErr))
err = merr.ErrorOrNil()
}
}
return nil, err
}
// guard against RotationTime not being set or zero-value
lvr = resp.RotationTime
item = &queue.Item{
Key: name,
}
case logical.UpdateOperation:
// store updated Role
entry, err := logical.StorageEntryJSON(staticRolePath+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. The existing item could be tracking a WAL ID for this role,
// so it's important to keep the existing item rather than recreate it.
//TODO: Add retry logic
item, err = b.popFromRotationQueueByKey(name)
if err != nil {
return nil, err
}
}
item.Priority = lvr.Add(role.StaticAccount.RotationPeriod).Unix()
// Add their rotation to the queue
if err := b.pushItem(item); err != nil {
return nil, err
}
return nil, nil
}
type roleEntry struct {
StaticAccount *staticAccount `json:"static_account" mapstructure:"static_account"`
}
type staticAccount struct {
// DN to create or assume management for static accounts
DN string `json:"dn"`
// 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"`
}
// 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
}
func (b *backend) pathStaticRoleList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roles, err := req.Storage.List(ctx, staticRolePath)
if err != nil {
return nil, fmt.Errorf("failed to list roles: %w", err)
}
return logical.ListResponse(roles), nil
}
func (b *backend) staticRole(ctx context.Context, s logical.Storage, roleName string) (*roleEntry, error) {
entry, err := s.Get(ctx, staticRolePath+roleName)
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
}
return &result, nil
}
const staticRoleHelpSynopsis = `
Manage the static roles that can be created with this backend.
`
const staticRoleHelpDescription = `
This path lets you manage the static roles that can be created with this
backend. Static Roles are associated with a single LDAP entry, and manage the
password based on a rotation period, automatically rotating the password.
The "dn" parameter is required and configures the domain name to use when managing
the existing entry.
The "username" parameter is required and configures the username for the LDAP entry.
This is helpful to provide a usable name when domain name (DN) isn't used directly for
authentication.
The "rotation_period' parameter is required and configures how often, in seconds, the credentials should be
automatically rotated by Vault. The minimum is 5 seconds (5s).
`
const staticRolesListHelpDescription = `
List all the static roles being managed by Vault.
`
const staticRolesListHelpSynopsis = `
This path lists all the static roles Vault is currently managing in OpenLDAP.
`