open-vault/vault/cluster.go

470 lines
13 KiB
Go
Raw Normal View History

package vault
import (
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/json"
"errors"
"fmt"
"math/big"
mathrand "math/rand"
"net"
"net/http"
"time"
2017-01-06 20:42:18 +00:00
"github.com/hashicorp/errwrap"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/vault/helper/jsonutil"
)
const (
// Storage path where the local cluster name and identifier are stored
2016-08-09 15:28:42 +00:00
coreLocalClusterInfoPath = "core/cluster/local/info"
2017-01-04 21:44:03 +00:00
corePrivateKeyTypeP521 = "p521"
corePrivateKeyTypeED25519 = "ed25519"
// Internal so as not to log a trace message
IntNoForwardingHeaderName = "X-Vault-Internal-No-Request-Forwarding"
)
var (
ErrCannotForward = errors.New("cannot forward request; no connection or address not known")
)
2017-01-04 21:44:03 +00:00
// This can be one of a few key types so the different params may or may not be filled
type clusterKeyParams struct {
Type string `json:"type" structs:"type" mapstructure:"type"`
2017-01-06 20:42:18 +00:00
X *big.Int `json:"x" structs:"x" mapstructure:"x"`
Y *big.Int `json:"y" structs:"y" mapstructure:"y"`
D *big.Int `json:"d" structs:"d" mapstructure:"d"`
}
// Structure representing the storage entry that holds cluster information
type Cluster struct {
// Name of the cluster
Name string `json:"name" structs:"name" mapstructure:"name"`
// Identifier of the cluster
ID string `json:"id" structs:"id" mapstructure:"id"`
}
2017-01-06 20:42:18 +00:00
// Cluster fetches the details of the local cluster. This method errors out
// when Vault is sealed.
2016-07-26 13:18:38 +00:00
func (c *Core) Cluster() (*Cluster, error) {
var cluster Cluster
// Fetch the storage entry. This call fails when Vault is sealed.
2016-08-09 15:28:42 +00:00
entry, err := c.barrier.Get(coreLocalClusterInfoPath)
if err != nil {
2016-08-10 19:22:12 +00:00
return nil, err
}
if entry == nil {
return &cluster, nil
}
// Decode the cluster information
if err = jsonutil.DecodeJSON(entry.Value, &cluster); err != nil {
2016-08-10 19:22:12 +00:00
return nil, fmt.Errorf("failed to decode cluster details: %v", err)
}
// Set in config file
if c.clusterName != "" {
cluster.Name = c.clusterName
}
return &cluster, nil
}
2016-08-19 15:03:53 +00:00
// This sets our local cluster cert and private key based on the advertisement.
// It also ensures the cert is in our local cluster cert pool.
func (c *Core) loadLocalClusterTLS(adv activeAdvertisement) (retErr error) {
defer func() {
if retErr != nil {
c.clusterParamsLock.Lock()
c.localClusterCert = nil
c.localClusterPrivateKey = nil
c.localClusterParsedCert = nil
2017-03-02 15:54:31 +00:00
c.clusterParamsLock.Unlock()
c.requestForwardingConnectionLock.Lock()
c.clearForwardingClients()
c.requestForwardingConnectionLock.Unlock()
}
}()
switch {
case adv.ClusterAddr == "":
// Clustering disabled on the server, don't try to look for params
return nil
case adv.ClusterKeyParams == nil:
2017-03-01 23:16:47 +00:00
c.logger.Error("core: no key params found loading local cluster TLS information")
return fmt.Errorf("no local cluster key params found")
case adv.ClusterKeyParams.X == nil, adv.ClusterKeyParams.Y == nil, adv.ClusterKeyParams.D == nil:
2017-03-01 23:16:47 +00:00
c.logger.Error("core: failed to parse local cluster key due to missing params")
return fmt.Errorf("failed to parse local cluster key")
2016-08-19 15:03:53 +00:00
case adv.ClusterKeyParams.Type != corePrivateKeyTypeP521:
2017-03-01 23:16:47 +00:00
c.logger.Error("core: unknown local cluster key type", "key_type", adv.ClusterKeyParams.Type)
return fmt.Errorf("failed to find valid local cluster key type")
case adv.ClusterCert == nil || len(adv.ClusterCert) == 0:
2017-03-01 23:16:47 +00:00
c.logger.Error("core: no local cluster cert found")
return fmt.Errorf("no local cluster cert found")
}
2016-08-19 15:03:53 +00:00
// Prevent data races with the TLS parameters
c.clusterParamsLock.Lock()
defer c.clusterParamsLock.Unlock()
c.localClusterPrivateKey = &ecdsa.PrivateKey{
PublicKey: ecdsa.PublicKey{
Curve: elliptic.P521(),
X: adv.ClusterKeyParams.X,
Y: adv.ClusterKeyParams.Y,
},
D: adv.ClusterKeyParams.D,
}
c.localClusterCert = adv.ClusterCert
cert, err := x509.ParseCertificate(c.localClusterCert)
if err != nil {
2017-03-01 23:16:47 +00:00
c.logger.Error("core: failed parsing local cluster certificate", "error", err)
return fmt.Errorf("error parsing local cluster certificate: %v", err)
}
c.localClusterParsedCert = cert
return nil
}
// setupCluster creates storage entries for holding Vault cluster information.
2016-07-26 13:18:38 +00:00
// Entries will be created only if they are not already present. If clusterName
// is not supplied, this method will auto-generate it.
func (c *Core) setupCluster() error {
2017-01-06 20:42:18 +00:00
// Prevent data races with the TLS parameters
c.clusterParamsLock.Lock()
defer c.clusterParamsLock.Unlock()
// Check if storage index is already present or not
2016-07-26 13:18:38 +00:00
cluster, err := c.Cluster()
if err != nil {
2016-08-19 20:45:17 +00:00
c.logger.Error("core: failed to get cluster details", "error", err)
return err
}
var modified bool
if cluster == nil {
cluster = &Cluster{}
}
if cluster.Name == "" {
// If cluster name is not supplied, generate one
if c.clusterName == "" {
2016-08-19 20:45:17 +00:00
c.logger.Trace("core: cluster name not found/set, generating new")
clusterNameBytes, err := uuid.GenerateRandomBytes(4)
if err != nil {
2016-08-19 20:45:17 +00:00
c.logger.Error("core: failed to generate cluster name", "error", err)
return err
}
c.clusterName = fmt.Sprintf("vault-cluster-%08x", clusterNameBytes)
}
cluster.Name = c.clusterName
2016-08-19 20:45:17 +00:00
if c.logger.IsDebug() {
c.logger.Debug("core: cluster name set", "name", cluster.Name)
}
modified = true
}
if cluster.ID == "" {
2016-08-19 20:45:17 +00:00
c.logger.Trace("core: cluster ID not found, generating new")
// Generate a clusterID
cluster.ID, err = uuid.GenerateUUID()
if err != nil {
2016-08-19 20:45:17 +00:00
c.logger.Error("core: failed to generate cluster identifier", "error", err)
return err
}
2016-08-19 20:45:17 +00:00
if c.logger.IsDebug() {
c.logger.Debug("core: cluster ID set", "id", cluster.ID)
}
modified = true
}
2016-08-19 15:03:53 +00:00
// If we're using HA, generate server-to-server parameters
if c.ha != nil {
// Create a private key
if c.localClusterPrivateKey == nil {
2016-08-19 20:45:17 +00:00
c.logger.Trace("core: generating cluster private key")
2016-08-19 15:03:53 +00:00
key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
if err != nil {
2016-08-19 20:45:17 +00:00
c.logger.Error("core: failed to generate local cluster key", "error", err)
2016-08-19 15:03:53 +00:00
return err
}
c.localClusterPrivateKey = key
}
2016-08-19 15:03:53 +00:00
// Create a certificate
if c.localClusterCert == nil {
2016-08-19 20:45:17 +00:00
c.logger.Trace("core: generating local cluster certificate")
2016-08-19 15:03:53 +00:00
host, err := uuid.GenerateUUID()
if err != nil {
return err
}
2017-03-01 23:16:47 +00:00
host = fmt.Sprintf("fw-%s", host)
2016-08-19 15:03:53 +00:00
template := &x509.Certificate{
Subject: pkix.Name{
CommonName: host,
},
DNSNames: []string{host},
ExtKeyUsage: []x509.ExtKeyUsage{
x509.ExtKeyUsageServerAuth,
x509.ExtKeyUsageClientAuth,
},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement | x509.KeyUsageCertSign,
SerialNumber: big.NewInt(mathrand.Int63()),
NotBefore: time.Now().Add(-30 * time.Second),
// 30 years of single-active uptime ought to be enough for anybody
NotAfter: time.Now().Add(262980 * time.Hour),
BasicConstraintsValid: true,
IsCA: true,
}
2016-08-19 15:03:53 +00:00
certBytes, err := x509.CreateCertificate(rand.Reader, template, template, c.localClusterPrivateKey.Public(), c.localClusterPrivateKey)
if err != nil {
2016-08-19 20:45:17 +00:00
c.logger.Error("core: error generating self-signed cert", "error", err)
2017-01-06 20:42:18 +00:00
return errwrap.Wrapf("unable to generate local cluster certificate: {{err}}", err)
2016-08-19 15:03:53 +00:00
}
parsedCert, err := x509.ParseCertificate(certBytes)
2016-08-19 15:03:53 +00:00
if err != nil {
2016-08-19 20:45:17 +00:00
c.logger.Error("core: error parsing self-signed cert", "error", err)
2017-01-06 20:42:18 +00:00
return errwrap.Wrapf("error parsing generated certificate: {{err}}", err)
2016-08-19 15:03:53 +00:00
}
2016-08-19 15:03:53 +00:00
c.localClusterCert = certBytes
c.localClusterParsedCert = parsedCert
}
}
if modified {
// Encode the cluster information into as a JSON string
rawCluster, err := json.Marshal(cluster)
if err != nil {
2016-08-19 20:45:17 +00:00
c.logger.Error("core: failed to encode cluster details", "error", err)
return err
}
// Store it
err = c.barrier.Put(&Entry{
Key: coreLocalClusterInfoPath,
Value: rawCluster,
})
if err != nil {
2016-08-19 20:45:17 +00:00
c.logger.Error("core: failed to store cluster details", "error", err)
return err
}
}
return nil
}
// startClusterListener starts cluster request listeners during postunseal. It
2016-08-19 15:03:53 +00:00
// is assumed that the state lock is held while this is run. Right now this
// only starts forwarding listeners; it's TBD whether other request types will
// be built in the same mechanism or started independently.
func (c *Core) startClusterListener() error {
if c.clusterAddr == "" {
2017-03-01 23:16:47 +00:00
c.logger.Info("core: clustering disabled, not starting listeners")
return nil
}
2016-08-19 15:03:53 +00:00
if c.clusterListenerAddrs == nil || len(c.clusterListenerAddrs) == 0 {
2017-03-01 23:16:47 +00:00
c.logger.Warn("core: clustering not disabled but no addresses to listen on")
2016-08-19 15:03:53 +00:00
return fmt.Errorf("cluster addresses not found")
}
2017-03-01 23:16:47 +00:00
c.logger.Trace("core: starting cluster listeners")
2016-08-19 15:03:53 +00:00
err := c.startForwarding()
if err != nil {
return err
}
return nil
}
// stopClusterListener stops any existing listeners during preseal. It is
// assumed that the state lock is held while this is run.
func (c *Core) stopClusterListener() {
2016-08-19 15:03:53 +00:00
if c.clusterAddr == "" {
2017-03-01 23:16:47 +00:00
c.logger.Trace("core: clustering disabled, not stopping listeners")
2016-08-19 15:03:53 +00:00
return
}
if !c.clusterListenersRunning {
2017-03-01 23:16:47 +00:00
c.logger.Info("core: cluster listeners not running")
return
}
2017-03-01 23:16:47 +00:00
c.logger.Info("core: stopping cluster listeners")
2016-08-19 15:03:53 +00:00
// Tell the goroutine managing the listeners to perform the shutdown
// process
c.clusterListenerShutdownCh <- struct{}{}
// The reason for this loop-de-loop is that we may be unsealing again
// quickly, and if the listeners are not yet closed, we will get socket
// bind errors. This ensures proper ordering.
2017-03-01 23:16:47 +00:00
c.logger.Trace("core: waiting for success notification while stopping cluster listeners")
<-c.clusterListenerShutdownSuccessCh
c.clusterListenersRunning = false
2017-03-01 23:16:47 +00:00
c.logger.Info("core: cluster listeners successfully shut down")
}
// ClusterTLSConfig generates a TLS configuration based on the local/replicated
// cluster key and cert.
func (c *Core) ClusterTLSConfig() (*tls.Config, error) {
// Using lookup functions allows just-in-time lookup of the current state
// of clustering as connections come and go
serverLookup := func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
switch {
default:
var localCert bytes.Buffer
c.clusterParamsLock.RLock()
localCert.Write(c.localClusterCert)
localSigner := c.localClusterPrivateKey
parsedCert := c.localClusterParsedCert
c.clusterParamsLock.RUnlock()
if localCert.Len() == 0 {
return nil, fmt.Errorf("got forwarding connection but no local cert")
}
2016-08-19 15:03:53 +00:00
//c.logger.Trace("core: performing cert name lookup", "hello_server_name", clientHello.ServerName, "local_cluster_cert_name", parsedCert.Subject.CommonName)
2016-08-19 15:03:53 +00:00
return &tls.Certificate{
Certificate: [][]byte{localCert.Bytes()},
PrivateKey: localSigner,
Leaf: parsedCert,
}, nil
}
return nil, nil
}
clientLookup := func(requestInfo *tls.CertificateRequestInfo) (*tls.Certificate, error) {
//c.logger.Trace("core: performing client cert lookup")
if len(requestInfo.AcceptableCAs) != 1 {
return nil, fmt.Errorf("expected only a single acceptable CA")
}
var localCert bytes.Buffer
c.clusterParamsLock.RLock()
localCert.Write(c.localClusterCert)
localSigner := c.localClusterPrivateKey
parsedCert := c.localClusterParsedCert
c.clusterParamsLock.RUnlock()
if localCert.Len() == 0 {
return nil, fmt.Errorf("forwarding connection client but no local cert")
}
return &tls.Certificate{
Certificate: [][]byte{localCert.Bytes()},
PrivateKey: localSigner,
Leaf: parsedCert,
}, nil
}
serverConfigLookup := func(clientHello *tls.ClientHelloInfo) (*tls.Config, error) {
//c.logger.Trace("core: performing server config lookup")
for _, v := range clientHello.SupportedProtos {
switch v {
case "h2", requestForwardingALPN:
default:
return nil, fmt.Errorf("unknown ALPN proto %s", v)
}
}
caPool := x509.NewCertPool()
ret := &tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
GetCertificate: serverLookup,
GetClientCertificate: clientLookup,
MinVersion: tls.VersionTLS12,
RootCAs: caPool,
ClientCAs: caPool,
NextProtos: clientHello.SupportedProtos,
CipherSuites: c.clusterCipherSuites,
}
switch {
default:
c.clusterParamsLock.RLock()
parsedCert := c.localClusterParsedCert
c.clusterParamsLock.RUnlock()
if parsedCert == nil {
return nil, fmt.Errorf("forwarding connection client but no local cert")
}
caPool.AddCert(parsedCert)
}
return ret, nil
}
tlsConfig := &tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
GetCertificate: serverLookup,
GetClientCertificate: clientLookup,
GetConfigForClient: serverConfigLookup,
MinVersion: tls.VersionTLS12,
CipherSuites: c.clusterCipherSuites,
}
var localCert bytes.Buffer
c.clusterParamsLock.RLock()
localCert.Write(c.localClusterCert)
parsedCert := c.localClusterParsedCert
c.clusterParamsLock.RUnlock()
if parsedCert != nil {
tlsConfig.ServerName = parsedCert.Subject.CommonName
pool := x509.NewCertPool()
pool.AddCert(parsedCert)
tlsConfig.RootCAs = pool
tlsConfig.ClientCAs = pool
}
return tlsConfig, nil
}
2016-08-19 15:03:53 +00:00
func (c *Core) SetClusterListenerAddrs(addrs []*net.TCPAddr) {
c.clusterListenerAddrs = addrs
}
func (c *Core) SetClusterHandler(handler http.Handler) {
c.clusterHandler = handler
}