-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathsecret_access_keys.go
355 lines (302 loc) · 9.84 KB
/
secret_access_keys.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
package aws
import (
"context"
"fmt"
"math/rand"
"regexp"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/vault/helper/awsutil"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
)
const secretAccessKeyType = "access_keys"
func secretAccessKeys(b *backend) *framework.Secret {
return &framework.Secret{
Type: secretAccessKeyType,
Fields: map[string]*framework.FieldSchema{
"access_key": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Access Key",
},
"secret_key": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Secret Key",
},
"security_token": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Security Token",
},
},
Renew: b.secretAccessKeysRenew,
Revoke: b.secretAccessKeysRevoke,
}
}
func genUsername(displayName, policyName, userType string) (ret string, warning string) {
var midString string
switch userType {
case "iam_user":
// IAM users are capped at 64 chars; this leaves, after the beginning and
// end added below, 42 chars to play with.
midString = fmt.Sprintf("%s-%s-",
normalizeDisplayName(displayName),
normalizeDisplayName(policyName))
if len(midString) > 42 {
midString = midString[0:42]
warning = "the calling token display name/IAM policy name were truncated to fit into IAM username length limits"
}
case "sts":
// Capped at 32 chars, which leaves only a couple of characters to play
// with, so don't insert display name or policy name at all
}
ret = fmt.Sprintf("vault-%s%d-%d", midString, time.Now().Unix(), rand.Int31n(10000))
return
}
func (b *backend) secretTokenCreate(ctx context.Context, s logical.Storage,
displayName, policyName, policy string,
lifeTimeInSeconds int64) (*logical.Response, error) {
b.clientMutex.RLock()
unlockFunc := b.clientMutex.RUnlock
defer func() { unlockFunc() }()
if b.stsClient == nil {
// Upgrade the lock for writing
b.clientMutex.RUnlock()
b.clientMutex.Lock()
unlockFunc = b.clientMutex.Unlock
stsClient, err := clientSTS(ctx, s)
if err != nil {
return logical.ErrorResponse(err.Error()), nil
}
b.stsClient = stsClient
}
username, usernameWarning := genUsername(displayName, policyName, "sts")
tokenResp, err := b.stsClient.GetFederationToken(
&sts.GetFederationTokenInput{
Name: aws.String(username),
Policy: aws.String(policy),
DurationSeconds: &lifeTimeInSeconds,
})
if err != nil {
return logical.ErrorResponse(fmt.Sprintf(
"Error generating STS keys: %s", err)), awsutil.CheckAWSError(err)
}
resp := b.Secret(secretAccessKeyType).Response(map[string]interface{}{
"access_key": *tokenResp.Credentials.AccessKeyId,
"secret_key": *tokenResp.Credentials.SecretAccessKey,
"security_token": *tokenResp.Credentials.SessionToken,
}, map[string]interface{}{
"username": username,
"policy": policy,
"is_sts": true,
})
// Set the secret TTL to appropriately match the expiration of the token
resp.Secret.TTL = tokenResp.Credentials.Expiration.Sub(time.Now())
// STS are purposefully short-lived and aren't renewable
resp.Secret.Renewable = false
if usernameWarning != "" {
resp.AddWarning(usernameWarning)
}
return resp, nil
}
func (b *backend) assumeRole(ctx context.Context, s logical.Storage,
displayName, roleName, roleArn, policy string,
lifeTimeInSeconds int64) (*logical.Response, error) {
b.clientMutex.Lock()
defer b.clientMutex.Unlock()
if b.stsClient == nil {
stsClient, err := clientSTS(ctx, s)
if err != nil {
return logical.ErrorResponse(err.Error()), nil
}
b.stsClient = stsClient
}
username, usernameWarning := genUsername(displayName, roleName, "iam_user")
assumeRoleInput := &sts.AssumeRoleInput{
RoleSessionName: aws.String(username),
RoleArn: aws.String(roleArn),
DurationSeconds: &lifeTimeInSeconds,
}
if policy != "" {
assumeRoleInput.SetPolicy(policy)
}
tokenResp, err := b.stsClient.AssumeRole(assumeRoleInput)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf(
"Error assuming role: %s", err)), awsutil.CheckAWSError(err)
}
resp := b.Secret(secretAccessKeyType).Response(map[string]interface{}{
"access_key": *tokenResp.Credentials.AccessKeyId,
"secret_key": *tokenResp.Credentials.SecretAccessKey,
"security_token": *tokenResp.Credentials.SessionToken,
}, map[string]interface{}{
"username": username,
"policy": roleArn,
"is_sts": true,
})
// Set the secret TTL to appropriately match the expiration of the token
resp.Secret.TTL = tokenResp.Credentials.Expiration.Sub(time.Now())
// STS are purposefully short-lived and aren't renewable
resp.Secret.Renewable = false
if usernameWarning != "" {
resp.AddWarning(usernameWarning)
}
return resp, nil
}
func (b *backend) secretAccessKeysCreate(
ctx context.Context,
s logical.Storage,
displayName, policyName string, role *awsRoleEntry) (*logical.Response, error) {
b.clientMutex.RLock()
unlockFunc := b.clientMutex.RUnlock
defer func() { unlockFunc() }()
if b.iamClient == nil {
// Upgrade the lock for writing
b.clientMutex.RUnlock()
b.clientMutex.Lock()
unlockFunc = b.clientMutex.Unlock
iamClient, err := clientIAM(ctx, s)
if err != nil {
return logical.ErrorResponse(err.Error()), nil
}
b.iamClient = iamClient
}
username, usernameWarning := genUsername(displayName, policyName, "iam_user")
// Write to the WAL that this user will be created. We do this before
// the user is created because if switch the order then the WAL put
// can fail, which would put us in an awkward position: we have a user
// we need to rollback but can't put the WAL entry to do the rollback.
walID, err := framework.PutWAL(ctx, s, "user", &walUser{
UserName: username,
})
if err != nil {
return nil, errwrap.Wrapf("error writing WAL entry: {{err}}", err)
}
// Create the user
_, err = b.iamClient.CreateUser(&iam.CreateUserInput{
UserName: aws.String(username),
})
if err != nil {
return logical.ErrorResponse(fmt.Sprintf(
"Error creating IAM user: %s", err)), awsutil.CheckAWSError(err)
}
for _, arn := range role.PolicyArns {
// Attach existing policy against user
_, err = b.iamClient.AttachUserPolicy(&iam.AttachUserPolicyInput{
UserName: aws.String(username),
PolicyArn: aws.String(arn),
})
if err != nil {
return logical.ErrorResponse(fmt.Sprintf(
"Error attaching user policy: %s", err)), awsutil.CheckAWSError(err)
}
}
if role.PolicyDocument != "" {
// Add new inline user policy against user
_, err = b.iamClient.PutUserPolicy(&iam.PutUserPolicyInput{
UserName: aws.String(username),
PolicyName: aws.String(policyName),
PolicyDocument: aws.String(role.PolicyDocument),
})
if err != nil {
return logical.ErrorResponse(fmt.Sprintf(
"Error putting user policy: %s", err)), awsutil.CheckAWSError(err)
}
}
// Create the keys
keyResp, err := b.iamClient.CreateAccessKey(&iam.CreateAccessKeyInput{
UserName: aws.String(username),
})
if err != nil {
return logical.ErrorResponse(fmt.Sprintf(
"Error creating access keys: %s", err)), awsutil.CheckAWSError(err)
}
// Remove the WAL entry, we succeeded! If we fail, we don't return
// the secret because it'll get rolled back anyways, so we have to return
// an error here.
if err := framework.DeleteWAL(ctx, s, walID); err != nil {
return nil, errwrap.Wrapf("failed to commit WAL entry: {{err}}", err)
}
// Return the info!
resp := b.Secret(secretAccessKeyType).Response(map[string]interface{}{
"access_key": *keyResp.AccessKey.AccessKeyId,
"secret_key": *keyResp.AccessKey.SecretAccessKey,
"security_token": nil,
}, map[string]interface{}{
"username": username,
"policy": role,
"is_sts": false,
})
lease, err := b.Lease(ctx, s)
if err != nil || lease == nil {
lease = &configLease{}
}
resp.Secret.TTL = lease.Lease
resp.Secret.MaxTTL = lease.LeaseMax
if usernameWarning != "" {
resp.AddWarning(usernameWarning)
}
return resp, nil
}
func (b *backend) secretAccessKeysRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
// STS already has a lifetime, and we don't support renewing it
isSTSRaw, ok := req.Secret.InternalData["is_sts"]
if ok {
isSTS, ok := isSTSRaw.(bool)
if ok {
if isSTS {
return nil, nil
}
}
}
lease, err := b.Lease(ctx, req.Storage)
if err != nil {
return nil, err
}
if lease == nil {
lease = &configLease{}
}
resp := &logical.Response{Secret: req.Secret}
resp.Secret.TTL = lease.Lease
resp.Secret.MaxTTL = lease.LeaseMax
return resp, nil
}
func (b *backend) secretAccessKeysRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
// STS cleans up after itself so we can skip this if is_sts internal data
// element set to true. If is_sts is not set, assumes old version
// and defaults to the IAM approach.
isSTSRaw, ok := req.Secret.InternalData["is_sts"]
if ok {
isSTS, ok := isSTSRaw.(bool)
if ok {
if isSTS {
return nil, nil
}
} else {
return nil, fmt.Errorf("secret has is_sts but value could not be understood")
}
}
// Get the username from the internal data
usernameRaw, ok := req.Secret.InternalData["username"]
if !ok {
return nil, fmt.Errorf("secret is missing username internal data")
}
username, ok := usernameRaw.(string)
if !ok {
return nil, fmt.Errorf("secret is missing username internal data")
}
// Use the user rollback mechanism to delete this user
err := pathUserRollback(ctx, req, "user", map[string]interface{}{
"username": username,
})
if err != nil {
return nil, err
}
return nil, nil
}
func normalizeDisplayName(displayName string) string {
re := regexp.MustCompile("[^a-zA-Z0-9+=,.@_-]")
return re.ReplaceAllString(displayName, "_")
}