/
path_static_roles.go
331 lines (283 loc) · 10.5 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
package aws
import (
"context"
"errors"
"fmt"
"net/http"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/fatih/structs"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
"github.com/hashicorp/vault/sdk/queue"
)
const (
pathStaticRole = "static-roles"
paramRoleName = "name"
paramUsername = "username"
paramRotationPeriod = "rotation_period"
)
type staticRoleEntry struct {
Name string `json:"name" structs:"name" mapstructure:"name"`
ID string `json:"id" structs:"id" mapstructure:"id"`
Username string `json:"username" structs:"username" mapstructure:"username"`
RotationPeriod time.Duration `json:"rotation_period" structs:"rotation_period" mapstructure:"rotation_period"`
}
func pathStaticRoles(b *backend) *framework.Path {
roleResponse := map[int][]framework.Response{
http.StatusOK: {{
Description: http.StatusText(http.StatusOK),
Fields: map[string]*framework.FieldSchema{
paramRoleName: {
Type: framework.TypeString,
Description: descRoleName,
},
paramUsername: {
Type: framework.TypeString,
Description: descUsername,
},
paramRotationPeriod: {
Type: framework.TypeDurationSecond,
Description: descRotationPeriod,
},
},
}},
}
return &framework.Path{
Pattern: fmt.Sprintf("%s/%s", pathStaticRole, framework.GenericNameWithAtRegex(paramRoleName)),
Fields: map[string]*framework.FieldSchema{
paramRoleName: {
Type: framework.TypeString,
Description: descRoleName,
},
paramUsername: {
Type: framework.TypeString,
Description: descUsername,
},
paramRotationPeriod: {
Type: framework.TypeDurationSecond,
Description: descRotationPeriod,
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathStaticRolesRead,
Responses: roleResponse,
},
logical.UpdateOperation: &framework.PathOperation{
Callback: b.pathStaticRolesWrite,
ForwardPerformanceSecondary: true,
ForwardPerformanceStandby: true,
Responses: roleResponse,
},
logical.DeleteOperation: &framework.PathOperation{
Callback: b.pathStaticRolesDelete,
ForwardPerformanceSecondary: true,
ForwardPerformanceStandby: true,
Responses: map[int][]framework.Response{
http.StatusNoContent: {{
Description: http.StatusText(http.StatusNoContent),
}},
},
},
},
HelpSynopsis: pathStaticRolesHelpSyn,
HelpDescription: pathStaticRolesHelpDesc,
}
}
func (b *backend) pathStaticRolesRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName, ok := data.GetOk(paramRoleName)
if !ok {
return nil, fmt.Errorf("missing %q parameter", paramRoleName)
}
b.roleMutex.RLock()
defer b.roleMutex.RUnlock()
entry, err := req.Storage.Get(ctx, formatRoleStoragePath(roleName.(string)))
if err != nil {
return nil, fmt.Errorf("failed to read configuration for static role %q: %w", roleName, err)
}
if entry == nil {
return nil, nil
}
var config staticRoleEntry
if err := entry.DecodeJSON(&config); err != nil {
return nil, fmt.Errorf("failed to decode configuration for static role %q: %w", roleName, err)
}
return &logical.Response{
Data: formatResponse(config),
}, nil
}
func (b *backend) pathStaticRolesWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
// Create & validate config from request parameters
config := staticRoleEntry{}
isCreate := req.Operation == logical.CreateOperation
if rawRoleName, ok := data.GetOk(paramRoleName); ok {
config.Name = rawRoleName.(string)
if err := b.validateRoleName(config.Name); err != nil {
return nil, err
}
} else {
return logical.ErrorResponse("missing %q parameter", paramRoleName), nil
}
// retrieve old role value
entry, err := req.Storage.Get(ctx, formatRoleStoragePath(config.Name))
if err != nil {
return nil, fmt.Errorf("couldn't check storage for pre-existing role: %w", err)
}
if entry != nil {
err = entry.DecodeJSON(&config)
if err != nil {
return nil, fmt.Errorf("couldn't convert existing role into config struct: %w", err)
}
} else {
// if we couldn't find an entry, this is a create event
isCreate = true
}
// other params are optional if we're not Creating
if rawUsername, ok := data.GetOk(paramUsername); ok {
config.Username = rawUsername.(string)
if err := b.validateIAMUserExists(ctx, req.Storage, &config, isCreate); err != nil {
return nil, err
}
} else if isCreate {
return logical.ErrorResponse("missing %q parameter", paramUsername), nil
}
if rawRotationPeriod, ok := data.GetOk(paramRotationPeriod); ok {
config.RotationPeriod = time.Duration(rawRotationPeriod.(int)) * time.Second
if err := b.validateRotationPeriod(config.RotationPeriod); err != nil {
return nil, err
}
} else if isCreate {
return logical.ErrorResponse("missing %q parameter", paramRotationPeriod), nil
}
b.roleMutex.Lock()
defer b.roleMutex.Unlock()
// Upsert role config
newRole, err := logical.StorageEntryJSON(formatRoleStoragePath(config.Name), config)
if err != nil {
return nil, fmt.Errorf("failed to marshal object to JSON: %w", err)
}
err = req.Storage.Put(ctx, newRole)
if err != nil {
return nil, fmt.Errorf("failed to save object in storage: %w", err)
}
// Bootstrap initial set of keys if they did not exist before. AWS Secret Access Keys can only be obtained on creation,
// so we need to boostrap new roles with a new initial set of keys to be able to serve valid credentials to Vault clients.
existingCreds, err := req.Storage.Get(ctx, formatCredsStoragePath(config.Name))
if err != nil {
return nil, fmt.Errorf("unable to verify if credentials already exist for role %q: %w", config.Name, err)
}
if existingCreds == nil {
err := b.createCredential(ctx, req.Storage, config, false)
if err != nil {
return nil, fmt.Errorf("failed to create new credentials for role %q: %w", config.Name, err)
}
err = b.credRotationQueue.Push(&queue.Item{
Key: config.Name,
Value: config,
Priority: time.Now().Add(config.RotationPeriod).Unix(),
})
if err != nil {
return nil, fmt.Errorf("failed to add item into the rotation queue for role %q: %w", config.Name, err)
}
}
return &logical.Response{
Data: formatResponse(config),
}, nil
}
func (b *backend) pathStaticRolesDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName, ok := data.GetOk(paramRoleName)
if !ok {
return nil, fmt.Errorf("missing %q parameter", paramRoleName)
}
b.roleMutex.Lock()
defer b.roleMutex.Unlock()
entry, err := req.Storage.Get(ctx, formatRoleStoragePath(roleName.(string)))
if err != nil {
return nil, fmt.Errorf("couldn't locate role in storage due to error: %w", err)
}
// no entry in storage, but no error either, congrats, it's deleted!
if entry == nil {
return nil, nil
}
var cfg staticRoleEntry
err = entry.DecodeJSON(&cfg)
if err != nil {
return nil, fmt.Errorf("couldn't convert storage entry to role config")
}
err = b.deleteCredential(ctx, req.Storage, cfg, false)
if err != nil {
return nil, fmt.Errorf("failed to clean credentials while deleting role %q: %w", roleName.(string), err)
}
// delete from the queue
_, err = b.credRotationQueue.PopByKey(cfg.Name)
if err != nil {
return nil, fmt.Errorf("couldn't delete key from queue: %w", err)
}
return nil, req.Storage.Delete(ctx, formatRoleStoragePath(roleName.(string)))
}
func (b *backend) validateRoleName(name string) error {
if name == "" {
return errors.New("empty role name attribute given")
}
return nil
}
// validateIAMUser checks the user information we have for the role against the information on AWS. On a create, it uses the username
// to retrieve the user information and _sets_ the userID. On update, it validates the userID and username.
func (b *backend) validateIAMUserExists(ctx context.Context, storage logical.Storage, entry *staticRoleEntry, isCreate bool) error {
c, err := b.clientIAM(ctx, storage)
if err != nil {
return fmt.Errorf("unable to validate username %q: %w", entry.Username, err)
}
// we don't really care about the content of the result, just that it's not an error
out, err := c.GetUser(&iam.GetUserInput{
UserName: aws.String(entry.Username),
})
if err != nil || out.User == nil {
return fmt.Errorf("unable to validate username %q: %w", entry.Username, err)
}
if *out.User.UserName != entry.Username {
return fmt.Errorf("AWS GetUser returned a username, but it didn't match: %q was requested, but %q was returned", entry.Username, *out.User.UserName)
}
if !isCreate && *out.User.UserId != entry.ID {
return fmt.Errorf("AWS GetUser returned a user, but the ID did not match: %q was requested, but %q was returned", entry.ID, *out.User.UserId)
} else {
// if this is an insert, store the userID. This is the immutable part of an IAM user, but it's not exactly user-friendly.
// So, we allow users to specify usernames, but on updates we'll use the ID as a verification cross-check.
entry.ID = *out.User.UserId
}
return nil
}
const (
minAllowableRotationPeriod = 1 * time.Minute
)
func (b *backend) validateRotationPeriod(period time.Duration) error {
if period < minAllowableRotationPeriod {
return fmt.Errorf("role rotation period out of range: must be greater than %.2f seconds", minAllowableRotationPeriod.Seconds())
}
return nil
}
func formatResponse(cfg staticRoleEntry) map[string]interface{} {
response := structs.New(cfg).Map()
response[paramRotationPeriod] = int64(cfg.RotationPeriod.Seconds())
return response
}
func formatRoleStoragePath(roleName string) string {
return fmt.Sprintf("%s/%s", pathStaticRole, roleName)
}
const pathStaticRolesHelpSyn = `
Manage static roles for AWS.
`
const pathStaticRolesHelpDesc = `
This path lets you manage static roles (users) for the AWS secret backend.
A static role is associated with a single IAM user, and manages the access
keys based on a rotation period, automatically rotating the credential. If
the IAM user has multiple access keys, the oldest key will be rotated.
`
const (
descRoleName = "The name of this role."
descUsername = "The IAM user to adopt as a static role."
descRotationPeriod = `Period by which to rotate the backing credential of the adopted user.
This can be a Go duration (e.g, '1m', 24h'), or an integer number of seconds.`
)