-
Notifications
You must be signed in to change notification settings - Fork 4.3k
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
5844 AWS Root Credential Rotation #9921
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
fb63f60
strip redundant field type declarations
tyrannosaurus-becks 4e57223
root credential rotation for aws creds plugin
tyrannosaurus-becks 7c1aab7
correct port in doc
tyrannosaurus-becks f82b235
Change location of mocks awsutil and update methods that no longer exist
e160731
Update website/pages/docs/auth/aws.mdx
dab9205
Update sdk version to get the awsutil mock file
be9bb27
Re-vendor modules to pass CI
d723743
Use write lock for the entirety of AWS root cred rotation
57dd072
Update docs for AWS root cred rotation for clarity
10035c1
Merge branch 'master' into 5844-aws-root-cred-rotation
8db2c38
Merge branch 'master' into 5844-aws-root-cred-rotation
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,210 @@ | ||
package awsauth | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
|
||
"github.com/aws/aws-sdk-go/aws" | ||
"github.com/aws/aws-sdk-go/aws/credentials" | ||
"github.com/aws/aws-sdk-go/aws/session" | ||
"github.com/aws/aws-sdk-go/service/ec2" | ||
"github.com/aws/aws-sdk-go/service/iam" | ||
"github.com/aws/aws-sdk-go/service/iam/iamiface" | ||
"github.com/hashicorp/errwrap" | ||
"github.com/hashicorp/go-cleanhttp" | ||
"github.com/hashicorp/go-multierror" | ||
"github.com/hashicorp/vault/sdk/framework" | ||
"github.com/hashicorp/vault/sdk/helper/awsutil" | ||
"github.com/hashicorp/vault/sdk/logical" | ||
) | ||
|
||
func (b *backend) pathConfigRotateRoot() *framework.Path { | ||
return &framework.Path{ | ||
Pattern: "config/rotate-root", | ||
|
||
Operations: map[logical.Operation]framework.OperationHandler{ | ||
logical.UpdateOperation: &framework.PathOperation{ | ||
Callback: b.pathConfigRotateRootUpdate, | ||
}, | ||
}, | ||
|
||
HelpSynopsis: pathConfigRotateRootHelpSyn, | ||
HelpDescription: pathConfigRotateRootHelpDesc, | ||
} | ||
} | ||
|
||
func (b *backend) pathConfigRotateRootUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) { | ||
// First get the AWS key and secret and validate that we _can_ rotate them. | ||
// We need the read lock here to prevent anything else from mutating it while we're using it. | ||
b.configMutex.Lock() | ||
defer b.configMutex.Unlock() | ||
|
||
clientConf, err := b.nonLockedClientConfigEntry(ctx, req.Storage) | ||
if err != nil { | ||
return nil, err | ||
} | ||
if clientConf == nil { | ||
return logical.ErrorResponse(`can't update client config because it's unset`), nil | ||
} | ||
if clientConf.AccessKey == "" { | ||
return logical.ErrorResponse("can't update access_key because it's unset"), nil | ||
} | ||
if clientConf.SecretKey == "" { | ||
return logical.ErrorResponse("can't update secret_key because it's unset"), nil | ||
} | ||
|
||
// Getting our client through the b.clientIAM method requires values retrieved through | ||
// the user providing an ARN, which we don't have here, so let's just directly | ||
// make what we need. | ||
staticCreds := &credentials.StaticProvider{ | ||
Value: credentials.Value{ | ||
AccessKeyID: clientConf.AccessKey, | ||
SecretAccessKey: clientConf.SecretKey, | ||
}, | ||
} | ||
// By default, leave the iamEndpoint nil to tell AWS it's unset. However, if it is | ||
// configured, populate the pointer. | ||
var iamEndpoint *string | ||
if clientConf.IAMEndpoint != "" { | ||
iamEndpoint = aws.String(clientConf.IAMEndpoint) | ||
} | ||
|
||
// Attempt to retrieve the region, error out if no region is provided. | ||
region, err := awsutil.GetRegion("") | ||
if err != nil { | ||
return nil, errwrap.Wrapf("error retrieving region: {{err}}", err) | ||
} | ||
|
||
awsConfig := &aws.Config{ | ||
Credentials: credentials.NewCredentials(staticCreds), | ||
Endpoint: iamEndpoint, | ||
|
||
// Generally speaking, GetRegion will use the Vault server's region. However, if this | ||
// needs to be overridden, an easy way would be to set the AWS_DEFAULT_REGION on the Vault server | ||
// to the desired region. If that's still insufficient for someone's use case, in the future we | ||
// could add the ability to specify the region either on the client config or as part of the | ||
// inbound rotation call. | ||
Region: aws.String(region), | ||
|
||
// Prevents races. | ||
HTTPClient: cleanhttp.DefaultClient(), | ||
} | ||
sess, err := session.NewSession(awsConfig) | ||
if err != nil { | ||
return nil, err | ||
} | ||
iamClient := getIAMClient(sess) | ||
calvn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// Get the current user's name since it's required to create an access key. | ||
// Empty input means get the current user. | ||
var getUserInput iam.GetUserInput | ||
getUserRes, err := iamClient.GetUser(&getUserInput) | ||
if err != nil { | ||
return nil, errwrap.Wrapf("error calling GetUser: {{err}}", err) | ||
} | ||
if getUserRes == nil { | ||
return nil, fmt.Errorf("nil response from GetUser") | ||
} | ||
if getUserRes.User == nil { | ||
return nil, fmt.Errorf("nil user returned from GetUser") | ||
} | ||
if getUserRes.User.UserName == nil { | ||
return nil, fmt.Errorf("nil UserName returned from GetUser") | ||
} | ||
|
||
// Create the new access key and secret. | ||
createAccessKeyInput := iam.CreateAccessKeyInput{ | ||
UserName: getUserRes.User.UserName, | ||
} | ||
createAccessKeyRes, err := iamClient.CreateAccessKey(&createAccessKeyInput) | ||
if err != nil { | ||
return nil, errwrap.Wrapf("error calling CreateAccessKey: {{err}}", err) | ||
} | ||
if createAccessKeyRes.AccessKey == nil { | ||
return nil, fmt.Errorf("nil response from CreateAccessKey") | ||
} | ||
if createAccessKeyRes.AccessKey.AccessKeyId == nil || createAccessKeyRes.AccessKey.SecretAccessKey == nil { | ||
return nil, fmt.Errorf("nil AccessKeyId or SecretAccessKey returned from CreateAccessKey") | ||
} | ||
|
||
// We're about to attempt to store the newly created key and secret, but just in case we can't, | ||
// let's clean up after ourselves. | ||
storedNewConf := false | ||
var errs error | ||
defer func() { | ||
if storedNewConf { | ||
return | ||
} | ||
// Attempt to delete the access key and secret we created but couldn't store and use. | ||
deleteAccessKeyInput := iam.DeleteAccessKeyInput{ | ||
AccessKeyId: createAccessKeyRes.AccessKey.AccessKeyId, | ||
UserName: getUserRes.User.UserName, | ||
} | ||
if _, err := iamClient.DeleteAccessKey(&deleteAccessKeyInput); err != nil { | ||
// Include this error in the errs returned by this method. | ||
errs = multierror.Append(errs, fmt.Errorf("error deleting newly created but unstored access key ID %s: %s", *createAccessKeyRes.AccessKey.AccessKeyId, err)) | ||
} | ||
}() | ||
|
||
// Now get ready to update storage, doing everything beforehand so we can minimize how long | ||
// we need to hold onto the lock. | ||
newEntry, err := b.configClientToEntry(clientConf) | ||
if err != nil { | ||
errs = multierror.Append(errs, errwrap.Wrapf("error generating new client config JSON: {{err}}", err)) | ||
return nil, errs | ||
} | ||
|
||
oldAccessKey := clientConf.AccessKey | ||
clientConf.AccessKey = *createAccessKeyRes.AccessKey.AccessKeyId | ||
clientConf.SecretKey = *createAccessKeyRes.AccessKey.SecretAccessKey | ||
|
||
// Someday we may want to allow the user to send a number of seconds to wait here | ||
// before deleting the previous access key to allow work to complete. That would allow | ||
// AWS, which is eventually consistent, to finish populating the new key in all places. | ||
if err := req.Storage.Put(ctx, newEntry); err != nil { | ||
errs = multierror.Append(errs, errwrap.Wrapf("error saving new client config: {{err}}", err)) | ||
return nil, errs | ||
} | ||
storedNewConf = true | ||
|
||
// Previous cached clients need to be cleared because they may have been made using | ||
// the soon-to-be-obsolete credentials. | ||
b.IAMClientsMap = make(map[string]map[string]*iam.IAM) | ||
b.EC2ClientsMap = make(map[string]map[string]*ec2.EC2) | ||
|
||
// Now to clean up the old key. | ||
deleteAccessKeyInput := iam.DeleteAccessKeyInput{ | ||
AccessKeyId: aws.String(oldAccessKey), | ||
UserName: getUserRes.User.UserName, | ||
} | ||
if _, err = iamClient.DeleteAccessKey(&deleteAccessKeyInput); err != nil { | ||
errs = multierror.Append(errs, errwrap.Wrapf(fmt.Sprintf("error deleting old access key ID %s: {{err}}", oldAccessKey), err)) | ||
return nil, errs | ||
} | ||
return &logical.Response{ | ||
Data: map[string]interface{}{ | ||
"access_key": clientConf.AccessKey, | ||
}, | ||
}, nil | ||
} | ||
|
||
// getIAMClient allows us to change how an IAM client is created | ||
// during testing. The AWS SDK doesn't easily lend itself to testing | ||
// using a Go httptest server because if you inject a test URL into | ||
// the config, the client strips important information about which | ||
// endpoint it's hitting. Per | ||
// https://aws.amazon.com/blogs/developer/mocking-out-then-aws-sdk-for-go-for-unit-testing/, | ||
// this is the recommended approach. | ||
var getIAMClient = func(sess *session.Session) iamiface.IAMAPI { | ||
return iam.New(sess) | ||
} | ||
|
||
const pathConfigRotateRootHelpSyn = ` | ||
Request to rotate the AWS credentials used by Vault | ||
` | ||
|
||
const pathConfigRotateRootHelpDesc = ` | ||
This path attempts to rotate the AWS credentials used by Vault for this mount. | ||
It is only valid if Vault has been configured to use AWS IAM credentials via the | ||
config/client endpoint. | ||
` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
package awsauth | ||
|
||
import ( | ||
"context" | ||
"testing" | ||
"time" | ||
|
||
"github.com/aws/aws-sdk-go/aws" | ||
"github.com/aws/aws-sdk-go/aws/session" | ||
"github.com/aws/aws-sdk-go/service/iam" | ||
"github.com/aws/aws-sdk-go/service/iam/iamiface" | ||
"github.com/hashicorp/go-hclog" | ||
"github.com/hashicorp/vault/sdk/helper/awsutil" | ||
"github.com/hashicorp/vault/sdk/logical" | ||
) | ||
|
||
func TestPathConfigRotateRoot(t *testing.T) { | ||
getIAMClient = func(sess *session.Session) iamiface.IAMAPI { | ||
return &awsutil.MockIAM{ | ||
CreateAccessKeyOutput: &iam.CreateAccessKeyOutput{ | ||
AccessKey: &iam.AccessKey{ | ||
AccessKeyId: aws.String("fizz2"), | ||
SecretAccessKey: aws.String("buzz2"), | ||
}, | ||
}, | ||
DeleteAccessKeyOutput: &iam.DeleteAccessKeyOutput{}, | ||
GetUserOutput: &iam.GetUserOutput{ | ||
User: &iam.User{ | ||
UserName: aws.String("ellen"), | ||
}, | ||
}, | ||
} | ||
} | ||
|
||
ctx := context.Background() | ||
storage := &logical.InmemStorage{} | ||
b, err := Factory(ctx, &logical.BackendConfig{ | ||
StorageView: storage, | ||
Logger: hclog.Default(), | ||
System: &logical.StaticSystemView{ | ||
DefaultLeaseTTLVal: time.Hour, | ||
MaxLeaseTTLVal: time.Hour, | ||
}, | ||
}) | ||
if err != nil { | ||
t.Fatal(err) | ||
} | ||
|
||
clientConf := &clientConfig{ | ||
AccessKey: "fizz1", | ||
SecretKey: "buzz1", | ||
} | ||
entry, err := logical.StorageEntryJSON("config/client", clientConf) | ||
if err != nil { | ||
t.Fatal(err) | ||
} | ||
if err := storage.Put(ctx, entry); err != nil { | ||
t.Fatal(err) | ||
} | ||
|
||
req := &logical.Request{ | ||
Operation: logical.UpdateOperation, | ||
Path: "config/rotate-root", | ||
Storage: storage, | ||
} | ||
resp, err := b.HandleRequest(ctx, req) | ||
if err != nil || (resp != nil && resp.IsError()) { | ||
t.Fatalf("bad: resp: %#v\nerr:%v", resp, err) | ||
} | ||
if resp == nil { | ||
t.Fatal("expected nil response to represent a 204") | ||
} | ||
if resp.Data == nil { | ||
t.Fatal("expected resp.Data") | ||
} | ||
if resp.Data["access_key"].(string) != "fizz2" { | ||
t.Fatalf("expected new access key buzz2 but received %s", resp.Data["access_key"]) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Wow TIL. I never thought about the need for this before.