/
impl.go
731 lines (676 loc) · 23.4 KB
/
impl.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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
package aws
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"regexp"
"sort"
"strings"
"sync"
"time"
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/armor"
"golang.org/x/sync/semaphore"
"github.com/prometheus/client_golang/prometheus"
"github.com/Cloud-Foundations/cloud-gate/broker"
"github.com/Cloud-Foundations/cloud-gate/broker/configuration"
"github.com/Cloud-Foundations/golib/pkg/auth/userinfo"
"github.com/Cloud-Foundations/golib/pkg/auth/userinfo/filter"
"github.com/Cloud-Foundations/golib/pkg/log"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/sts"
"gopkg.in/ini.v1"
)
// TODO: these should come in from config
const (
defaultRegion = "us-west-2"
masterAWSProfileName = "broker-master"
)
var (
awsListRolesAttempt = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "cloudgate_aws_listroles_attempt_counter",
Help: "Attempts to ListRoles from AWS",
},
[]string{"accountName"},
)
awsListRolesSuccess = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "cloudgate_aws_listroles_success_counter",
Help: "Success count of listRoles on AWS",
},
[]string{"accountName"},
)
awsAssumeRoleAttempt = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "cloudgate_aws_assumerole_attempt_counter",
Help: "Success count of assumeRole on AWS",
},
[]string{"accountName", "roleName"},
)
awsAssumeRoleSuccess = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "cloudgate_aws_assumerole_success_counter",
Help: "Success count of assumeRole on AWS",
},
[]string{"accountName", "roleName"},
)
)
func init() {
prometheus.MustRegister(awsListRolesAttempt)
prometheus.MustRegister(awsListRolesSuccess)
prometheus.MustRegister(awsAssumeRoleAttempt)
prometheus.MustRegister(awsAssumeRoleSuccess)
}
const maxRoleRequestsInFlight = 10
func newBroker(userInfo userinfo.UserGroupsGetter, credentialsFilename string,
listRolesRoleName string, logger log.DebugLogger,
auditLogger log.DebugLogger) *Broker {
if listRolesRoleName == "" {
listRolesRoleName = defaultListRolesRoleName
}
return &Broker{
rawUserInfo: userInfo,
credentialsFilename: credentialsFilename,
logger: logger,
auditLogger: auditLogger,
listRolesRoleName: listRolesRoleName,
listRolesSemaphore: semaphore.NewWeighted(int64(maxRoleRequestsInFlight)),
userAllowedCredentialsCache: make(
map[string]userAllowedCredentialsCacheEntry),
accountRoleCache: make(map[string]accountRoleCacheEntry),
isUnsealedChannel: make(chan error, 1),
profileCredentials: make(map[string]awsProfileEntry),
}
}
func (b *Broker) accountIDFromName(accountName string) (string, error) {
for _, account := range b.config.AWS.Account {
if account.Name == accountName {
return account.AccountID, nil
}
}
return "", errors.New("accountNAme not found")
}
func (b *Broker) accountHumanNameFromName(accountName string) (string, error) {
for _, account := range b.config.AWS.Account {
if account.Name == accountName {
if account.DisplayName != "" {
return account.DisplayName, nil
}
return account.Name, nil
}
}
return "", errors.New("accountNAme not found")
}
func (b *Broker) processNewUnsealingSecret(secret string) (ready bool, err error) {
// if already loaded then fast quit
// probably add some mutex here
if b.credentialsFilename == "" || len(b.profileCredentials) > 0 {
return true, nil
}
decbuf := bytes.NewBuffer(b.rawCredentialsFile)
armorBlock, err := armor.Decode(decbuf)
if err != nil {
b.logger.Printf("Cannot decode armored file")
return false, err
}
password := []byte(secret)
failed := false
prompt := func(keys []openpgp.Key, symmetric bool) ([]byte, error) {
// If the given passphrase isn't correct, the function will be called
// again, forever. This method will fail fast.
// Ref: https://godoc.org/golang.org/x/crypto/openpgp#PromptFunction
if failed {
return nil, errors.New("decryption failed")
}
failed = true
return password, nil
}
md, err := openpgp.ReadMessage(armorBlock.Body, nil, prompt, nil)
if err != nil {
b.logger.Printf("cannot read message")
return false, err
}
plaintextBytes, err := ioutil.ReadAll(md.UnverifiedBody)
if err != nil {
return false, err
}
err = b.loadCredentialsFrombytes(plaintextBytes)
if err != nil {
return false, nil
}
return true, nil
}
func (b *Broker) loadCredentialsFile() (err error) {
if b.credentialsFilename == "" {
b.isUnsealedChannel <- nil
return nil
}
b.rawCredentialsFile, err = ioutil.ReadFile(b.credentialsFilename)
if err != nil {
return nil
}
fileAsString := string(b.rawCredentialsFile[:])
if strings.HasPrefix(fileAsString, "-----BEGIN PGP MESSAGE-----") {
return nil
}
return b.loadCredentialsFrombytes(b.rawCredentialsFile)
}
func (b *Broker) loadCredentialsFrombytes(credentials []byte) error {
cfg, err := ini.Load(credentials)
if err != nil {
return err
}
sections := cfg.SectionStrings()
for _, profileName := range sections {
accessKeyID := cfg.Section(profileName).Key(
"aws_access_key_id").String()
secretAccessKey := cfg.Section(profileName).Key(
"aws_secret_access_key").String()
if len(accessKeyID) < 3 || len(secretAccessKey) < 3 {
continue
}
region := cfg.Section(profileName).Key("region").String()
if region == "" {
region = defaultRegion
}
entry := awsProfileEntry{AccessKeyID: accessKeyID,
SecretAccessKey: secretAccessKey,
Region: region}
b.profileCredentials[profileName] = entry
}
if len(b.profileCredentials) < 1 {
return errors.New("nothing loaded")
}
//it is now unsealed
b.isUnsealedChannel <- nil
return nil
}
// Returns an AWS *Credentials and region name, returns nil if credentials
// cannot be found.
func (b *Broker) getCredentialsFromProfile(profileName string) (
*credentials.Credentials, string, error) {
profileEntry, ok := b.profileCredentials[profileName]
if !ok {
if profileName == masterAWSProfileName {
return b.getCredentialsFromMetaData()
}
return nil, "", errors.New("invalid credentials name")
}
sessionCredentials := credentials.NewStaticCredentials(
profileEntry.AccessKeyID, profileEntry.SecretAccessKey, "")
return sessionCredentials, profileEntry.Region, nil
}
func (b *Broker) getCredentialsFromMetaData() (
*credentials.Credentials, string, error) {
creds := credentials.NewCredentials(&ec2rolecreds.EC2RoleProvider{
Client: ec2metadata.New(session.New(&aws.Config{})),
ExpiryWindow: time.Minute,
})
if creds == nil {
return nil, "", errors.New("unable to get EC2 role credentials")
}
return creds, defaultRegion, nil
}
const profileAssumeRoleDurationSeconds = 3600
func (b *Broker) withProfileAssumeRole(accountName string, profileName string,
roleName string,
roleSessionName string) (*sts.AssumeRoleOutput, string, error) {
sessionCredentials, region, err := b.getCredentialsFromProfile(profileName)
if err != nil {
return nil, "", err
}
if sessionCredentials == nil {
return nil, "", fmt.Errorf("No valid profile=%s", profileName)
}
masterSession, err := session.NewSession(
aws.NewConfig().WithCredentials(sessionCredentials).WithRegion(region))
if err != nil {
return nil, "", err
}
if masterSession == nil {
return nil, "", errors.New("masterSession == nil")
}
stsClient := sts.New(masterSession)
b.logger.Debugf(2, "stsClient=%v", stsClient)
var durationSeconds int64
durationSeconds = profileAssumeRoleDurationSeconds
accountID, err := b.accountIDFromName(accountName)
if err != nil {
return nil, "", err
}
arnRolePrefix := "arn:aws:iam"
if strings.HasPrefix(region, "us-gov-") {
arnRolePrefix = "arn:aws-us-gov:iam"
}
roleArn := fmt.Sprintf("%s::%s:role/%s", arnRolePrefix, accountID, roleName)
b.logger.Debugf(2, "calling sts.AssumeRole(role=%s, sessionName=%s)\n",
roleArn, roleSessionName)
assumeRoleInput := sts.AssumeRoleInput{
DurationSeconds: &durationSeconds,
RoleArn: &roleArn,
RoleSessionName: &roleSessionName,
}
awsAssumeRoleAttempt.WithLabelValues(accountName, roleName).Inc()
assumeRoleOutput, err := stsClient.AssumeRole(&assumeRoleInput)
if err == nil {
awsAssumeRoleSuccess.WithLabelValues(accountName, roleName).Inc()
}
return assumeRoleOutput, region, err
}
const getAWSRolesTimeout = 10 * time.Second
func (b *Broker) withSessionGetAWSRoleList(validSession *session.Session, accountName string) ([]string, error) {
iamClient := iam.New(validSession)
var maxItems int64
maxItems = 500
listRolesInput := iam.ListRolesInput{MaxItems: &maxItems}
var roleNames []string
ctx := context.TODO()
if err := b.listRolesSemaphore.Acquire(ctx, 1); err != nil {
b.logger.Printf("Failed to acquire semaphore: %v", err)
return nil, err
}
defer b.listRolesSemaphore.Release(1)
c := make(chan error, 1)
go func() {
awsListRolesAttempt.WithLabelValues(accountName).Inc()
err := iamClient.ListRolesPages(&listRolesInput,
func(listRolesOutput *iam.ListRolesOutput, lastPage bool) bool {
b.logger.Debugf(2, "listrolesoutput =%v", listRolesOutput)
b.logger.Debugf(2, "loop, lastPage=%s", lastPage)
for _, role := range listRolesOutput.Roles {
roleNames = append(roleNames, *role.RoleName)
}
return !lastPage
})
c <- err
}()
select {
case getRolesErr := <-c:
if getRolesErr != nil {
return nil, getRolesErr
}
case <-time.After(getAWSRolesTimeout):
return nil, fmt.Errorf("AWS Get roles had a timeout for account %s", accountName)
}
awsListRolesSuccess.WithLabelValues(accountName).Inc()
sort.Strings(roleNames)
b.logger.Debugf(1, "roleNames(v =%v)", roleNames)
return roleNames, nil
}
func (b *Broker) masterGetAWSRolesForAccount(accountName string) ([]string, error) {
b.logger.Debugf(1, "top of masterGetAWSRolesForAccount for account =%s",
accountName)
assumeRoleOutput, region, err := b.withProfileAssumeRole(accountName, masterAWSProfileName, b.listRolesRoleName, "brokermaster")
if err != nil {
b.logger.Debugf(0, "cannot assume master role for account %s, err=%s", accountName, err)
return nil, err
}
b.logger.Debugf(2, "assume role success for account=%s, roleoutput=%v", accountName, assumeRoleOutput)
sessionCredentials := credentials.NewStaticCredentials(*assumeRoleOutput.Credentials.AccessKeyId,
*assumeRoleOutput.Credentials.SecretAccessKey, *assumeRoleOutput.Credentials.SessionToken)
assumedSession := session.Must(session.NewSession(aws.NewConfig().WithCredentials(sessionCredentials).WithRegion(region)))
return b.withSessionGetAWSRoleList(assumedSession, accountName)
}
func (b *Broker) getAWSRolesForAccountNonCached(accountName string) ([]string, error) {
b.logger.Debugf(1, "top of getAWSRolesForAccountNonCached for account =%s",
accountName)
accountRoles, err := b.masterGetAWSRolesForAccount(accountName)
if err == nil {
return accountRoles, nil
}
b.logger.Printf("Doing fallback for accountName=%s", accountName)
// Master role does not work, try fallback with direct account
profileName := accountName
sessionCredentials, region, err := b.getCredentialsFromProfile(profileName)
if err != nil {
return nil, err
}
if sessionCredentials == nil {
return nil, errors.New(fmt.Sprintf("no valid profile=%s", profileName))
}
// This is strange, no error calling?
accountSession := session.Must(session.NewSession(aws.NewConfig().WithCredentials(sessionCredentials).WithRegion(region)))
return b.withSessionGetAWSRoleList(accountSession, accountName)
}
const roleCacheDuration = time.Second * 1800
const negativeCacheSeconds = 15
func (b *Broker) getAWSRolesForAccount(accountName string) ([]string, error) {
b.logger.Debugf(1, "top of getAWSRolesForAccount for account =%s",
accountName)
b.accountRoleMutex.Lock()
cachedEntry, ok := b.accountRoleCache[accountName]
b.accountRoleMutex.Unlock()
if ok {
if cachedEntry.Expiration.After(time.Now()) {
b.logger.Debugf(1, "Got roles from cache")
return cachedEntry.Roles, nil
}
if cachedEntry.LastBadTime.After(time.Now().Add(time.Second * -(negativeCacheSeconds))) {
b.logger.Debugf(1, "getAWSRolesForAccount. Returning recently stale data from cache")
return cachedEntry.Roles, nil
}
// Entry has expired
value, err := b.getAWSRolesForAccountNonCached(accountName)
if err != nil {
// For availability reasons, we prefer to allow users to
// continue using the cloudgate-server on expired AWS data
// This allow us to continue to operate on transient AWS
// errors.
b.logger.Printf("Failure gettting non-cached roles, using expired cache")
cachedEntry.LastBadTime = time.Now()
b.accountRoleMutex.Lock()
b.accountRoleCache[accountName] = cachedEntry
b.accountRoleMutex.Unlock()
return cachedEntry.Roles, nil
}
cachedEntry.Roles = value
cachedEntry.Expiration = time.Now().Add(roleCacheDuration)
b.accountRoleMutex.Lock()
b.accountRoleCache[accountName] = cachedEntry
b.accountRoleMutex.Unlock()
return value, nil
}
value, err := b.getAWSRolesForAccountNonCached(accountName)
if err != nil {
return value, err
}
cachedEntry.Roles = value
cachedEntry.Expiration = time.Now().Add(roleCacheDuration)
b.accountRoleMutex.Lock()
b.accountRoleCache[accountName] = cachedEntry
b.accountRoleMutex.Unlock()
return value, nil
}
func stringIntersectionNoDups(set1, set2 []string) (intersection []string) {
stringMap := make(map[string]string, len(set1))
for _, v1 := range set1 {
stringMap[strings.ToLower(v1)] = v1
}
for _, v2 := range set2 {
v1, ok := stringMap[strings.ToLower(v2)]
if ok {
intersection = append(intersection, v1)
}
}
return intersection
}
func (b *Broker) getUserAllowedAccountsFromGroups(userGroups []string) ([]broker.PermittedAccount, error) {
b.logger.Debugf(1,
"top of getUserAllowedAccountsFromGroups for userGroups: %v",
userGroups)
groupToAccountName := make(map[string]string)
var groupList []string
for _, account := range b.config.AWS.Account {
groupName := account.GroupName
if len(groupName) == 0 {
groupName = account.Name
}
groupName = strings.ToLower(groupName)
groupToAccountName[groupName] = account.Name
groupList = append(groupList, groupName)
}
var allowedRoles map[string][]string
allowedRoles = make(map[string][]string)
for _, accountName := range groupList {
reString := fmt.Sprintf("(?i)^%s-(.*)$", accountName)
b.logger.Debugf(2, "reString=%v", reString)
re, err := regexp.Compile(reString)
if err != nil {
return nil, err
}
for _, group := range userGroups {
matches := re.FindStringSubmatch(group)
b.logger.Debugf(4, "matches-XXX=%v %d", matches, len(matches))
if len(matches) == 2 {
b.logger.Debugf(2, "matches=%v", matches)
accountGroupName := accountName
allowedRoles[accountGroupName] = append(allowedRoles[accountGroupName], matches[1])
}
}
}
b.logger.Debugf(1, "allowedRoles(pre)=%v", allowedRoles)
//now add extra roles:
for _, account := range b.config.AWS.Account {
if len(account.ExtraUserRoles) < 1 {
continue
}
if currentValue, ok := allowedRoles[account.Name]; ok {
allowedRoles[account.Name] = append(currentValue, account.ExtraUserRoles...)
} else {
allowedRoles[account.Name] = account.ExtraUserRoles
}
}
b.logger.Debugf(1, "allowedRoles(post)=%v", allowedRoles)
var permittedAccounts []broker.PermittedAccount
var mux sync.Mutex
var wg sync.WaitGroup
for groupName, allowedRoles := range allowedRoles {
accountName, ok := groupToAccountName[groupName]
if !ok {
return nil, errors.New("Cannot map to accountname for some username")
}
displayName, err := b.accountHumanNameFromName(accountName)
if err != nil {
return nil, err
}
wg.Add(1)
go func(accountName string, displayName string, allowedRoles []string) {
defer wg.Done()
rolesForAccount, err := b.getAWSRolesForAccount(accountName)
if err != nil {
b.logger.Printf("Error getting profile for account %s: %s", accountName, err)
return
}
allowedAndAvailable := stringIntersectionNoDups(rolesForAccount, allowedRoles)
if len(allowedAndAvailable) < 1 {
return
}
sort.Strings(allowedAndAvailable)
var account = broker.PermittedAccount{Name: accountName,
HumanName: displayName,
PermittedRoleName: allowedAndAvailable}
mux.Lock()
defer mux.Unlock()
permittedAccounts = append(permittedAccounts, account)
}(accountName, displayName, allowedRoles)
}
wg.Wait()
b.logger.Debugf(1, "permittedAccounts=%+v", permittedAccounts)
return permittedAccounts, nil
}
func (b *Broker) getUserAllowedAccountsNonCached(username string) ([]broker.PermittedAccount, error) {
if b.config == nil {
return nil, errors.New("nil config")
}
userGroups, err := b.userInfo.GetUserGroups(username)
if err != nil {
return nil, err
}
b.logger.Debugf(1, "UserGroups for '%s' =%+v", username, userGroups)
return b.getUserAllowedAccountsFromGroups(userGroups)
}
const cacheDuration = time.Second * 300
func (b *Broker) getUserAllowedAccounts(username string) ([]broker.PermittedAccount, error) {
b.userAllowedCredentialsMutex.Lock()
cachedEntry, ok := b.userAllowedCredentialsCache[username]
b.userAllowedCredentialsMutex.Unlock()
if ok {
if cachedEntry.Expiration.After(time.Now()) {
b.logger.Debugf(1, "Got authz from cache")
return cachedEntry.PermittedAccounts, nil
}
// entry is expired
value, err := b.getUserAllowedAccountsNonCached(username)
if err != nil {
b.logger.Printf("Failure gettting non-cached, using expired cache")
return cachedEntry.PermittedAccounts, nil
}
cachedEntry.PermittedAccounts = value
cachedEntry.Expiration = time.Now().Add(cacheDuration)
b.userAllowedCredentialsMutex.Lock()
b.userAllowedCredentialsCache[username] = cachedEntry
b.userAllowedCredentialsMutex.Unlock()
return value, nil
}
value, err := b.getUserAllowedAccountsNonCached(username)
if err != nil {
b.logger.Printf("getUserAllowedAccounts: Failure gettting userinfo for non-cached user: %s. Err: %s", username, err)
return value, err
}
cachedEntry.PermittedAccounts = value
cachedEntry.Expiration = time.Now().Add(cacheDuration)
b.userAllowedCredentialsMutex.Lock()
b.userAllowedCredentialsCache[username] = cachedEntry
b.userAllowedCredentialsMutex.Unlock()
return value, nil
}
func (b *Broker) isUserAllowedToAssumeRole(username string, accountName string, roleName string) (bool, error) {
// TODO: could be made more efficient, dont need to know all accounts, just one account.
permittedAccount, err := b.getUserAllowedAccounts(username)
if err != nil {
return false, err
}
for _, account := range permittedAccount {
if account.Name != accountName {
continue
}
for _, permittedRoleName := range account.PermittedRoleName {
if permittedRoleName == roleName {
return true, nil
}
}
}
return false, nil
}
type ExchangeCredentialsJSON struct {
SessionId string `json:"sessionId"`
SessionKey string `json:"sessionKey"`
SessionToken string `json:"sessionToken"`
}
type SessionTokenResponseJSON struct {
SigninToken string `json:"SigninToken"`
}
const consoleSessionDurationSeconds = "43000" //3600 * 12
func (b *Broker) getConsoleURLForAccountRole(accountName string, roleName string, userName string, issuerURL string) (string, error) {
assumeRoleOutput, region, err := b.withProfileAssumeRole(accountName, masterAWSProfileName, roleName, userName)
if err != nil {
b.logger.Debugf(1, "cannot assume role for account %s with master account, err=%s ", accountName, err)
// try using a direct role if possible then
assumeRoleOutput, region, err = b.withProfileAssumeRole(accountName, accountName, roleName, userName)
if err != nil {
b.logger.Printf("cannot assume role for account %s, err=%s", accountName, err)
return "", err
}
}
b.logger.Debugf(2, "assume role success for account=%s, roleoutput=%v", accountName, assumeRoleOutput)
sessionCredentials := ExchangeCredentialsJSON{
SessionId: *assumeRoleOutput.Credentials.AccessKeyId,
SessionKey: *assumeRoleOutput.Credentials.SecretAccessKey,
SessionToken: *assumeRoleOutput.Credentials.SessionToken,
}
b.logger.Debugf(2, "sessionCredentials=%v", sessionCredentials)
bcreds, err := json.Marshal(sessionCredentials)
if err != nil {
return "", err
}
creds := url.QueryEscape(string(bcreds[:]))
b.logger.Debugf(1, "sessionCredentials-escaped=%v", creds)
federationUrl := "https://signin.aws.amazon.com/federation"
awsDestinationURL := "https://console.aws.amazon.com/"
if strings.HasPrefix(region, "us-gov-") {
federationUrl = "https://signin.amazonaws-us-gov.com/federation"
awsDestinationURL = "https://console.amazonaws-us-gov.com/"
}
req, err := http.NewRequest("GET", federationUrl, nil)
if err != nil {
return "", err
}
q := req.URL.Query()
q.Add("Action", "getSigninToken")
q.Add("Session", string(bcreds[:]))
q.Add("SessionDuration", consoleSessionDurationSeconds)
req.URL.RawQuery = q.Encode()
b.logger.Debugf(2, "req=%+v", req)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
b.logger.Debugf(2, "resp=%+v", resp)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
if resp.StatusCode >= 300 {
return "", fmt.Errorf(string(body))
}
b.logger.Debugf(1, "resp=%s", string(body))
var tokenOutput SessionTokenResponseJSON
err = json.Unmarshal(body, &tokenOutput)
if err != nil {
return "", err
}
b.logger.Debugf(1, "Issuer=%s", issuerURL)
encodedIssuer := url.QueryEscape(issuerURL)
targetUrl := fmt.Sprintf("%s?Action=login&Issuer=%s&Destination=%s&SigninToken=%s", federationUrl, encodedIssuer, awsDestinationURL, tokenOutput.SigninToken)
b.logger.Debugf(1, "targetURL=%s", targetUrl)
b.auditLogger.Printf("Console url generated for: %s on account %s role %s", userName, accountName, roleName)
return targetUrl, nil
}
func (b *Broker) generateTokenCredentials(accountName string, roleName string, userName string) (*broker.AWSCredentialsJSON, error) {
assumeRoleOutput, region, err := b.withProfileAssumeRole(accountName, masterAWSProfileName, roleName, userName)
if err != nil {
b.logger.Debugf(1, "cannot assume role for account %s with master account, err=%s ", accountName, err)
// try using a direct role if possible then
assumeRoleOutput, region, err = b.withProfileAssumeRole(accountName, accountName, roleName, userName)
if err != nil {
b.logger.Printf("cannot assume role for account %s, err=%s", accountName, err)
return nil, err
}
}
b.logger.Debugf(2, "assume role success for account=%s, roleoutput=%v", accountName, assumeRoleOutput)
if !strings.HasPrefix(region, "us-gov-") {
region = ""
}
outVal := broker.AWSCredentialsJSON{
SessionId: *assumeRoleOutput.Credentials.AccessKeyId,
SessionKey: *assumeRoleOutput.Credentials.SecretAccessKey,
SessionToken: *assumeRoleOutput.Credentials.SessionToken,
Region: region,
Expiration: time.Now().Add(time.Second * profileAssumeRoleDurationSeconds),
}
b.auditLogger.Printf("Token credentials (KeyId %s) generated for: %s on account %s role %s",
*assumeRoleOutput.Credentials.AccessKeyId, userName, accountName, roleName)
return &outVal, nil
}
func (b *Broker) updateConfiguration(
config *configuration.Configuration) error {
if config == nil {
return errors.New("nill config passed")
}
if config.AWS.GroupPrefix == "" {
b.userInfo = b.rawUserInfo
} else {
ui, err := filter.NewUserGroupsFilter(b.rawUserInfo,
"^"+config.AWS.GroupPrefix)
if err != nil {
return err
}
b.userInfo = ui
}
b.logger.Debugf(1, "config=%+v", *config)
b.config = config
return nil
}