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

Add automated root rotation support to DB Secrets #29557

Merged
merged 4 commits into from
Feb 11, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions builtin/credential/aws/path_config_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package awsauth
import (
"context"
"errors"
"fmt"
"net/http"
"net/textproto"
"net/url"
Expand Down Expand Up @@ -434,11 +435,12 @@ func (b *backend) pathConfigClientCreateUpdate(ctx context.Context, req *logical

if changedCreds || changedOtherConfig || req.Operation == logical.CreateOperation {
if err := req.Storage.Put(ctx, entry); err != nil {
wrappedError := err
if performedRotationManagerOpern != "" {
b.Logger().Error("write to storage failed but the rotation manager still succeeded.",
"operation", performedRotationManagerOpern, "mount", req.MountPoint, "path", req.Path)
wrappedError = fmt.Errorf("write to storage failed but the rotation manager still succeeded; "+
"operation=%s, mount=%s, path=%s, storageError=%s", performedRotationManagerOpern, req.MountPoint, req.Path, err)
}
return nil, err
return nil, wrappedError
}
}

Expand Down
8 changes: 5 additions & 3 deletions builtin/logical/aws/path_config_root.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package aws
import (
"context"
"errors"
"fmt"

"github.com/aws/aws-sdk-go/aws"
"github.com/hashicorp/vault/sdk/framework"
Expand Down Expand Up @@ -282,11 +283,12 @@ func (b *backend) pathConfigRootWrite(ctx context.Context, req *logical.Request,

// Save the config
if err := putConfigToStorage(ctx, req, rc); err != nil {
wrappedError := err
if performedRotationManagerOpern != "" {
b.Logger().Error("write to storage failed but the rotation manager still succeeded.",
"operation", performedRotationManagerOpern, "mount", req.MountPoint, "path", req.Path)
wrappedError = fmt.Errorf("write to storage failed but the rotation manager still succeeded; "+
"operation=%s, mount=%s, path=%s, storageError=%s", performedRotationManagerOpern, req.MountPoint, req.Path, err)
}
return nil, err
return nil, wrappedError
}

// clear possible cached IAM / STS clients after successfully updating
Expand Down
119 changes: 119 additions & 0 deletions builtin/logical/database/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"net/rpc"
"regexp"
"strconv"
"strings"
"sync"
Expand All @@ -20,6 +21,7 @@ import (
"github.com/hashicorp/vault/builtin/logical/database/schedule"
"github.com/hashicorp/vault/helper/metricsutil"
"github.com/hashicorp/vault/helper/syncmap"
"github.com/hashicorp/vault/helper/versions"
"github.com/hashicorp/vault/internalshared/configutil"
v4 "github.com/hashicorp/vault/sdk/database/dbplugin"
v5 "github.com/hashicorp/vault/sdk/database/dbplugin/v5"
Expand All @@ -39,6 +41,8 @@ const (
minRootCredRollbackAge = 1 * time.Minute
)

var databaseConfigNameFromRotationIDRegex = regexp.MustCompile("^.+/config/(.+$)")

type dbPluginInstance struct {
sync.RWMutex
database databaseVersionWrapper
Expand Down Expand Up @@ -127,6 +131,110 @@ func Backend(conf *logical.BackendConfig) *databaseBackend {
WALRollback: b.walRollback,
WALRollbackMinAge: minRootCredRollbackAge,
BackendType: logical.TypeLogical,
RotateCredential: func(ctx context.Context, request *logical.Request) error {
name, err := b.getDatabaseConfigNameFromRotationID(request.RotationID)
if err != nil {
return err
}

if name == "" {
return errors.New("empty rotation name")
}

config, err := b.DatabaseConfig(ctx, request.Storage, name)
if err != nil {
return err
}

rootUsername, ok := config.ConnectionDetails["username"].(string)
if !ok || rootUsername == "" {
return fmt.Errorf("unable to rotate root credentials: no username in configuration")
}

rootPassword, ok := config.ConnectionDetails["password"].(string)
if !ok || rootPassword == "" {
return fmt.Errorf("unable to rotate root credentials: no password in configuration")
}

dbi, err := b.GetConnection(ctx, request.Storage, name)
if err != nil {
return err
}

// Take the write lock on the instance
dbi.Lock()
defer func() {
dbi.Unlock()
// Even on error, still remove the connection
b.ClearConnectionId(name, dbi.id)
}()
defer func() {
// Close the plugin
dbi.closed = true
if err := dbi.database.Close(); err != nil {
b.Logger().Error("error closing the database plugin connection", "err", err)
}
}()

generator, err := newPasswordGenerator(nil)
if err != nil {
return fmt.Errorf("failed to construct credential generator: %s", err)
}
generator.PasswordPolicy = config.PasswordPolicy

// Generate new credentials
oldPassword := config.ConnectionDetails["password"].(string)
newPassword, err := generator.generate(ctx, &b, dbi.database)
if err != nil {
b.CloseIfShutdown(dbi, err)
return fmt.Errorf("failed to generate password: %s", err)
}
config.ConnectionDetails["password"] = newPassword

// Write a WAL entry
walID, err := framework.PutWAL(ctx, request.Storage, rotateRootWALKey, &rotateRootCredentialsWAL{
ConnectionName: name,
UserName: rootUsername,
OldPassword: oldPassword,
NewPassword: newPassword,
})
if err != nil {
return err
}

updateReq := v5.UpdateUserRequest{
Username: rootUsername,
CredentialType: v5.CredentialTypePassword,
Password: &v5.ChangePassword{
NewPassword: newPassword,
Statements: v5.Statements{
Commands: config.RootCredentialsRotateStatements,
},
},
}
newConfigDetails, err := dbi.database.UpdateUser(ctx, updateReq, true)
if err != nil {
return fmt.Errorf("failed to update user: %w", err)
}
if newConfigDetails != nil {
config.ConnectionDetails = newConfigDetails
}

if versions.IsBuiltinVersion(config.PluginVersion) {
config.PluginVersion = ""
}
err = storeConfig(ctx, request.Storage, name, config)
if err != nil {
return err
}

err = framework.DeleteWAL(ctx, request.Storage, walID)
if err != nil {
b.Logger().Warn("unable to delete WAL", "error", err, "WAL ID", walID)
}

return nil
},
}

b.logger = conf.Logger
Expand Down Expand Up @@ -483,6 +591,17 @@ func (b *databaseBackend) dbEvent(ctx context.Context,
}
}

func (b *databaseBackend) getDatabaseConfigNameFromRotationID(path string) (string, error) {
if !databaseConfigNameFromRotationIDRegex.MatchString(path) {
return "", fmt.Errorf("no name found from rotation ID")
}
res := databaseConfigNameFromRotationIDRegex.FindStringSubmatch(path)
if len(res) != 2 {
return "", fmt.Errorf("unexpected number of matches (%d) for name in rotation ID", len(res))
}
return res[1], nil
}

const backendHelp = `
The database backend supports using many different databases
as secret backends, including but not limited to:
Expand Down
20 changes: 20 additions & 0 deletions builtin/logical/database/backend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,10 @@ func TestBackend_config_connection(t *testing.T) {
"plugin_version": "",
"verify_connection": false,
"skip_static_role_import_rotation": false,
"rotation_schedule": "",
"rotation_period": 0,
"rotation_window": 0,
"disable_automated_rotation": false,
}
configReq.Operation = logical.ReadOperation
resp, err = b.HandleRequest(namespace.RootContext(nil), configReq)
Expand All @@ -221,6 +225,7 @@ func TestBackend_config_connection(t *testing.T) {
}

delete(resp.Data["connection_details"].(map[string]interface{}), "name")
delete(resp.Data, "AutomatedRotationParams")
if !reflect.DeepEqual(expected, resp.Data) {
t.Fatalf("bad: expected:%#v\nactual:%#v\n", expected, resp.Data)
}
Expand Down Expand Up @@ -269,6 +274,10 @@ func TestBackend_config_connection(t *testing.T) {
"plugin_version": "",
"verify_connection": false,
"skip_static_role_import_rotation": false,
"rotation_schedule": "",
"rotation_period": 0,
"rotation_window": 0,
"disable_automated_rotation": false,
}
configReq.Operation = logical.ReadOperation
resp, err = b.HandleRequest(namespace.RootContext(nil), configReq)
Expand All @@ -277,6 +286,7 @@ func TestBackend_config_connection(t *testing.T) {
}

delete(resp.Data["connection_details"].(map[string]interface{}), "name")
delete(resp.Data, "AutomatedRotationParams")
if !reflect.DeepEqual(expected, resp.Data) {
t.Fatalf("bad: expected:%#v\nactual:%#v\n", expected, resp.Data)
}
Expand Down Expand Up @@ -314,6 +324,10 @@ func TestBackend_config_connection(t *testing.T) {
"plugin_version": "",
"verify_connection": false,
"skip_static_role_import_rotation": false,
"rotation_schedule": "",
"rotation_period": 0,
"rotation_window": 0,
"disable_automated_rotation": false,
}
configReq.Operation = logical.ReadOperation
resp, err = b.HandleRequest(namespace.RootContext(nil), configReq)
Expand All @@ -322,6 +336,7 @@ func TestBackend_config_connection(t *testing.T) {
}

delete(resp.Data["connection_details"].(map[string]interface{}), "name")
delete(resp.Data, "AutomatedRotationParams")
if !reflect.DeepEqual(expected, resp.Data) {
t.Fatalf("bad: expected:%#v\nactual:%#v\n", expected, resp.Data)
}
Expand Down Expand Up @@ -773,13 +788,18 @@ func TestBackend_connectionCrud(t *testing.T) {
"plugin_version": "",
"verify_connection": false,
"skip_static_role_import_rotation": false,
"rotation_schedule": "",
"rotation_period": json.Number("0"),
"rotation_window": json.Number("0"),
"disable_automated_rotation": false,
}
resp, err = client.Read("database/config/plugin-test")
if err != nil {
t.Fatalf("err:%s resp:%#v\n", err, resp)
}

delete(resp.Data["connection_details"].(map[string]interface{}), "name")
delete(resp.Data, "AutomatedRotationParams")
if diff := deep.Equal(resp.Data, expected); diff != nil {
t.Fatal(strings.Join(diff, "\n"))
}
Expand Down
51 changes: 50 additions & 1 deletion builtin/logical/database/path_config_connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@ import (
"github.com/hashicorp/vault/helper/versions"
v5 "github.com/hashicorp/vault/sdk/database/dbplugin/v5"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/automatedrotationutil"
"github.com/hashicorp/vault/sdk/helper/consts"
"github.com/hashicorp/vault/sdk/helper/pluginutil"
"github.com/hashicorp/vault/sdk/logical"
"github.com/hashicorp/vault/sdk/rotation"
)

var (
Expand Down Expand Up @@ -49,6 +51,8 @@ type DatabaseConfig struct {
// role-level by the role's skip_import_rotation field. The default is
// false. Enterprise only.
SkipStaticRoleImportRotation bool `json:"skip_static_role_import_rotation" structs:"skip_static_role_import_rotation" mapstructure:"skip_static_role_import_rotation"`

automatedrotationutil.AutomatedRotationParams
}

// ConnectionDetails represents the DatabaseConfig.ConnectionDetails map as a
Expand Down Expand Up @@ -263,6 +267,7 @@ func pathConfigurePluginConnection(b *databaseBackend) *framework.Path {
},
}
AddConnectionFieldsEnt(fields)
automatedrotationutil.AddAutomatedRotationFields(fields)

return &framework.Path{
Pattern: fmt.Sprintf("config/%s", framework.GenericNameRegex("name")),
Expand Down Expand Up @@ -409,6 +414,7 @@ func (b *databaseBackend) connectionReadHandler() framework.OperationFunc {
}

resp.Data = structs.New(config).Map()
config.PopulateAutomatedRotationData(resp.Data)
return resp, nil
}
}
Expand Down Expand Up @@ -500,6 +506,10 @@ func (b *databaseBackend) connectionWriteHandler() framework.OperationFunc {
config.SkipStaticRoleImportRotation = skipImportRotationRaw.(bool)
}

if err := config.ParseAutomatedRotationFields(data); err != nil {
return logical.ErrorResponse(err.Error()), nil
}

// Remove these entries from the data before we store it keyed under
// ConnectionDetails.
delete(data.Raw, "name")
Expand All @@ -510,6 +520,10 @@ func (b *databaseBackend) connectionWriteHandler() framework.OperationFunc {
delete(data.Raw, "root_rotation_statements")
delete(data.Raw, "password_policy")
delete(data.Raw, "skip_static_role_import_rotation")
delete(data.Raw, "rotation_schedule")
delete(data.Raw, "rotation_window")
delete(data.Raw, "rotation_ttl")
delete(data.Raw, "disable_automated_rotation")

id, err := uuid.GenerateUUID()
if err != nil {
Expand Down Expand Up @@ -560,14 +574,49 @@ func (b *databaseBackend) connectionWriteHandler() framework.OperationFunc {
oldConn.Close()
}

var performedRotationManagerOpern string
if config.ShouldDeregisterRotationJob() {
performedRotationManagerOpern = "deregistration"
// Disable Automated Rotation and Deregister credentials if required
deregisterReq := &rotation.RotationJobDeregisterRequest{
MountPoint: req.MountPoint,
ReqPath: req.Path,
}

b.Logger().Debug("Deregistering rotation job", "mount", req.MountPoint+req.Path)
if err := b.System().DeregisterRotationJob(ctx, deregisterReq); err != nil {
return logical.ErrorResponse("error deregistering rotation job: %s", err), nil
}
} else if config.ShouldRegisterRotationJob() {
performedRotationManagerOpern = "registration"
// Register the rotation job if it's required.
cfgReq := &rotation.RotationJobConfigureRequest{
MountPoint: req.MountPoint,
ReqPath: req.Path,
RotationSchedule: config.RotationSchedule,
RotationWindow: config.RotationWindow,
RotationPeriod: config.RotationPeriod,
}

b.Logger().Debug("Registering rotation job", "mount", req.MountPoint+req.Path)
if _, err = b.System().RegisterRotationJob(ctx, cfgReq); err != nil {
return logical.ErrorResponse("error registering rotation job: %s", err), nil
}
}

// 1.12.0 and 1.12.1 stored builtin plugins in storage, but 1.12.2 reverted
// that, so clean up any pre-existing stored builtin versions on write.
if versions.IsBuiltinVersion(config.PluginVersion) {
config.PluginVersion = ""
}
err = storeConfig(ctx, req.Storage, name, config)
if err != nil {
return nil, err
wrappedError := err
if performedRotationManagerOpern != "" {
wrappedError = fmt.Errorf("write to storage failed but the rotation manager still succeeded; "+
"operation=%s, mount=%s, path=%s, storageError=%s", performedRotationManagerOpern, req.MountPoint, req.Path, err)
}
return nil, wrappedError
}

resp := &logical.Response{}
Expand Down
Loading
Loading