2017-08-03 17:24:27 +00:00
|
|
|
package mysql
|
2015-06-08 10:32:44 +00:00
|
|
|
|
|
|
|
import (
|
2018-01-19 06:44:44 +00:00
|
|
|
"context"
|
2015-07-17 15:54:38 +00:00
|
|
|
"crypto/tls"
|
|
|
|
"crypto/x509"
|
2015-06-08 10:32:44 +00:00
|
|
|
"database/sql"
|
2015-06-12 05:56:25 +00:00
|
|
|
"fmt"
|
2015-07-17 15:54:38 +00:00
|
|
|
"io/ioutil"
|
|
|
|
"net/url"
|
2015-06-08 10:32:44 +00:00
|
|
|
"sort"
|
2017-06-01 22:20:32 +00:00
|
|
|
"strconv"
|
2015-06-12 17:31:46 +00:00
|
|
|
"strings"
|
2015-06-08 10:32:44 +00:00
|
|
|
"time"
|
|
|
|
|
2018-04-03 00:46:59 +00:00
|
|
|
log "github.com/hashicorp/go-hclog"
|
2016-08-19 20:45:17 +00:00
|
|
|
|
2015-06-08 10:32:44 +00:00
|
|
|
"github.com/armon/go-metrics"
|
2015-07-17 15:54:38 +00:00
|
|
|
mysql "github.com/go-sql-driver/mysql"
|
2017-06-01 22:20:32 +00:00
|
|
|
"github.com/hashicorp/errwrap"
|
2017-06-16 15:09:15 +00:00
|
|
|
"github.com/hashicorp/vault/helper/strutil"
|
2017-08-03 17:24:27 +00:00
|
|
|
"github.com/hashicorp/vault/physical"
|
2015-07-17 15:54:38 +00:00
|
|
|
)
|
|
|
|
|
2018-01-20 01:44:24 +00:00
|
|
|
// Verify MySQLBackend satisfies the correct interfaces
|
|
|
|
var _ physical.Backend = (*MySQLBackend)(nil)
|
|
|
|
|
2015-07-29 20:03:46 +00:00
|
|
|
// Unreserved tls key
|
|
|
|
// Reserved values are "true", "false", "skip-verify"
|
|
|
|
const mysqlTLSKey = "default"
|
2015-06-08 10:32:44 +00:00
|
|
|
|
|
|
|
// MySQLBackend is a physical backend that stores data
|
|
|
|
// within MySQL database.
|
|
|
|
type MySQLBackend struct {
|
2015-06-18 21:31:00 +00:00
|
|
|
dbTable string
|
2015-06-12 05:56:25 +00:00
|
|
|
client *sql.DB
|
|
|
|
statements map[string]*sql.Stmt
|
2016-08-19 20:45:17 +00:00
|
|
|
logger log.Logger
|
2017-08-03 17:24:27 +00:00
|
|
|
permitPool *physical.PermitPool
|
2015-06-08 10:32:44 +00:00
|
|
|
}
|
|
|
|
|
2017-08-03 17:24:27 +00:00
|
|
|
// NewMySQLBackend constructs a MySQL backend using the given API client and
|
2015-06-08 10:32:44 +00:00
|
|
|
// server address and credential for accessing mysql database.
|
2017-08-03 17:24:27 +00:00
|
|
|
func NewMySQLBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) {
|
2017-06-01 22:20:32 +00:00
|
|
|
var err error
|
|
|
|
|
2015-06-18 21:31:00 +00:00
|
|
|
// Get the MySQL credentials to perform read/write operations.
|
|
|
|
username, ok := conf["username"]
|
|
|
|
if !ok || username == "" {
|
|
|
|
return nil, fmt.Errorf("missing username")
|
|
|
|
}
|
|
|
|
password, ok := conf["password"]
|
2018-07-13 19:35:06 +00:00
|
|
|
if !ok || password == "" {
|
2015-06-18 21:31:00 +00:00
|
|
|
return nil, fmt.Errorf("missing password")
|
|
|
|
}
|
|
|
|
|
2015-06-08 10:32:44 +00:00
|
|
|
// Get or set MySQL server address. Defaults to localhost and default port(3306)
|
|
|
|
address, ok := conf["address"]
|
|
|
|
if !ok {
|
|
|
|
address = "127.0.0.1:3306"
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get the MySQL database and table details.
|
|
|
|
database, ok := conf["database"]
|
|
|
|
if !ok {
|
2015-06-18 21:31:00 +00:00
|
|
|
database = "vault"
|
2015-06-08 10:32:44 +00:00
|
|
|
}
|
|
|
|
table, ok := conf["table"]
|
|
|
|
if !ok {
|
2015-06-18 21:31:00 +00:00
|
|
|
table = "vault"
|
2015-06-08 10:32:44 +00:00
|
|
|
}
|
2018-08-10 23:38:20 +00:00
|
|
|
dbTable := "`" + database + "`" + "." + "`" + table + "`"
|
2015-06-08 10:32:44 +00:00
|
|
|
|
2018-03-28 19:47:40 +00:00
|
|
|
maxIdleConnStr, ok := conf["max_idle_connections"]
|
|
|
|
var maxIdleConnInt int
|
2018-03-28 18:43:55 +00:00
|
|
|
if ok {
|
2018-03-28 19:47:40 +00:00
|
|
|
maxIdleConnInt, err = strconv.Atoi(maxIdleConnStr)
|
2018-03-28 18:43:55 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, errwrap.Wrapf("failed parsing max_idle_connections parameter: {{err}}", err)
|
|
|
|
}
|
|
|
|
if logger.IsDebug() {
|
2018-04-03 00:46:59 +00:00
|
|
|
logger.Debug("max_idle_connections set", "max_idle_connections", maxIdleConnInt)
|
2018-03-28 18:43:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-28 19:47:40 +00:00
|
|
|
maxConnLifeStr, ok := conf["max_connection_lifetime"]
|
|
|
|
var maxConnLifeInt int
|
2018-03-28 18:43:55 +00:00
|
|
|
if ok {
|
|
|
|
maxConnLifeInt, err = strconv.Atoi(maxConnLifeStr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errwrap.Wrapf("failed parsing max_connection_lifetime parameter: {{err}}", err)
|
|
|
|
}
|
|
|
|
if logger.IsDebug() {
|
2018-04-03 00:46:59 +00:00
|
|
|
logger.Debug("max_connection_lifetime set", "max_connection_lifetime", maxConnLifeInt)
|
2018-03-28 18:43:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-06-01 22:20:32 +00:00
|
|
|
maxParStr, ok := conf["max_parallel"]
|
|
|
|
var maxParInt int
|
|
|
|
if ok {
|
|
|
|
maxParInt, err = strconv.Atoi(maxParStr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err)
|
|
|
|
}
|
|
|
|
if logger.IsDebug() {
|
2018-04-03 00:46:59 +00:00
|
|
|
logger.Debug("max_parallel set", "max_parallel", maxParInt)
|
2017-06-01 22:20:32 +00:00
|
|
|
}
|
2017-07-17 17:04:49 +00:00
|
|
|
} else {
|
2017-08-03 17:24:27 +00:00
|
|
|
maxParInt = physical.DefaultParallelOperations
|
2017-06-01 22:20:32 +00:00
|
|
|
}
|
|
|
|
|
2015-07-17 15:54:38 +00:00
|
|
|
dsnParams := url.Values{}
|
2015-07-29 20:03:46 +00:00
|
|
|
tlsCaFile, ok := conf["tls_ca_file"]
|
2015-07-17 15:54:38 +00:00
|
|
|
if ok {
|
2015-07-29 20:03:46 +00:00
|
|
|
if err := setupMySQLTLSConfig(tlsCaFile); err != nil {
|
2018-04-05 15:49:21 +00:00
|
|
|
return nil, errwrap.Wrapf("failed register TLS config: {{err}}", err)
|
2015-07-17 15:54:38 +00:00
|
|
|
}
|
|
|
|
|
2015-07-29 20:03:46 +00:00
|
|
|
dsnParams.Add("tls", mysqlTLSKey)
|
2015-07-17 15:54:38 +00:00
|
|
|
}
|
|
|
|
|
2015-06-08 10:32:44 +00:00
|
|
|
// Create MySQL handle for the database.
|
2015-07-17 15:54:38 +00:00
|
|
|
dsn := username + ":" + password + "@tcp(" + address + ")/?" + dsnParams.Encode()
|
2015-06-08 10:32:44 +00:00
|
|
|
db, err := sql.Open("mysql", dsn)
|
|
|
|
if err != nil {
|
2018-04-05 15:49:21 +00:00
|
|
|
return nil, errwrap.Wrapf("failed to connect to mysql: {{err}}", err)
|
2015-06-08 10:32:44 +00:00
|
|
|
}
|
2017-07-17 17:04:49 +00:00
|
|
|
db.SetMaxOpenConns(maxParInt)
|
2018-03-28 19:47:40 +00:00
|
|
|
if maxIdleConnInt != 0 {
|
2018-03-28 18:43:55 +00:00
|
|
|
db.SetMaxIdleConns(maxIdleConnInt)
|
|
|
|
}
|
2018-03-28 19:47:40 +00:00
|
|
|
if maxConnLifeInt != 0 {
|
|
|
|
db.SetConnMaxLifetime(time.Duration(maxConnLifeInt) * time.Second)
|
2018-03-28 18:43:55 +00:00
|
|
|
}
|
2017-12-19 19:23:58 +00:00
|
|
|
// Check schema exists
|
|
|
|
var schemaExist bool
|
|
|
|
schemaRows, err := db.Query("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = ?", database)
|
|
|
|
if err != nil {
|
2018-04-05 15:49:21 +00:00
|
|
|
return nil, errwrap.Wrapf("failed to check mysql schema exist: {{err}}", err)
|
2017-12-19 19:23:58 +00:00
|
|
|
}
|
|
|
|
defer schemaRows.Close()
|
|
|
|
schemaExist = schemaRows.Next()
|
|
|
|
|
|
|
|
// Check table exists
|
|
|
|
var tableExist bool
|
|
|
|
tableRows, err := db.Query("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", table, database)
|
|
|
|
|
|
|
|
if err != nil {
|
2018-04-05 15:49:21 +00:00
|
|
|
return nil, errwrap.Wrapf("failed to check mysql table exist: {{err}}", err)
|
2017-12-19 19:23:58 +00:00
|
|
|
}
|
|
|
|
defer tableRows.Close()
|
|
|
|
tableExist = tableRows.Next()
|
|
|
|
|
2015-06-18 21:31:00 +00:00
|
|
|
// Create the required database if it doesn't exists.
|
2017-12-19 19:23:58 +00:00
|
|
|
if !schemaExist {
|
2018-08-10 23:38:20 +00:00
|
|
|
if _, err := db.Exec("CREATE DATABASE IF NOT EXISTS `" + database + "`"); err != nil {
|
2018-04-05 15:49:21 +00:00
|
|
|
return nil, errwrap.Wrapf("failed to create mysql database: {{err}}", err)
|
2017-12-19 19:23:58 +00:00
|
|
|
}
|
2015-06-08 10:32:44 +00:00
|
|
|
}
|
|
|
|
|
2015-06-18 21:31:00 +00:00
|
|
|
// Create the required table if it doesn't exists.
|
2017-12-19 19:23:58 +00:00
|
|
|
if !tableExist {
|
|
|
|
create_query := "CREATE TABLE IF NOT EXISTS " + dbTable +
|
|
|
|
" (vault_key varbinary(512), vault_value mediumblob, PRIMARY KEY (vault_key))"
|
|
|
|
if _, err := db.Exec(create_query); err != nil {
|
2018-04-05 15:49:21 +00:00
|
|
|
return nil, errwrap.Wrapf("failed to create mysql table: {{err}}", err)
|
2017-12-19 19:23:58 +00:00
|
|
|
}
|
2015-06-12 05:56:25 +00:00
|
|
|
}
|
|
|
|
|
2015-06-08 10:32:44 +00:00
|
|
|
// Setup the backend.
|
|
|
|
m := &MySQLBackend{
|
2015-06-18 21:31:00 +00:00
|
|
|
dbTable: dbTable,
|
2015-06-12 05:56:25 +00:00
|
|
|
client: db,
|
2015-06-18 21:31:00 +00:00
|
|
|
statements: make(map[string]*sql.Stmt),
|
2016-04-26 03:10:32 +00:00
|
|
|
logger: logger,
|
2017-08-03 17:24:27 +00:00
|
|
|
permitPool: physical.NewPermitPool(maxParInt),
|
2015-06-08 10:32:44 +00:00
|
|
|
}
|
|
|
|
|
2015-06-18 21:31:00 +00:00
|
|
|
// Prepare all the statements required
|
|
|
|
statements := map[string]string{
|
|
|
|
"put": "INSERT INTO " + dbTable +
|
|
|
|
" VALUES( ?, ? ) ON DUPLICATE KEY UPDATE vault_value=VALUES(vault_value)",
|
|
|
|
"get": "SELECT vault_value FROM " + dbTable + " WHERE vault_key = ?",
|
|
|
|
"delete": "DELETE FROM " + dbTable + " WHERE vault_key = ?",
|
|
|
|
"list": "SELECT vault_key FROM " + dbTable + " WHERE vault_key LIKE ?",
|
|
|
|
}
|
|
|
|
for name, query := range statements {
|
|
|
|
if err := m.prepare(name, query); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
2017-06-01 22:20:32 +00:00
|
|
|
|
2015-06-08 10:32:44 +00:00
|
|
|
return m, nil
|
|
|
|
}
|
|
|
|
|
2015-06-18 21:31:00 +00:00
|
|
|
// prepare is a helper to prepare a query for future execution
|
|
|
|
func (m *MySQLBackend) prepare(name, query string) error {
|
|
|
|
stmt, err := m.client.Prepare(query)
|
|
|
|
if err != nil {
|
2018-04-05 15:49:21 +00:00
|
|
|
return errwrap.Wrapf(fmt.Sprintf("failed to prepare %q: {{err}}", name), err)
|
2015-06-18 21:31:00 +00:00
|
|
|
}
|
|
|
|
m.statements[name] = stmt
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-06-08 10:32:44 +00:00
|
|
|
// Put is used to insert or update an entry.
|
2018-01-19 06:44:44 +00:00
|
|
|
func (m *MySQLBackend) Put(ctx context.Context, entry *physical.Entry) error {
|
2015-06-08 10:32:44 +00:00
|
|
|
defer metrics.MeasureSince([]string{"mysql", "put"}, time.Now())
|
|
|
|
|
2017-06-01 22:20:32 +00:00
|
|
|
m.permitPool.Acquire()
|
|
|
|
defer m.permitPool.Release()
|
|
|
|
|
2015-06-12 05:56:25 +00:00
|
|
|
_, err := m.statements["put"].Exec(entry.Key, entry.Value)
|
2015-06-08 10:32:44 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get is used to fetch and entry.
|
2018-01-19 06:44:44 +00:00
|
|
|
func (m *MySQLBackend) Get(ctx context.Context, key string) (*physical.Entry, error) {
|
2015-06-08 10:32:44 +00:00
|
|
|
defer metrics.MeasureSince([]string{"mysql", "get"}, time.Now())
|
|
|
|
|
2017-06-01 22:20:32 +00:00
|
|
|
m.permitPool.Acquire()
|
|
|
|
defer m.permitPool.Release()
|
|
|
|
|
2015-06-08 10:32:44 +00:00
|
|
|
var result []byte
|
2015-06-12 05:56:25 +00:00
|
|
|
err := m.statements["get"].QueryRow(key).Scan(&result)
|
2015-06-18 21:31:00 +00:00
|
|
|
if err == sql.ErrNoRows {
|
2015-06-13 02:19:40 +00:00
|
|
|
return nil, nil
|
2015-06-08 10:32:44 +00:00
|
|
|
}
|
2015-06-18 21:31:00 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2015-06-12 17:31:46 +00:00
|
|
|
}
|
|
|
|
|
2017-08-03 17:24:27 +00:00
|
|
|
ent := &physical.Entry{
|
2015-06-08 10:32:44 +00:00
|
|
|
Key: key,
|
|
|
|
Value: result,
|
|
|
|
}
|
|
|
|
return ent, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Delete is used to permanently delete an entry
|
2018-01-19 06:44:44 +00:00
|
|
|
func (m *MySQLBackend) Delete(ctx context.Context, key string) error {
|
2015-06-08 10:32:44 +00:00
|
|
|
defer metrics.MeasureSince([]string{"mysql", "delete"}, time.Now())
|
|
|
|
|
2017-06-01 22:20:32 +00:00
|
|
|
m.permitPool.Acquire()
|
|
|
|
defer m.permitPool.Release()
|
|
|
|
|
2015-06-12 05:56:25 +00:00
|
|
|
_, err := m.statements["delete"].Exec(key)
|
2015-06-08 10:32:44 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// List is used to list all the keys under a given
|
|
|
|
// prefix, up to the next prefix.
|
2018-01-19 06:44:44 +00:00
|
|
|
func (m *MySQLBackend) List(ctx context.Context, prefix string) ([]string, error) {
|
2015-06-08 10:32:44 +00:00
|
|
|
defer metrics.MeasureSince([]string{"mysql", "list"}, time.Now())
|
|
|
|
|
2017-06-01 22:20:32 +00:00
|
|
|
m.permitPool.Acquire()
|
|
|
|
defer m.permitPool.Release()
|
|
|
|
|
2015-06-18 21:31:00 +00:00
|
|
|
// Add the % wildcard to the prefix to do the prefix search
|
|
|
|
likePrefix := prefix + "%"
|
|
|
|
rows, err := m.statements["list"].Query(likePrefix)
|
2016-11-17 14:59:27 +00:00
|
|
|
if err != nil {
|
2018-04-05 15:49:21 +00:00
|
|
|
return nil, errwrap.Wrapf("failed to execute statement: {{err}}", err)
|
2016-11-17 14:59:27 +00:00
|
|
|
}
|
2015-06-08 10:32:44 +00:00
|
|
|
|
2015-06-18 21:31:00 +00:00
|
|
|
var keys []string
|
2015-06-08 10:32:44 +00:00
|
|
|
for rows.Next() {
|
2015-06-18 21:31:00 +00:00
|
|
|
var key string
|
|
|
|
err = rows.Scan(&key)
|
2015-06-08 10:32:44 +00:00
|
|
|
if err != nil {
|
2018-04-05 15:49:21 +00:00
|
|
|
return nil, errwrap.Wrapf("failed to scan rows: {{err}}", err)
|
2015-06-08 10:32:44 +00:00
|
|
|
}
|
|
|
|
|
2015-06-18 21:31:00 +00:00
|
|
|
key = strings.TrimPrefix(key, prefix)
|
|
|
|
if i := strings.Index(key, "/"); i == -1 {
|
|
|
|
// Add objects only from the current 'folder'
|
|
|
|
keys = append(keys, key)
|
|
|
|
} else if i != -1 {
|
|
|
|
// Add truncated 'folder' paths
|
2017-06-16 15:09:15 +00:00
|
|
|
keys = strutil.AppendIfMissing(keys, string(key[:i+1]))
|
2015-06-08 10:32:44 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
sort.Strings(keys)
|
|
|
|
return keys, nil
|
|
|
|
}
|
2015-07-17 15:54:38 +00:00
|
|
|
|
2015-07-29 20:03:46 +00:00
|
|
|
// Establish a TLS connection with a given CA certificate
|
2018-03-20 18:54:10 +00:00
|
|
|
// Register a tsl.Config associated with the same key as the dns param from sql.Open
|
2015-07-29 20:03:46 +00:00
|
|
|
// foo:bar@tcp(127.0.0.1:3306)/dbname?tls=default
|
|
|
|
func setupMySQLTLSConfig(tlsCaFile string) error {
|
2015-07-17 15:54:38 +00:00
|
|
|
rootCertPool := x509.NewCertPool()
|
|
|
|
|
2015-07-29 20:03:46 +00:00
|
|
|
pem, err := ioutil.ReadFile(tlsCaFile)
|
2015-07-17 15:54:38 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2015-07-29 20:03:46 +00:00
|
|
|
err = mysql.RegisterTLSConfig(mysqlTLSKey, &tls.Config{
|
2015-07-17 15:54:38 +00:00
|
|
|
RootCAs: rootCertPool,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|