forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 1
/
aws.go
300 lines (256 loc) · 7.58 KB
/
aws.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
package aws
import (
"context"
"encoding/base64"
"errors"
"fmt"
"net/http"
"reflect"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/vault/api"
awsauth "github.com/hashicorp/vault/builtin/credential/aws"
"github.com/hashicorp/vault/command/agent/auth"
"github.com/hashicorp/vault/sdk/helper/awsutil"
)
const (
typeEC2 = "ec2"
typeIAM = "iam"
/*
IAM creds can be inferred from instance metadata or the container
identity service, and those creds expire at varying intervals with
new creds becoming available at likewise varying intervals. Let's
default to polling once a minute so all changes can be picked up
rather quickly. This is configurable, however.
*/
defaultCredentialPollInterval = 60
)
type awsMethod struct {
logger hclog.Logger
authType string
nonce string
mountPath string
role string
headerValue string
region string
// These are used to share the latest creds safely across goroutines.
credLock sync.Mutex
lastCreds *credentials.Credentials
// Notifies the outer environment that it should call Authenticate again.
credsFound chan struct{}
// Detects that the outer environment is closing.
stopCh chan struct{}
}
func NewAWSAuthMethod(conf *auth.AuthConfig) (auth.AuthMethod, error) {
if conf == nil {
return nil, errors.New("empty config")
}
if conf.Config == nil {
return nil, errors.New("empty config data")
}
a := &awsMethod{
logger: conf.Logger,
mountPath: conf.MountPath,
credsFound: make(chan struct{}),
stopCh: make(chan struct{}),
region: awsutil.DefaultRegion,
}
typeRaw, ok := conf.Config["type"]
if !ok {
return nil, errors.New("missing 'type' value")
}
a.authType, ok = typeRaw.(string)
if !ok {
return nil, errors.New("could not convert 'type' config value to string")
}
roleRaw, ok := conf.Config["role"]
if !ok {
return nil, errors.New("missing 'role' value")
}
a.role, ok = roleRaw.(string)
if !ok {
return nil, errors.New("could not convert 'role' config value to string")
}
switch {
case a.role == "":
return nil, errors.New("'role' value is empty")
case a.authType == "":
return nil, errors.New("'type' value is empty")
case a.authType != typeEC2 && a.authType != typeIAM:
return nil, errors.New("'type' value is invalid")
}
accessKey := ""
accessKeyRaw, ok := conf.Config["access_key"]
if ok {
accessKey, ok = accessKeyRaw.(string)
if !ok {
return nil, errors.New("could not convert 'access_key' value into string")
}
}
secretKey := ""
secretKeyRaw, ok := conf.Config["secret_key"]
if ok {
secretKey, ok = secretKeyRaw.(string)
if !ok {
return nil, errors.New("could not convert 'secret_key' value into string")
}
}
sessionToken := ""
sessionTokenRaw, ok := conf.Config["session_token"]
if ok {
sessionToken, ok = sessionTokenRaw.(string)
if !ok {
return nil, errors.New("could not convert 'session_token' value into string")
}
}
headerValueRaw, ok := conf.Config["header_value"]
if ok {
a.headerValue, ok = headerValueRaw.(string)
if !ok {
return nil, errors.New("could not convert 'header_value' value into string")
}
}
nonceRaw, ok := conf.Config["nonce"]
if ok {
a.nonce, ok = nonceRaw.(string)
if !ok {
return nil, errors.New("could not convert 'nonce' value into string")
}
}
regionRaw, ok := conf.Config["region"]
if ok {
a.region, ok = regionRaw.(string)
if !ok {
return nil, errors.New("could not convert 'region' value into string")
}
}
if a.authType == typeIAM {
// Check for an optional custom frequency at which we should poll for creds.
credentialPollIntervalSec := defaultCredentialPollInterval
if credentialPollIntervalRaw, ok := conf.Config["credential_poll_interval"]; ok {
if credentialPollInterval, ok := credentialPollIntervalRaw.(int); ok {
credentialPollIntervalSec = credentialPollInterval
} else {
return nil, errors.New("could not convert 'credential_poll_interval' into int")
}
}
// Do an initial population of the creds because we want to err right away if we can't
// even get a first set.
creds, err := awsauth.RetrieveCreds(accessKey, secretKey, sessionToken, a.logger)
if err != nil {
return nil, err
}
a.lastCreds = creds
go a.pollForCreds(accessKey, secretKey, sessionToken, credentialPollIntervalSec)
}
return a, nil
}
func (a *awsMethod) Authenticate(ctx context.Context, client *api.Client) (retToken string, header http.Header, retData map[string]interface{}, retErr error) {
a.logger.Trace("beginning authentication")
data := make(map[string]interface{})
sess, err := session.NewSession()
if err != nil {
retErr = errwrap.Wrapf("error creating session: {{err}}", err)
return
}
metadataSvc := ec2metadata.New(sess)
switch a.authType {
case typeEC2:
// Fetch document
{
doc, err := metadataSvc.GetDynamicData("/instance-identity/document")
if err != nil {
retErr = errwrap.Wrapf("error requesting doc: {{err}}", err)
return
}
data["identity"] = base64.StdEncoding.EncodeToString([]byte(doc))
}
// Fetch signature
{
signature, err := metadataSvc.GetDynamicData("/instance-identity/signature")
if err != nil {
retErr = errwrap.Wrapf("error requesting signature: {{err}}", err)
return
}
data["signature"] = signature
}
// Add the reauthentication value, if we have one
if a.nonce == "" {
uid, err := uuid.GenerateUUID()
if err != nil {
retErr = errwrap.Wrapf("error generating uuid for reauthentication value: {{err}}", err)
return
}
a.nonce = uid
}
data["nonce"] = a.nonce
default:
// This is typeIAM.
a.credLock.Lock()
defer a.credLock.Unlock()
var err error
data, err = awsauth.GenerateLoginData(a.lastCreds, a.headerValue, a.region)
if err != nil {
retErr = errwrap.Wrapf("error creating login value: {{err}}", err)
return
}
}
data["role"] = a.role
return fmt.Sprintf("%s/login", a.mountPath), nil, data, nil
}
func (a *awsMethod) NewCreds() chan struct{} {
return a.credsFound
}
func (a *awsMethod) CredSuccess() {}
func (a *awsMethod) Shutdown() {
close(a.credsFound)
close(a.stopCh)
}
func (a *awsMethod) pollForCreds(accessKey, secretKey, sessionToken string, frequencySeconds int) {
ticker := time.NewTicker(time.Duration(frequencySeconds) * time.Second)
defer ticker.Stop()
for {
select {
case <-a.stopCh:
a.logger.Trace("shutdown triggered, stopping aws auth handler")
return
case <-ticker.C:
if err := a.checkCreds(accessKey, secretKey, sessionToken); err != nil {
a.logger.Warn("unable to retrieve current creds, retaining last creds", "error", err)
}
}
}
}
func (a *awsMethod) checkCreds(accessKey, secretKey, sessionToken string) error {
a.credLock.Lock()
defer a.credLock.Unlock()
a.logger.Trace("checking for new credentials")
currentCreds, err := awsauth.RetrieveCreds(accessKey, secretKey, sessionToken, a.logger)
if err != nil {
return err
}
currentVal, err := currentCreds.Get()
if err != nil {
return err
}
lastVal, err := a.lastCreds.Get()
if err != nil {
return err
}
// These will always have different pointers regardless of whether their
// values are identical, hence the use of DeepEqual.
if !a.lastCreds.IsExpired() && reflect.DeepEqual(currentVal, lastVal) {
a.logger.Trace("credentials are unchanged and still valid")
return nil
}
a.lastCreds = currentCreds
a.logger.Trace("new credentials detected, triggering Authenticate")
a.credsFound <- struct{}{}
return nil
}