Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for IAM in secure storage + MFA issue #557

Merged
merged 1 commit into from
Nov 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
64 changes: 52 additions & 12 deletions pkg/cfaws/assumer_aws_iam.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/credentials/stscreds"
"github.com/aws/aws-sdk-go-v2/service/sts"
"github.com/aws/aws-sdk-go-v2/service/sts/types"
Expand All @@ -22,27 +23,58 @@ type AwsIamAssumer struct {
// Default behaviour is to use the sdk to retrieve the credentials from the file
// For launching the console there is an extra step GetFederationToken that happens after this to get a session token
func (aia *AwsIamAssumer) AssumeTerminal(ctx context.Context, c *Profile, configOpts ConfigOpts) (aws.Credentials, error) {
if c.HasSecureStorageIAMCredentials {
secureIAMCredentialStorage := securestorage.NewSecureIAMCredentialStorage()
return secureIAMCredentialStorage.GetCredentials(c.Name)
}

// check if the valid credentials are available in session credential store

sessionCredStorage := securestorage.NewSecureSessionCredentialStorage()

cachedCreds, ok, err := sessionCredStorage.GetCredentials(c.AWSConfig.Profile)
cachedCreds, err := sessionCredStorage.GetCredentials(c.AWSConfig.Profile)
if err != nil {
return aws.Credentials{}, err
}

if ok && !cachedCreds.Expired() {
clio.Debugw("error loading cached credentials", "error", err)
} else if cachedCreds != nil && !cachedCreds.Expired() {
clio.Debugw("credentials found in cache", "expires", cachedCreds.Expires.String(), "canExpire", cachedCreds.CanExpire, "timeNow", time.Now().String())
return cachedCreds, err
return *cachedCreds, err
}

clio.Debugw("refreshing credentials", "reason", "not found")

if c.HasSecureStorageIAMCredentials {
secureIAMCredentialStorage := securestorage.NewSecureIAMCredentialStorage()
creds, err := secureIAMCredentialStorage.GetCredentials(c.Name)
if err != nil {
return aws.Credentials{}, err
}
/**If the IAM credentials in secure storage are valid and no MFA is required:
*[profile example]
*region = us-west-2
*credential_process = dgranted credential-process --profile=example
**/
if c.AWSConfig.MFASerial == "" {
return creds, nil
}

cfg, err := config.LoadDefaultConfig(ctx, config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(creds.AccessKeyID, creds.SecretAccessKey, creds.SessionToken)))
if err != nil {
return aws.Credentials{}, err
}
/**If the IAM credentials in secure storage MFA is required:
*[profile example]
*region = us-west-2
*mfa_serial = arn:aws:iam::616777145260:mfa
*credential_process = dgranted credential-process --profile=example
**/
clio.Debugw("generating temporary credentials", "assumer", aia.Type(), "profile_type", "base_profile_with_mfa")
creds, err = aia.getTemporaryCreds(ctx, cfg, c, configOpts)
if err != nil {
return aws.Credentials{}, err
}

if err := sessionCredStorage.StoreCredentials(c.AWSConfig.Profile, creds); err != nil {
clio.Warnf("Error caching credentials, MFA token will be requested before current token is expired")
}

return creds, nil
}

//using ~/.aws/credentials file for creds
opts := []func(*config.LoadOptions) error{
// load the config profile
Expand All @@ -66,7 +98,15 @@ func (aia *AwsIamAssumer) AssumeTerminal(ctx context.Context, c *Profile, config
}
aro.Duration = configOpts.Duration

// If the mfa_serial is defined on the root profile, we need to set it in this config so that the aws SDK knows to prompt for MFA token
/**If the mfa_serial is defined on the root profile, we need to set it in this config so that the aws SDK knows to prompt for MFA token:
*[profile base]
*region = us-west-2
*mfa_serial = arn:aws:iam::616777145260:mfa

*[profile prod]
*role_arn = XXXXXXX
*source_profile = base
**/
if len(c.Parents) > 0 {
if c.Parents[0].AWSConfig.MFASerial != "" {
aro.SerialNumber = aws.String(c.Parents[0].AWSConfig.MFASerial)
Expand Down
114 changes: 58 additions & 56 deletions pkg/granted/credential_process.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,79 +39,81 @@ var CredentialProcess = cli.Command{
if err != nil {
return err
}
var needsRefresh bool
var credentials aws.Credentials

profileName := c.String("profile")
autoLogin := c.Bool("auto-login")
secureSessionCredentialStorage := securestorage.NewSecureSessionCredentialStorage()
clio.Debugw("running credential process with config", "profile", profileName, "url", c.String("url"), "window", c.Duration("window"), "disableCredentialProcessCache", cfg.DisableCredentialProcessCache)
if !cfg.DisableCredentialProcessCache {
creds, ok, err := secureSessionCredentialStorage.GetCredentials(profileName)
if err != nil {
return err
}
if !ok {
clio.Debugw("refreshing credentials", "reason", "not found")
needsRefresh = true
} else {
clio.Debugw("credentials found in cache", "expires", creds.Expires.String(), "canExpire", creds.CanExpire, "timeNow", time.Now().String(), "refreshIfBeforeNow", creds.Expires.Add(-c.Duration("window")).String())
if creds.CanExpire && creds.Expires.Add(-c.Duration("window")).Before(time.Now()) {
clio.Debugw("refreshing credentials", "reason", "credentials are expired")
needsRefresh = true
} else {
clio.Debugw("using cached credentials")
credentials = creds
}
}
} else {
clio.Debugw("refreshing credentials", "reason", "credential process cache is disabled via config")
needsRefresh = true
}

if needsRefresh {
profiles, err := cfaws.LoadProfiles()
if err != nil {
return err
}
useCache := !cfg.DisableCredentialProcessCache

profile, err := profiles.LoadInitialisedProfile(c.Context, profileName)
if useCache {
// try and look up session credentials from the secure storage cache.
cachedCreds, err := secureSessionCredentialStorage.GetCredentials(profileName)
if err != nil {
return err
clio.Debugw("error loading cached credentials", "error", err)
} else if cachedCreds == nil {
clio.Debugw("refreshing credentials", "reason", "cachedCreds was nil")
} else if cachedCreds.CanExpire && cachedCreds.Expires.Add(-c.Duration("window")).Before(time.Now()) {
clio.Debugw("refreshing credentials", "reason", "credentials are expired")
} else {
// if we get here, the cached session credentials are valid
clio.Debugw("credentials found in cache", "expires", cachedCreds.Expires.String(), "canExpire", cachedCreds.CanExpire, "timeNow", time.Now().String(), "refreshIfBeforeNow", cachedCreds.Expires.Add(-c.Duration("window")).String())
return printCredentials(*cachedCreds)
}
}

duration := time.Hour
if profile.AWSConfig.RoleDurationSeconds != nil {
duration = *profile.AWSConfig.RoleDurationSeconds
}
if !useCache {
clio.Debugw("refreshing credentials", "reason", "credential process cache is disabled via config")
}

credentials, err = profile.AssumeTerminal(c.Context, cfaws.ConfigOpts{Duration: duration, UsingCredentialProcess: true, CredentialProcessAutoLogin: autoLogin})
if err != nil {
return err
}
if !cfg.DisableCredentialProcessCache {
clio.Debugw("storing refreshed credentials in credential process cache", "expires", credentials.Expires.String(), "canExpire", credentials.CanExpire, "timeNow", time.Now().String())
if err := secureSessionCredentialStorage.StoreCredentials(profileName, credentials); err != nil {
return err
}
}
profiles, err := cfaws.LoadProfiles()
if err != nil {
return err
}

out := awsCredsStdOut{
Version: 1,
AccessKeyID: credentials.AccessKeyID,
SecretAccessKey: credentials.SecretAccessKey,
SessionToken: credentials.SessionToken,
profile, err := profiles.LoadInitialisedProfile(c.Context, profileName)
if err != nil {
return err
}
if credentials.CanExpire {
out.Expiration = credentials.Expires.Format(time.RFC3339)

duration := time.Hour
if profile.AWSConfig.RoleDurationSeconds != nil {
duration = *profile.AWSConfig.RoleDurationSeconds
}

jsonOut, err := json.Marshal(out)
credentials, err := profile.AssumeTerminal(c.Context, cfaws.ConfigOpts{Duration: duration, UsingCredentialProcess: true, CredentialProcessAutoLogin: autoLogin})
if err != nil {
return errors.Wrap(err, "marshalling session credentials")
return err
}
if !cfg.DisableCredentialProcessCache {
clio.Debugw("storing refreshed credentials in credential process cache", "expires", credentials.Expires.String(), "canExpire", credentials.CanExpire, "timeNow", time.Now().String())
if err := secureSessionCredentialStorage.StoreCredentials(profileName, credentials); err != nil {
return err
}
}

fmt.Println(string(jsonOut))
return nil
return printCredentials(credentials)
},
}

func printCredentials(creds aws.Credentials) error {

out := awsCredsStdOut{
Version: 1,
AccessKeyID: creds.AccessKeyID,
SecretAccessKey: creds.SecretAccessKey,
SessionToken: creds.SessionToken,
}
if creds.CanExpire {
out.Expiration = creds.Expires.Format(time.RFC3339)
}

jsonOut, err := json.Marshal(out)
if err != nil {
return errors.Wrap(err, "marshalling session credentials")
}

fmt.Println(string(jsonOut))
return nil
}
20 changes: 12 additions & 8 deletions pkg/securestorage/session_credential_storage.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package securestorage

import (
"github.com/99designs/keyring"
"github.com/aws/aws-sdk-go-v2/aws"
)

Expand All @@ -17,14 +16,19 @@ func NewSecureSessionCredentialStorage() SessionCredentialSecureStorage {
}
}

func (i *SessionCredentialSecureStorage) GetCredentials(profile string) (credentials aws.Credentials, ok bool, err error) {
err = i.SecureStorage.Retrieve(profile, &credentials)
if err == keyring.ErrKeyNotFound {
err = nil
} else if err == nil {
ok = true
func (i *SessionCredentialSecureStorage) GetCredentials(profile string) (*aws.Credentials, error) {
// by default, set the credentials to be expiring so that we force a refresh if there are
// any problems unmarshalling them.
credentials := aws.Credentials{
CanExpire: true,
}
return

err := i.SecureStorage.Retrieve(profile, &credentials)
if err != nil {
return nil, err
}

return &credentials, nil
}

func (i *SessionCredentialSecureStorage) StoreCredentials(profile string, credentials aws.Credentials) (err error) {
Expand Down