2018-04-03 18:10:59 +00:00
|
|
|
package proxy
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"crypto/tls"
|
|
|
|
"errors"
|
|
|
|
"net"
|
2018-06-11 16:53:28 +00:00
|
|
|
"sync"
|
2018-04-03 18:10:59 +00:00
|
|
|
"sync/atomic"
|
|
|
|
"time"
|
|
|
|
|
2018-06-11 16:53:28 +00:00
|
|
|
metrics "github.com/armon/go-metrics"
|
2021-04-28 21:53:43 +00:00
|
|
|
"github.com/hashicorp/go-hclog"
|
|
|
|
|
2018-09-12 16:07:47 +00:00
|
|
|
"github.com/hashicorp/consul/api"
|
2018-04-03 18:10:59 +00:00
|
|
|
"github.com/hashicorp/consul/connect"
|
2019-06-04 14:02:38 +00:00
|
|
|
"github.com/hashicorp/consul/ipaddr"
|
2018-04-03 18:10:59 +00:00
|
|
|
)
|
|
|
|
|
2018-06-11 16:53:28 +00:00
|
|
|
const (
|
2020-01-28 23:50:41 +00:00
|
|
|
publicListenerPrefix = "inbound"
|
|
|
|
upstreamListenerPrefix = "upstream"
|
2018-06-11 16:53:28 +00:00
|
|
|
)
|
|
|
|
|
2018-04-03 18:10:59 +00:00
|
|
|
// Listener is the implementation of a specific proxy listener. It has pluggable
|
|
|
|
// Listen and Dial methods to suit public mTLS vs upstream semantics. It handles
|
|
|
|
// the lifecycle of the listener and all connections opened through it
|
|
|
|
type Listener struct {
|
|
|
|
// Service is the connect service instance to use.
|
|
|
|
Service *connect.Service
|
|
|
|
|
2018-09-12 16:07:47 +00:00
|
|
|
// listenFunc, dialFunc, and bindAddr are set by type-specific constructors.
|
2018-04-03 18:10:59 +00:00
|
|
|
listenFunc func() (net.Listener, error)
|
|
|
|
dialFunc func() (net.Conn, error)
|
2018-04-26 13:01:20 +00:00
|
|
|
bindAddr string
|
2018-04-03 18:10:59 +00:00
|
|
|
|
|
|
|
stopFlag int32
|
|
|
|
stopChan chan struct{}
|
|
|
|
|
2018-04-20 21:26:00 +00:00
|
|
|
// listeningChan is closed when listener is opened successfully. It's really
|
|
|
|
// only for use in tests where we need to coordinate wait for the Serve
|
|
|
|
// goroutine to be running before we proceed trying to connect. On my laptop
|
|
|
|
// this always works out anyway but on constrained VMs and especially docker
|
|
|
|
// containers (e.g. in CI) we often see the Dial routine win the race and get
|
|
|
|
// `connection refused`. Retry loops and sleeps are unpleasant workarounds and
|
|
|
|
// this is cheap and correct.
|
|
|
|
listeningChan chan struct{}
|
2021-04-28 21:53:43 +00:00
|
|
|
listener net.Listener
|
2018-04-20 21:26:00 +00:00
|
|
|
|
2020-01-28 23:50:41 +00:00
|
|
|
logger hclog.Logger
|
2018-06-11 16:53:28 +00:00
|
|
|
|
|
|
|
// Gauge to track current open connections
|
2019-01-23 15:09:01 +00:00
|
|
|
activeConns int32
|
2018-06-11 16:53:28 +00:00
|
|
|
connWG sync.WaitGroup
|
|
|
|
metricPrefix string
|
|
|
|
metricLabels []metrics.Label
|
2018-04-03 18:10:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewPublicListener returns a Listener setup to listen for public mTLS
|
|
|
|
// connections and proxy them to the configured local application over TCP.
|
|
|
|
func NewPublicListener(svc *connect.Service, cfg PublicListenerConfig,
|
2020-01-28 23:50:41 +00:00
|
|
|
logger hclog.Logger) *Listener {
|
2019-06-04 14:02:38 +00:00
|
|
|
bindAddr := ipaddr.FormatAddressPort(cfg.BindAddress, cfg.BindPort)
|
2018-04-03 18:10:59 +00:00
|
|
|
return &Listener{
|
|
|
|
Service: svc,
|
|
|
|
listenFunc: func() (net.Listener, error) {
|
2018-04-26 13:01:20 +00:00
|
|
|
return tls.Listen("tcp", bindAddr, svc.ServerTLSConfig())
|
2018-04-03 18:10:59 +00:00
|
|
|
},
|
|
|
|
dialFunc: func() (net.Conn, error) {
|
|
|
|
return net.DialTimeout("tcp", cfg.LocalServiceAddress,
|
|
|
|
time.Duration(cfg.LocalConnectTimeoutMs)*time.Millisecond)
|
|
|
|
},
|
2018-04-26 13:01:20 +00:00
|
|
|
bindAddr: bindAddr,
|
2018-04-20 21:26:00 +00:00
|
|
|
stopChan: make(chan struct{}),
|
|
|
|
listeningChan: make(chan struct{}),
|
2020-01-28 23:50:41 +00:00
|
|
|
logger: logger.Named(publicListenerPrefix),
|
|
|
|
metricPrefix: publicListenerPrefix,
|
2018-06-11 16:53:28 +00:00
|
|
|
// For now we only label ourselves as source - we could fetch the src
|
|
|
|
// service from cert on each connection and label metrics differently but it
|
|
|
|
// significaly complicates the active connection tracking here and it's not
|
|
|
|
// clear that it's very valuable - on aggregate looking at all _outbound_
|
|
|
|
// connections across all proxies gets you a full picture of src->dst
|
|
|
|
// traffic. We might expand this later for better debugging of which clients
|
|
|
|
// are abusing a particular service instance but we'll see how valuable that
|
|
|
|
// seems for the extra complication of tracking many gauges here.
|
|
|
|
metricLabels: []metrics.Label{{Name: "dst", Value: svc.Name()}},
|
2018-04-03 18:10:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewUpstreamListener returns a Listener setup to listen locally for TCP
|
|
|
|
// connections that are proxied to a discovered Connect service instance.
|
2018-09-12 16:07:47 +00:00
|
|
|
func NewUpstreamListener(svc *connect.Service, client *api.Client,
|
2020-01-28 23:50:41 +00:00
|
|
|
cfg UpstreamConfig, logger hclog.Logger) *Listener {
|
2018-09-12 16:07:47 +00:00
|
|
|
return newUpstreamListenerWithResolver(svc, cfg,
|
|
|
|
UpstreamResolverFuncFromClient(client), logger)
|
|
|
|
}
|
|
|
|
|
|
|
|
func newUpstreamListenerWithResolver(svc *connect.Service, cfg UpstreamConfig,
|
|
|
|
resolverFunc func(UpstreamConfig) (connect.Resolver, error),
|
2020-01-28 23:50:41 +00:00
|
|
|
logger hclog.Logger) *Listener {
|
2019-06-04 14:02:38 +00:00
|
|
|
bindAddr := ipaddr.FormatAddressPort(cfg.LocalBindAddress, cfg.LocalBindPort)
|
2018-04-03 18:10:59 +00:00
|
|
|
return &Listener{
|
|
|
|
Service: svc,
|
|
|
|
listenFunc: func() (net.Listener, error) {
|
2018-04-26 13:01:20 +00:00
|
|
|
return net.Listen("tcp", bindAddr)
|
2018-04-03 18:10:59 +00:00
|
|
|
},
|
|
|
|
dialFunc: func() (net.Conn, error) {
|
2018-09-12 16:07:47 +00:00
|
|
|
rf, err := resolverFunc(cfg)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2018-04-03 18:10:59 +00:00
|
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(),
|
2018-09-12 16:07:47 +00:00
|
|
|
cfg.ConnectTimeout())
|
2018-04-03 18:10:59 +00:00
|
|
|
defer cancel()
|
2018-09-12 16:07:47 +00:00
|
|
|
return svc.Dial(ctx, rf)
|
2018-04-03 18:10:59 +00:00
|
|
|
},
|
2018-04-26 13:01:20 +00:00
|
|
|
bindAddr: bindAddr,
|
2018-04-20 21:26:00 +00:00
|
|
|
stopChan: make(chan struct{}),
|
|
|
|
listeningChan: make(chan struct{}),
|
2020-01-28 23:50:41 +00:00
|
|
|
logger: logger.Named(upstreamListenerPrefix),
|
|
|
|
metricPrefix: upstreamListenerPrefix,
|
2018-06-11 16:53:28 +00:00
|
|
|
metricLabels: []metrics.Label{
|
|
|
|
{Name: "src", Value: svc.Name()},
|
|
|
|
// TODO(banks): namespace support
|
2018-09-12 16:07:47 +00:00
|
|
|
{Name: "dst_type", Value: string(cfg.DestinationType)},
|
2018-06-11 16:53:28 +00:00
|
|
|
{Name: "dst", Value: cfg.DestinationName},
|
|
|
|
},
|
2018-04-03 18:10:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-20 21:26:00 +00:00
|
|
|
// Serve runs the listener until it is stopped. It is an error to call Serve
|
|
|
|
// more than once for any given Listener instance.
|
2018-04-03 18:10:59 +00:00
|
|
|
func (l *Listener) Serve() error {
|
2018-04-20 21:26:00 +00:00
|
|
|
// Ensure we mark state closed if we fail before Close is called externally.
|
|
|
|
defer l.Close()
|
|
|
|
|
|
|
|
if atomic.LoadInt32(&l.stopFlag) != 0 {
|
|
|
|
return errors.New("serve called on a closed listener")
|
|
|
|
}
|
|
|
|
|
2021-04-28 21:53:43 +00:00
|
|
|
var err error
|
|
|
|
l.listener, err = l.listenFunc()
|
2018-04-03 18:10:59 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2018-04-20 21:26:00 +00:00
|
|
|
close(l.listeningChan)
|
2018-04-03 18:10:59 +00:00
|
|
|
|
|
|
|
for {
|
2021-04-28 21:53:43 +00:00
|
|
|
conn, err := l.listener.Accept()
|
2018-04-03 18:10:59 +00:00
|
|
|
if err != nil {
|
|
|
|
if atomic.LoadInt32(&l.stopFlag) == 1 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-04-28 21:53:43 +00:00
|
|
|
l.connWG.Add(1)
|
2018-04-03 18:10:59 +00:00
|
|
|
go l.handleConn(conn)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// handleConn is the internal connection handler goroutine.
|
|
|
|
func (l *Listener) handleConn(src net.Conn) {
|
|
|
|
defer src.Close()
|
2021-04-28 21:53:43 +00:00
|
|
|
// Make sure Listener.Close waits for this conn to be cleaned up.
|
|
|
|
defer l.connWG.Done()
|
2018-04-03 18:10:59 +00:00
|
|
|
|
|
|
|
dst, err := l.dialFunc()
|
|
|
|
if err != nil {
|
2020-01-28 23:50:41 +00:00
|
|
|
l.logger.Error("failed to dial", "error", err)
|
2018-04-03 18:10:59 +00:00
|
|
|
return
|
|
|
|
}
|
2018-06-11 16:53:28 +00:00
|
|
|
|
|
|
|
// Track active conn now (first function call) and defer un-counting it when
|
|
|
|
// it closes.
|
|
|
|
defer l.trackConn()()
|
|
|
|
|
2018-04-03 18:10:59 +00:00
|
|
|
// Note no need to defer dst.Close() since conn handles that for us.
|
|
|
|
conn := NewConn(src, dst)
|
|
|
|
defer conn.Close()
|
|
|
|
|
2018-06-11 16:53:28 +00:00
|
|
|
connStop := make(chan struct{})
|
|
|
|
|
|
|
|
// Run another goroutine to copy the bytes.
|
|
|
|
go func() {
|
|
|
|
err = conn.CopyBytes()
|
|
|
|
if err != nil {
|
2020-01-28 23:50:41 +00:00
|
|
|
l.logger.Error("connection failed", "error", err)
|
2018-06-11 16:53:28 +00:00
|
|
|
}
|
|
|
|
close(connStop)
|
|
|
|
}()
|
|
|
|
|
|
|
|
// Periodically copy stats from conn to metrics (to keep metrics calls out of
|
|
|
|
// the path of every single packet copy). 5 seconds is probably good enough
|
|
|
|
// resolution - statsd and most others tend to summarize with lower resolution
|
|
|
|
// anyway and this amortizes the cost more.
|
|
|
|
var tx, rx uint64
|
|
|
|
statsT := time.NewTicker(5 * time.Second)
|
|
|
|
defer statsT.Stop()
|
|
|
|
|
|
|
|
reportStats := func() {
|
|
|
|
newTx, newRx := conn.Stats()
|
|
|
|
if delta := newTx - tx; delta > 0 {
|
|
|
|
metrics.IncrCounterWithLabels([]string{l.metricPrefix, "tx_bytes"},
|
|
|
|
float32(newTx-tx), l.metricLabels)
|
|
|
|
}
|
|
|
|
if delta := newRx - rx; delta > 0 {
|
|
|
|
metrics.IncrCounterWithLabels([]string{l.metricPrefix, "rx_bytes"},
|
|
|
|
float32(newRx-rx), l.metricLabels)
|
|
|
|
}
|
|
|
|
tx, rx = newTx, newRx
|
|
|
|
}
|
|
|
|
// Always report final stats for the conn.
|
|
|
|
defer reportStats()
|
|
|
|
|
|
|
|
// Wait for conn to close
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-connStop:
|
|
|
|
return
|
|
|
|
case <-l.stopChan:
|
|
|
|
return
|
|
|
|
case <-statsT.C:
|
|
|
|
reportStats()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// trackConn increments the count of active conns and returns a func() that can
|
|
|
|
// be deferred on to decrement the counter again on connection close.
|
|
|
|
func (l *Listener) trackConn() func() {
|
2019-01-23 15:09:01 +00:00
|
|
|
c := atomic.AddInt32(&l.activeConns, 1)
|
2018-06-11 16:53:28 +00:00
|
|
|
metrics.SetGaugeWithLabels([]string{l.metricPrefix, "conns"}, float32(c),
|
|
|
|
l.metricLabels)
|
|
|
|
|
|
|
|
return func() {
|
2019-01-23 15:09:01 +00:00
|
|
|
c := atomic.AddInt32(&l.activeConns, -1)
|
2018-06-11 16:53:28 +00:00
|
|
|
metrics.SetGaugeWithLabels([]string{l.metricPrefix, "conns"}, float32(c),
|
|
|
|
l.metricLabels)
|
2018-04-03 18:10:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close terminates the listener and all active connections.
|
|
|
|
func (l *Listener) Close() error {
|
2018-06-11 16:53:28 +00:00
|
|
|
oldFlag := atomic.SwapInt32(&l.stopFlag, 1)
|
|
|
|
if oldFlag == 0 {
|
|
|
|
close(l.stopChan)
|
|
|
|
// Wait for all conns to close
|
|
|
|
l.connWG.Wait()
|
2021-04-28 21:53:43 +00:00
|
|
|
|
|
|
|
if l.listener != nil {
|
|
|
|
l.listener.Close()
|
|
|
|
}
|
2018-06-11 16:53:28 +00:00
|
|
|
}
|
2018-04-03 18:10:59 +00:00
|
|
|
return nil
|
|
|
|
}
|
2018-04-20 21:26:00 +00:00
|
|
|
|
|
|
|
// Wait for the listener to be ready to accept connections.
|
|
|
|
func (l *Listener) Wait() {
|
|
|
|
<-l.listeningChan
|
|
|
|
}
|
2018-04-26 13:01:20 +00:00
|
|
|
|
|
|
|
// BindAddr returns the address the listen is bound to.
|
|
|
|
func (l *Listener) BindAddr() string {
|
|
|
|
return l.bindAddr
|
|
|
|
}
|