Skip to content

Commit

Permalink
Merge pull request #439 from geckoboard/feature-tls-mysql
Browse files Browse the repository at this point in the history
Using SSL to encrypt connections to MYSQL
  • Loading branch information
armon committed Aug 5, 2015
2 parents b4e011b + de2218d commit 5058582
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
47 changes: 45 additions & 2 deletions physical/mysql.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
package physical

import (
"crypto/tls"
"crypto/x509"
"database/sql"
"fmt"
"io/ioutil"
"net/url"
"sort"
"strings"
"time"

"github.com/armon/go-metrics"
_ "github.com/go-sql-driver/mysql"
mysql "github.com/go-sql-driver/mysql"
)

// Unreserved tls key
// Reserved values are "true", "false", "skip-verify"
const mysqlTLSKey = "default"

// MySQLBackend is a physical backend that stores data
// within MySQL database.
type MySQLBackend struct {
Expand Down Expand Up @@ -49,8 +57,18 @@ func newMySQLBackend(conf map[string]string) (Backend, error) {
}
dbTable := database + "." + table

dsnParams := url.Values{}
tlsCaFile, ok := conf["tls_ca_file"]
if ok {
if err := setupMySQLTLSConfig(tlsCaFile); err != nil {
return nil, fmt.Errorf("failed register TLS config: %v", err)
}

dsnParams.Add("tls", mysqlTLSKey)
}

// Create MySQL handle for the database.
dsn := username + ":" + password + "@tcp(" + address + ")/"
dsn := username + ":" + password + "@tcp(" + address + ")/?" + dsnParams.Encode()
db, err := sql.Open("mysql", dsn)
if err != nil {
return nil, fmt.Errorf("failed to connect to mysql: %v", err)
Expand Down Expand Up @@ -173,3 +191,28 @@ func (m *MySQLBackend) List(prefix string) ([]string, error) {
sort.Strings(keys)
return keys, nil
}

// Establish a TLS connection with a given CA certificate
// Register a tsl.Config associted with the same key as the dns param from sql.Open
// foo:bar@tcp(127.0.0.1:3306)/dbname?tls=default
func setupMySQLTLSConfig(tlsCaFile string) error {
rootCertPool := x509.NewCertPool()

pem, err := ioutil.ReadFile(tlsCaFile)
if err != nil {
return err
}

if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
return err
}

err = mysql.RegisterTLSConfig(mysqlTLSKey, &tls.Config{
RootCAs: rootCertPool,
})
if err != nil {
return err
}

return nil
}
2 changes: 2 additions & 0 deletions website/source/docs/config/index.html.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,8 @@ The MySQL backend has the following options:

* `table` (optional) - The name of the table to use. Defaults to "vault".

* `tls_ca_file` (optional) - The path to the CA certificate to connect using TLS

#### Backend Reference: Inmem

The in-memory backend has no configuration options.
Expand Down

0 comments on commit 5058582

Please sign in to comment.