Remove the deprecated old KMS worker auth mechanism (#3935)

This has been superceded by the nodeenrollment-based KMS worker auth
mechanism. This commit only removes the ability to connect with this
mechanism; some upgrade logic will remain intact for a bit and
can be removed later.
This commit is contained in:
Jeff Mitchell authored and GitHub committed 2024-01-12 11:58:12 -05:00
1 parent fb2aa30e80
commit 9332179a01
18 files changed
+253 -926

No files matched your search

+3 -3
View File
@@ -158,7 +158,7 @@ type Controller struct {
// replying to queries with "503 Service Unavailable".
HealthService *health.Service
pkiConnManager *cluster.DownstreamManager
downstreamConnManager *cluster.DownstreamManager
// ControllerExtension defines a std way to extend the controller
ControllerExtension intglobals.ControllerExtension
@@ -178,7 +178,7 @@ func New(ctx context.Context, conf *Config) (*Controller, error) {
workerStatusUpdateTimes: new(sync.Map),
enabledPlugins: conf.Server.EnabledPlugins,
apiListeners: make([]*base.ServerListener, 0),
pkiConnManager: cluster.NewDownstreamManager(),
downstreamConnManager: cluster.NewDownstreamManager(),
workerStatusGracePeriod: new(atomic.Int64),
livenessTimeToStale: new(atomic.Int64),
}
@@ -523,7 +523,7 @@ func (c *Controller) Start() error {
defer c.tickerWg.Done()
c.startCloseExpiredPendingTokens(c.baseContext)
}()
if err := c.startWorkerConnectionMaintenanceTicking(c.baseContext, c.tickerWg, c.pkiConnManager); err != nil {
if err := c.startWorkerConnectionMaintenanceTicking(c.baseContext, c.tickerWg, c.downstreamConnManager); err != nil {
return errors.Wrap(c.baseContext, err, op)
}
@@ -1,156 +0,0 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package controller
import (
"context"
"crypto/tls"
"fmt"
"net"
"strings"
"github.com/hashicorp/boundary/internal/daemon/common"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/internal/event"
nodeenet "github.com/hashicorp/nodeenrollment/net"
)
// tempError is an error that satisfies the temporary error interface that is
// internally used by gRPC to determine whether an error should cause a listener
// to die. Any error that isn't an accept error is wrapped in this since one
// connection failing TLS wise doesn't mean we don't want to accept any more...
type tempError struct {
error
}
// newTempError is a "temporary" error
func newTempError(inner error) tempError {
return tempError{error: inner}
}
func (t tempError) Temporary() bool {
return true
}
// startKmsConnRouter allows us to validate the nonce from a connection before
// handing it off to other purposes, such as the gRPC server. It is expected
// that the first thing a connection sends after successful TLS validation is
// the nonce that was contained in the KMS-encrypted TLS info. The reason is for
// replay attacks -- since the ALPN NextProtos are sent in the clear, we don't
// want anyone sniffing the connection to simply replay the hello message and
// gain access. By requiring the information encrypted within that message to
// match the first bytes sent in the connection itself, we require that the
// service making the incoming connection had to either be the service that did
// the initial encryption, or had to be able to decrypt that against the same
// KMS key. This means that KMS access is a requirement, and simple replay
// itself is not sufficient.
func startKmsConnRouter(
ctx context.Context,
c *Controller,
baseLn net.Listener,
authedListener,
reverseGrpcListener *nodeenet.MultiplexingListener,
) error {
const op = "controller.startKmsAuthRouter"
switch {
case c == nil:
return errors.New(ctx, errors.InvalidParameter, op, "nil Controller")
case baseLn == nil:
return errors.New(ctx, errors.InvalidParameter, op, "nil baseLn")
case authedListener == nil:
return errors.New(ctx, errors.InvalidParameter, op, "nil authedListener")
case reverseGrpcListener == nil:
return errors.New(ctx, errors.InvalidParameter, op, "nil reverseGrpcListener")
}
go func() {
for {
conn, err := baseLn.Accept()
if err != nil {
if err == net.ErrClosed {
// We're done
return
}
// Conn may already be closed but can't be sure, so just try anyways
if conn != nil {
if err := conn.Close(); err != nil {
event.WriteError(ctx, op, err, event.WithInfoMsg("error closing worker connection"))
}
}
event.WriteError(ctx, op, err, event.WithInfoMsg("error accepting kms connection"))
continue
}
if conn == nil {
// No idea why this would happen, but be safe before we operate
// on it below
event.WriteError(ctx, op, fmt.Errorf("connection is nil"))
continue
}
tlsConn, ok := conn.(*tls.Conn)
if !ok {
// This should never happen, but is just to be safe
event.WriteError(ctx, op, fmt.Errorf("connection is not a *tls.Conn"))
_ = conn.Close()
continue
}
if !strings.HasPrefix(tlsConn.ConnectionState().NegotiatedProtocol, "v1workerauth") {
// If we're here it hasn't been handled by PKI and can't be
// handled here. We should never actually get here...
event.WriteError(ctx, op, fmt.Errorf("connection is not a kms connection"))
_ = conn.Close()
continue
}
nonce := make([]byte, 20)
read, err := conn.Read(nonce)
if err != nil {
if err := conn.Close(); err != nil {
event.WriteError(ctx, op, err, event.WithInfoMsg("error closing worker connection"))
}
event.WriteError(ctx, op, err, event.WithInfoMsg("error reading nonce from connection"))
continue
}
if read != len(nonce) {
if err := conn.Close(); err != nil {
event.WriteError(ctx, op, err, event.WithInfoMsg("error closing worker connection"))
}
event.WriteError(ctx, op, fmt.Errorf("error reading nonce from worker, expected %d bytes, got %d", 20, read))
continue
}
workerInfoRaw, found := c.workerAuthCache.Load(string(nonce))
if !found {
if err := conn.Close(); err != nil {
event.WriteError(ctx, op, err, event.WithInfoMsg("error closing worker connection"))
}
event.WriteError(ctx, op, fmt.Errorf("did not find valid nonce for incoming worker"))
continue
}
workerInfo := workerInfoRaw.(*workerAuthEntry)
workerInfo.conn = tlsConn
c.workerAuthCache.Delete(string(nonce))
event.WriteSysEvent(ctx, op, "worker successfully authed", "name", workerInfo.Name, "description", workerInfo.Description, "proxy_address", workerInfo.ProxyAddress)
found = false
for _, proto := range workerInfo.clientNextProtos {
if proto == common.ReverseGrpcConnectionAlpnValue {
reverseGrpcListener.IngressConn(tlsConn, nil)
found = true
break
}
}
if found {
continue
}
// Didn't find specific ALPN values, so it's a normal grpc
// connection
authedListener.IngressConn(tlsConn, nil)
}
}()
return nil
}
+11 -44
View File
@@ -5,7 +5,6 @@ package controller
import (
"context"
"crypto/tls"
stderrors "errors"
"fmt"
"math"
@@ -159,9 +158,6 @@ func (c *Controller) configureForCluster(ln *base.ServerListener) (func(), error
Context: c.baseContext,
Storage: workerAuthStorage,
BaseListener: ln.ClusterListener,
BaseTlsConfiguration: &tls.Config{
GetConfigForClient: c.validateWorkerTls,
},
Options: []nodee.Option{
nodee.WithLogger(eventLogger),
nodee.WithRegistrationWrapper(wrapperToUse),
@@ -185,26 +181,11 @@ func (c *Controller) configureForCluster(ln *base.ServerListener) (func(), error
return nil, fmt.Errorf("error instantiating node enrollment authed split listener: %w", err)
}
// This wraps the normal pki worker connections with a listener which adds
// the worker key id of the connections to the controller's pkiConnManager.
pkiWorkerTrackingListener, err := cluster.NewTrackingListener(c.baseContext, nodeeAuthedListener, c.pkiConnManager, sourcePurpose(grpcListenerPurpose))
// This wraps connections with a listener which adds the worker key id of
// the connections to the controller's nodeeConnManager.
workerTrackingListener, err := cluster.NewTrackingListener(c.baseContext, nodeeAuthedListener, c.downstreamConnManager, sourcePurpose(grpcListenerPurpose))
if err != nil {
return nil, fmt.Errorf("%s: error creating pki worker tracking listener: %w", op, err)
}
// Create a multiplexer to unify connections between PKI and KMS
multiplexingAuthedListener, err := nodeenet.NewMultiplexingListener(c.baseContext, nodeeAuthedListener.Addr())
if err != nil {
return nil, fmt.Errorf("error instantiating authed multiplexed listener: %w", err)
}
if err := multiplexingAuthedListener.IngressListener(pkiWorkerTrackingListener); err != nil {
return nil, fmt.Errorf("error adding authed evented listener to multiplexed listener: %w", err)
}
// Connections that came in on the cluster listener that are not authed via
// PKI need to be sent for KMS routing
nodeeUnauthedListener, err := splitListener.GetListener(nodeenet.UnauthenticatedNextProto)
if err != nil {
return nil, fmt.Errorf("error instantiating node enrollment unauthed split listener: %w", err)
return nil, fmt.Errorf("%s: error creating node enrollment worker tracking listener: %w", op, err)
}
// Connections coming in here are authed by nodeenrollment and are for the
@@ -214,25 +195,11 @@ func (c *Controller) configureForCluster(ln *base.ServerListener) (func(), error
return nil, fmt.Errorf("error instantiating reverse gprc connection split listener: %w", err)
}
// This wraps the reverse grpc pki worker connections with a listener which
// adds the worker key id of the connections to the pkiConnManager.
revPkiWorkerTrackingListener, err := cluster.NewTrackingListener(c.baseContext, reverseGrpcListener, c.pkiConnManager, sourcePurpose(reverseGrpcListenerPurpose))
// This wraps the reverse grpc connections with a listener which adds the
// worker key id of the connections to the nodeeConnManager.
revWorkerTrackingListener, err := cluster.NewTrackingListener(c.baseContext, reverseGrpcListener, c.downstreamConnManager, sourcePurpose(reverseGrpcListenerPurpose))
if err != nil {
return nil, fmt.Errorf("%s: error creating reverse grpc pki worker tracking listener: %w", op, err)
}
// Create a multiplexer to unify reverse grpc connections between PKI and KMS
multiplexingReverseGrpcListener, err := nodeenet.NewMultiplexingListener(c.baseContext, reverseGrpcListener.Addr())
if err != nil {
return nil, fmt.Errorf("error instantiating reverse grpc multiplexed listener: %w", err)
}
if err := multiplexingReverseGrpcListener.IngressListener(revPkiWorkerTrackingListener); err != nil {
return nil, fmt.Errorf("error adding reverse grpc listener to multiplexed listener: %w", err)
}
// Start routing KMS connections
if err := startKmsConnRouter(c.baseContext, c, nodeeUnauthedListener, multiplexingAuthedListener, multiplexingReverseGrpcListener); err != nil {
return nil, errors.Wrap(c.baseContext, err, op)
return nil, fmt.Errorf("%s: error creating reverse grpc worker tracking listener: %w", op, err)
}
workerReqInterceptor, err := workerRequestInfoInterceptor(c.baseContext, c.conf.Eventer)
@@ -269,7 +236,7 @@ func (c *Controller) configureForCluster(ln *base.ServerListener) (func(), error
ln.GrpcServer = workerServer
return func() {
err := handleSecondaryConnection(c.baseContext, metric.InstrumentClusterTrackingListener(multiplexingReverseGrpcListener, reverseGrpcListenerPurpose),
err := handleSecondaryConnection(c.baseContext, metric.InstrumentClusterTrackingListener(revWorkerTrackingListener, reverseGrpcListenerPurpose),
c.downstreamConns)
if err != nil {
event.WriteError(c.baseContext, op, err, event.WithInfoMsg("handleSecondaryConnection error"))
@@ -281,9 +248,9 @@ func (c *Controller) configureForCluster(ln *base.ServerListener) (func(), error
}
}()
go func() {
err := ln.GrpcServer.Serve(metric.InstrumentClusterTrackingListener(multiplexingAuthedListener, grpcListenerPurpose))
err := ln.GrpcServer.Serve(metric.InstrumentClusterTrackingListener(workerTrackingListener, grpcListenerPurpose))
if err != nil && !errors.Is(err, net.ErrClosed) {
event.WriteError(c.baseContext, op, err, event.WithInfoMsg("multiplexingAuthedListener error"))
event.WriteError(c.baseContext, op, err, event.WithInfoMsg("workerTrackingListener error"))
}
}()
}, nil
+61 -65
View File
@@ -9,28 +9,36 @@ import (
"crypto/rand"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"io"
"log"
"math/big"
"net"
"net/http"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/internal/daemon/cluster"
"github.com/hashicorp/boundary/internal/server"
"github.com/hashicorp/boundary/version"
"github.com/hashicorp/go-secure-stdlib/base62"
"github.com/hashicorp/go-secure-stdlib/configutil/v2"
"github.com/hashicorp/go-secure-stdlib/listenerutil"
"github.com/hashicorp/nodeenrollment"
"github.com/hashicorp/nodeenrollment/protocol"
"github.com/hashicorp/nodeenrollment/storage/inmem"
"github.com/hashicorp/nodeenrollment/types"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/protobuf/proto"
"google.golang.org/grpc/backoff"
"google.golang.org/grpc/credentials/insecure"
)
func TestStartListeners(t *testing.T) {
@@ -240,17 +248,24 @@ func TestStartListeners(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
debugEnabled := new(atomic.Bool)
debugEnabled.Store(false)
opts := &TestControllerOpts{
EnableEventing: false,
WorkerAuthDebuggingEnabled: debugEnabled,
}
tc := &TestController{
t: t,
ctx: ctx,
cancel: cancel,
opts: opts,
shutdownDoneCh: make(chan struct{}),
shutdownOnce: new(sync.Once),
opts: new(TestControllerOpts),
}
t.Cleanup(func() { tc.Shutdown() })
conf := TestControllerConfig(t, ctx, tc, nil)
conf := TestControllerConfig(t, ctx, tc, opts)
conf.RawConfig.SharedConfig = &configutil.SharedConfig{Listeners: tt.listeners, DisableMlock: true}
err := conf.SetupListeners(nil, conf.RawConfig.SharedConfig, []string{"api", "cluster"})
@@ -718,11 +733,21 @@ func TestListenerCloseErrorCheck(t *testing.T) {
}
func clusterGrpcDialNoError(t *testing.T, c *Controller, network, addr string) {
grpcConn, err := grpc.Dial(addr,
grpc.WithInsecure(),
grpcConn, err := grpc.DialContext(
context.Background(),
addr,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithBlock(),
grpc.WithTimeout(5*time.Second),
grpc.WithContextDialer(clusterTestDialer(t, c, network)),
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithConnectParams(grpc.ConnectParams{
Backoff: backoff.Config{
BaseDelay: time.Second,
Multiplier: 1.2,
Jitter: 0.2,
MaxDelay: 3 * time.Second,
},
}),
)
require.NoError(t, err)
require.NoError(t, grpcConn.Close())
@@ -757,7 +782,7 @@ func testTlsHttpClient(t *testing.T, filePath string) *http.Client {
f, err := os.Open(filePath)
require.NoError(t, err)
certBytes, err := ioutil.ReadAll(f)
certBytes, err := io.ReadAll(f)
require.NoError(t, err)
require.NoError(t, f.Close())
@@ -795,68 +820,39 @@ func createTestCert(t *testing.T) ([]byte, ed25519.PublicKey, ed25519.PrivateKey
func clusterTestDialer(t *testing.T, c *Controller, network string) func(context.Context, string) (net.Conn, error) {
return func(ctx context.Context, addr string) (net.Conn, error) {
certBytes, _, priv := createTestCert(t)
marshaledKey, err := x509.MarshalPKCS8PrivateKey(priv)
storage, err := inmem.New(ctx)
require.NoError(t, err)
nonce, err := base62.Random(20)
_, err = types.NewNodeCredentials(
ctx,
storage,
)
require.NoError(t, err)
// after 0.13.0 we need to include the version that matches between the
// controller and the worker otherwise worker tls auth with fail
v := version.Get().Version
if version.Get().VersionMetadata != "" {
v += "+" + version.Get().VersionMetadata
name, err := base62.Random(20)
require.NoError(t, err)
wci := &cluster.WorkerConnectionInfo{
BoundaryVersion: version.Get().VersionNumber(),
Name: strings.ToLower(name),
OperationalState: server.ActiveOperationalState.String(),
}
info := base.WorkerAuthInfo{
CertPEM: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certBytes}),
KeyPEM: pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: marshaledKey}),
ConnectionNonce: nonce,
BoundaryVersion: v,
st, err := wci.AsConnectionStateStruct()
require.NoError(t, err)
conn, err := protocol.Dial(
ctx,
storage,
addr,
nodeenrollment.WithState(st),
nodeenrollment.WithRegistrationWrapper(c.conf.WorkerAuthKms),
nodeenrollment.WithLogger(c.conf.Logger),
nodeenrollment.WithWrappingRegistrationFlowApplicationSpecificParams(st),
)
if err != nil {
log.Println(err)
}
infoBytes, err := json.Marshal(info)
require.NoError(t, err)
encInfo, err := c.conf.WorkerAuthKms.Encrypt(ctx, infoBytes, nil)
require.NoError(t, err)
protoEncInfo, err := proto.Marshal(encInfo)
require.NoError(t, err)
b64alpn := base64.RawStdEncoding.EncodeToString(protoEncInfo)
var nextProtos []string
var count int
for i := 0; i < len(b64alpn); i += 230 {
end := i + 230
if end > len(b64alpn) {
end = len(b64alpn)
}
nextProtos = append(nextProtos, fmt.Sprintf("v1workerauth-%02d-%s", count, b64alpn[i:end]))
count++
}
cert, err := x509.ParseCertificate(certBytes)
require.NoError(t, err)
rootCAs := x509.NewCertPool()
rootCAs.AddCert(cert)
tlsCert, err := tls.X509KeyPair(info.CertPEM, info.KeyPEM)
require.NoError(t, err)
conn, err := tls.Dial(network, addr, &tls.Config{
Certificates: []tls.Certificate{tlsCert},
RootCAs: rootCAs,
NextProtos: nextProtos,
MinVersion: tls.VersionTLS13,
})
require.NoError(t, err)
_, err = conn.Write([]byte(nonce))
require.NoError(t, err)
return conn, nil
}
}
@@ -1,145 +0,0 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package controller
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net"
"strings"
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/internal/event"
"github.com/hashicorp/boundary/internal/server"
"github.com/hashicorp/boundary/version"
wrapping "github.com/hashicorp/go-kms-wrapping/v2"
"google.golang.org/protobuf/proto"
)
type workerAuthEntry struct {
*base.WorkerAuthInfo
conn net.Conn
clientNextProtos []string
}
// validateWorkerTls is called by the Go TLS stack with client info. It calls
// v1WorkerAuthConfig to validate the encryption and ensure the nonce has not
// been replayed, then stores connection information into the auth cache, which
// is used by the intercepting listener to log information.
func (c Controller) validateWorkerTls(hello *tls.ClientHelloInfo) (*tls.Config, error) {
const op = "controller.(Controller).validateWorkerTls"
for _, p := range hello.SupportedProtos {
switch {
case strings.HasPrefix(p, "v1workerauth-"):
tlsConf, workerInfo, err := c.v1WorkerAuthConfig(hello.SupportedProtos)
if err == nil {
// Store info that can be retrieved in the intercepting
// listener.
//
// NOTE: This is not a load-or-store because we need to ensure
// replays can't happen across controllers, hence storing in the
// database in v1WorkerAuthConfig. Although this could serve as
// a secondary check, a load-or-store here keeps the test from
// ensuring that it is rejected at the database level via the
// nonce unique constraint, which is by far the more important
// thing to validate (although there are DB-level tests for that
// too).
authEntry := &workerAuthEntry{
WorkerAuthInfo: workerInfo,
}
if len(hello.SupportedProtos) > 0 {
authEntry.clientNextProtos = make([]string, len(hello.SupportedProtos))
copy(authEntry.clientNextProtos, hello.SupportedProtos)
}
c.workerAuthCache.Store(workerInfo.ConnectionNonce, authEntry)
}
return tlsConf, err
}
}
return nil, errors.New("no supported protos found in hello")
}
// v1WorkerAuthConfig:
//
// * Reads the information from ALPN, combining across protos
// * Combines them to form the encrypted auth information
// * Validates it by decrypting against the configured KMS
// * Ensures that the nonce is unique to prevent replay attacks
// * Returns the shared TLS configuration that is used to establish the connection
func (c Controller) v1WorkerAuthConfig(protos []string) (*tls.Config, *base.WorkerAuthInfo, error) {
const op = "controller.(Controller).v1WorkerAuthConfig"
var firstMatchProto string
var encString string
for _, p := range protos {
if strings.HasPrefix(p, "v1workerauth-") {
// Strip that and the number
encString += strings.TrimPrefix(p, "v1workerauth-")[3:]
if firstMatchProto == "" {
firstMatchProto = p
}
}
}
if firstMatchProto == "" {
return nil, nil, errors.New("no matching proto found")
}
marshaledEncInfo, err := base64.RawStdEncoding.DecodeString(encString)
if err != nil {
return nil, nil, err
}
encInfo := new(wrapping.BlobInfo)
if err := proto.Unmarshal(marshaledEncInfo, encInfo); err != nil {
return nil, nil, err
}
if isNil(c.conf.WorkerAuthKms) {
return nil, nil, errors.New("worker auth kms not set")
}
marshaledInfo, err := c.conf.WorkerAuthKms.Decrypt(context.Background(), encInfo)
if err != nil {
return nil, nil, err
}
info := new(base.WorkerAuthInfo)
if err := json.Unmarshal(marshaledInfo, info); err != nil {
return nil, nil, err
}
if version.Get().VersionMetadata != "" {
incomingVer := version.FromVersionString(info.BoundaryVersion)
if (incomingVer == nil || incomingVer.VersionMetadata == "") && version.SupportsFeature(version.Binary, version.RequireVersionInWorkerInfo) {
err := errors.New("build contains version with metadata, incoming worker version is nil or has mismatched metadata")
event.WriteError(c.baseContext, op, err)
return nil, nil, err
}
}
// Check for replays
serversRepo, err := c.ServersRepoFn()
if err != nil {
return nil, nil, fmt.Errorf("unable to fetch server repo: %w", err)
}
if err := serversRepo.AddNonce(c.baseContext, info.ConnectionNonce, server.NoncePurposeWorkerAuth); err != nil {
return nil, nil, fmt.Errorf("unable to add connection nonce to database: %w", err)
}
rootCAs := x509.NewCertPool()
if ok := rootCAs.AppendCertsFromPEM(info.CertPEM); !ok {
return nil, info, errors.New("unable to add ca cert to cert pool")
}
tlsCert, err := tls.X509KeyPair(info.CertPEM, info.KeyPEM)
if err != nil {
return nil, info, err
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{tlsCert},
ClientCAs: rootCAs,
ClientAuth: tls.RequireAndVerifyClientCert,
NextProtos: []string{firstMatchProto},
MinVersion: tls.VersionTLS13,
}
return tlsConfig, info, nil
}