b55303eddb
* Add priority queue to sdk * fix issue of storing pointers and now copy * update to use copy structure * Remove file, put Item struct def. into other file * add link * clean up docs * refactor internal data structure to hide heap method implementations. Other cleanup after feedback * rename PushItem and PopItem to just Push/Pop, after encapsulating the heap methods * updates after feedback * refactoring/renaming * guard against pushing a nil item * minor updates after feedback * Add SetCredentials, GenerateCredentials gRPC methods to combined database backend gPRC * Initial Combined database backend implementation of static accounts and automatic rotation * vendor updates * initial implementation of static accounts with Combined database backend, starting with PostgreSQL implementation * add lock and setup of rotation queue * vendor the queue * rebase on new method signature of queue * remove mongo tests for now * update default role sql * gofmt after rebase * cleanup after rebasing to remove checks for ErrNotFound error * rebase cdcr-priority-queue * vendor dependencies with 'go mod vendor' * website database docs for Static Role support * document the rotate-role API endpoint * postgres specific static role docs * use constants for paths * updates from review * remove dead code * combine and clarify error message for older plugins * Update builtin/logical/database/backend.go Co-Authored-By: Jim Kalafut <jim@kalafut.net> * cleanups from feedback * code and comment cleanups * move db.RLock higher to protect db.GenerateCredentials call * Return output with WALID if we failed to delete the WAL * Update builtin/logical/database/path_creds_create.go Co-Authored-By: Jim Kalafut <jim@kalafut.net> * updates after running 'make fmt' * update after running 'make proto' * Update builtin/logical/database/path_roles.go Co-Authored-By: Brian Kassouf <briankassouf@users.noreply.github.com> * Update builtin/logical/database/path_roles.go Co-Authored-By: Brian Kassouf <briankassouf@users.noreply.github.com> * update comment and remove and rearrange some dead code * Update website/source/api/secret/databases/index.html.md Co-Authored-By: Jim Kalafut <jim@kalafut.net> * cleanups after review * Update sdk/database/dbplugin/grpc_transport.go Co-Authored-By: Brian Kassouf <briankassouf@users.noreply.github.com> * code cleanup after feedback * remove PasswordLastSet; it's not used * document GenerateCredentials and SetCredentials * Update builtin/logical/database/path_rotate_credentials.go Co-Authored-By: Brian Kassouf <briankassouf@users.noreply.github.com> * wrap pop and popbykey in backend methods to protect against nil cred rotation queue * use strings.HasPrefix instead of direct equality check for path * Forgot to commit this * updates after feedback * re-purpose an outdated test to now check that static and dynamic roles cannot share a name * check for unique name across dynamic and static roles * refactor loadStaticWALs to return a map of name/setCredentialsWAL struct to consolidate where we're calling set credentials * remove commented out code * refactor to have loadstaticwals filter out wals for roles that no longer exist * return error if nil input given * add nil check for input into setStaticAccount * Update builtin/logical/database/path_roles.go Co-Authored-By: Brian Kassouf <briankassouf@users.noreply.github.com> * add constant for queue tick time in seconds, used for comparrison in updates * Update builtin/logical/database/path_roles.go Co-Authored-By: Jim Kalafut <jim@kalafut.net> * code cleanup after review * remove misplaced code comment * remove commented out code * create a queue in the Factory method, even if it's never used * update path_roles to use a common set of fields, with specific overrides for dynamic/static roles by type * document new method * move rotation things into a specific file * rename test file and consolidate some static account tests * Update builtin/logical/database/path_roles.go Co-Authored-By: Brian Kassouf <briankassouf@users.noreply.github.com> * Update builtin/logical/database/rotation.go Co-Authored-By: Brian Kassouf <briankassouf@users.noreply.github.com> * Update builtin/logical/database/rotation.go Co-Authored-By: Brian Kassouf <briankassouf@users.noreply.github.com> * Update builtin/logical/database/rotation.go Co-Authored-By: Brian Kassouf <briankassouf@users.noreply.github.com> * Update builtin/logical/database/rotation.go Co-Authored-By: Brian Kassouf <briankassouf@users.noreply.github.com> * Update builtin/logical/database/rotation.go Co-Authored-By: Brian Kassouf <briankassouf@users.noreply.github.com> * update code comments, method names, and move more methods into rotation.go * update comments to be capitalized * remove the item from the queue before we try to destroy it * findStaticWAL returns an error * use lowercase keys when encoding WAL entries * small cleanups * remove vestigial static account check * remove redundant DeleteWAL call in populate queue * if we error on loading role, push back to queue with 10 second backoff * poll in initqueue to make sure the backend is setup and can write/delete data * add revoke_user_on_delete flag to allow users to opt-in to revoking the static database user on delete of the Vault role. Default false * add code comments on read-only loop * code comment updates * re-push if error returned from find static wal * add locksutil and acquire locks when pop'ing from the queue * grab exclusive locks for updating static roles * Add SetCredentials and GenerateCredentials stubs to mockPlugin * add a switch in initQueue to listen for cancelation * remove guard on zero time, it should have no affect * create a new context in Factory to pass on and use for closing the backend queue * restore master copy of vendor dir
305 lines
7.4 KiB
Go
305 lines
7.4 KiB
Go
package hana
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
_ "github.com/SAP/go-hdb/driver"
|
|
"github.com/hashicorp/vault/api"
|
|
"github.com/hashicorp/vault/sdk/database/dbplugin"
|
|
"github.com/hashicorp/vault/sdk/database/helper/connutil"
|
|
"github.com/hashicorp/vault/sdk/database/helper/credsutil"
|
|
"github.com/hashicorp/vault/sdk/database/helper/dbutil"
|
|
"github.com/hashicorp/vault/sdk/helper/dbtxn"
|
|
"github.com/hashicorp/vault/sdk/helper/strutil"
|
|
)
|
|
|
|
const (
|
|
hanaTypeName = "hdb"
|
|
)
|
|
|
|
// HANA is an implementation of Database interface
|
|
type HANA struct {
|
|
*connutil.SQLConnectionProducer
|
|
credsutil.CredentialsProducer
|
|
}
|
|
|
|
var _ dbplugin.Database = &HANA{}
|
|
|
|
// New implements builtinplugins.BuiltinFactory
|
|
func New() (interface{}, error) {
|
|
db := new()
|
|
// Wrap the plugin with middleware to sanitize errors
|
|
dbType := dbplugin.NewDatabaseErrorSanitizerMiddleware(db, db.SecretValues)
|
|
|
|
return dbType, nil
|
|
}
|
|
|
|
func new() *HANA {
|
|
connProducer := &connutil.SQLConnectionProducer{}
|
|
connProducer.Type = hanaTypeName
|
|
|
|
credsProducer := &credsutil.SQLCredentialsProducer{
|
|
DisplayNameLen: 32,
|
|
RoleNameLen: 20,
|
|
UsernameLen: 128,
|
|
Separator: "_",
|
|
}
|
|
|
|
return &HANA{
|
|
SQLConnectionProducer: connProducer,
|
|
CredentialsProducer: credsProducer,
|
|
}
|
|
}
|
|
|
|
// Run instantiates a HANA object, and runs the RPC server for the plugin
|
|
func Run(apiTLSConfig *api.TLSConfig) error {
|
|
dbType, err := New()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
dbplugin.Serve(dbType.(dbplugin.Database), api.VaultPluginTLSProvider(apiTLSConfig))
|
|
|
|
return nil
|
|
}
|
|
|
|
// Type returns the TypeName for this backend
|
|
func (h *HANA) Type() (string, error) {
|
|
return hanaTypeName, nil
|
|
}
|
|
|
|
func (h *HANA) getConnection(ctx context.Context) (*sql.DB, error) {
|
|
db, err := h.Connection(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return db.(*sql.DB), nil
|
|
}
|
|
|
|
// CreateUser generates the username/password on the underlying HANA secret backend
|
|
// as instructed by the CreationStatement provided.
|
|
func (h *HANA) CreateUser(ctx context.Context, statements dbplugin.Statements, usernameConfig dbplugin.UsernameConfig, expiration time.Time) (username string, password string, err error) {
|
|
// Grab the lock
|
|
h.Lock()
|
|
defer h.Unlock()
|
|
|
|
statements = dbutil.StatementCompatibilityHelper(statements)
|
|
|
|
// Get the connection
|
|
db, err := h.getConnection(ctx)
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
|
|
if len(statements.Creation) == 0 {
|
|
return "", "", dbutil.ErrEmptyCreationStatement
|
|
}
|
|
|
|
// Generate username
|
|
username, err = h.GenerateUsername(usernameConfig)
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
|
|
// HANA does not allow hyphens in usernames, and highly prefers capital letters
|
|
username = strings.Replace(username, "-", "_", -1)
|
|
username = strings.ToUpper(username)
|
|
|
|
// Generate password
|
|
password, err = h.GeneratePassword()
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
// Most HANA configurations have password constraints
|
|
// Prefix with A1a to satisfy these constraints. User will be forced to change upon login
|
|
password = strings.Replace(password, "-", "_", -1)
|
|
password = "A1a" + password
|
|
|
|
// If expiration is in the role SQL, HANA will deactivate the user when time is up,
|
|
// regardless of whether vault is alive to revoke lease
|
|
expirationStr, err := h.GenerateExpiration(expiration)
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
|
|
// Start a transaction
|
|
tx, err := db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
defer tx.Rollback()
|
|
|
|
// Execute each query
|
|
for _, stmt := range statements.Creation {
|
|
for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") {
|
|
query = strings.TrimSpace(query)
|
|
if len(query) == 0 {
|
|
continue
|
|
}
|
|
|
|
m := map[string]string{
|
|
"name": username,
|
|
"password": password,
|
|
"expiration": expirationStr,
|
|
}
|
|
if err := dbtxn.ExecuteTxQuery(ctx, tx, m, query); err != nil {
|
|
return "", "", err
|
|
}
|
|
}
|
|
}
|
|
|
|
// Commit the transaction
|
|
if err := tx.Commit(); err != nil {
|
|
return "", "", err
|
|
}
|
|
|
|
return username, password, nil
|
|
}
|
|
|
|
// Renewing hana user just means altering user's valid until property
|
|
func (h *HANA) RenewUser(ctx context.Context, statements dbplugin.Statements, username string, expiration time.Time) error {
|
|
statements = dbutil.StatementCompatibilityHelper(statements)
|
|
|
|
// Get connection
|
|
db, err := h.getConnection(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Start a transaction
|
|
tx, err := db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
|
|
// If expiration is in the role SQL, HANA will deactivate the user when time is up,
|
|
// regardless of whether vault is alive to revoke lease
|
|
expirationStr, err := h.GenerateExpiration(expiration)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Renew user's valid until property field
|
|
stmt, err := tx.PrepareContext(ctx, "ALTER USER "+username+" VALID UNTIL "+"'"+expirationStr+"'")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer stmt.Close()
|
|
if _, err := stmt.ExecContext(ctx); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Commit the transaction
|
|
if err := tx.Commit(); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// Revoking hana user will deactivate user and try to perform a soft drop
|
|
func (h *HANA) RevokeUser(ctx context.Context, statements dbplugin.Statements, username string) error {
|
|
statements = dbutil.StatementCompatibilityHelper(statements)
|
|
|
|
// default revoke will be a soft drop on user
|
|
if len(statements.Revocation) == 0 {
|
|
return h.revokeUserDefault(ctx, username)
|
|
}
|
|
|
|
// Get connection
|
|
db, err := h.getConnection(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Start a transaction
|
|
tx, err := db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
|
|
// Execute each query
|
|
for _, stmt := range statements.Revocation {
|
|
for _, query := range strutil.ParseArbitraryStringSlice(stmt, ";") {
|
|
query = strings.TrimSpace(query)
|
|
if len(query) == 0 {
|
|
continue
|
|
}
|
|
|
|
m := map[string]string{
|
|
"name": username,
|
|
}
|
|
if err := dbtxn.ExecuteTxQuery(ctx, tx, m, query); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
|
|
return tx.Commit()
|
|
}
|
|
|
|
func (h *HANA) revokeUserDefault(ctx context.Context, username string) error {
|
|
// Get connection
|
|
db, err := h.getConnection(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Start a transaction
|
|
tx, err := db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
|
|
// Disable server login for user
|
|
disableStmt, err := tx.PrepareContext(ctx, fmt.Sprintf("ALTER USER %s DEACTIVATE USER NOW", username))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer disableStmt.Close()
|
|
if _, err := disableStmt.ExecContext(ctx); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Invalidates current sessions and performs soft drop (drop if no dependencies)
|
|
// if hard drop is desired, custom revoke statements should be written for role
|
|
dropStmt, err := tx.PrepareContext(ctx, fmt.Sprintf("DROP USER %s RESTRICT", username))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer dropStmt.Close()
|
|
if _, err := dropStmt.ExecContext(ctx); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Commit transaction
|
|
if err := tx.Commit(); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// RotateRootCredentials is not currently supported on HANA
|
|
func (h *HANA) RotateRootCredentials(ctx context.Context, statements []string) (map[string]interface{}, error) {
|
|
return nil, errors.New("root credentaion rotation is not currently implemented in this database secrets engine")
|
|
}
|
|
|
|
// GenerateCredentials returns a generated password
|
|
func (h *HANA) GenerateCredentials(ctx context.Context) (string, error) {
|
|
password, err := h.GeneratePassword()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return password, nil
|
|
}
|