Files

9.0 KiB

transport

import "github.com/effective-security/porto/pkg/transport"

Package transport provides net.Listener wrappers for servers: a TLS listener that performs the handshake eagerly with optional CRL checking, and keepalive listeners that enable TCP keepalive on accepted connections.

TLSInfo holds the file-based TLS settings for a server and builds a tls.Config whose certificate is rotated by a tlsconfig.KeypairReloader (polling every 5 minutes). A failed build caches nothing, so it can be retried. Client certificates are checked only by ClientAuthType and the optional CRLVerifier; for any other policy, set VerifyConnection on the config returned by ServerTLSWithReloader before serving (again after Close, which drops the config).

Usage:

ln, err := net.Listen("tcp", ":8443")
if err != nil {
	return err
}
info := &transport.TLSInfo{
	CertFile:       "server.pem",
	KeyFile:        "server-key.pem",
	TrustedCAFile:  "ca.pem",
	ClientAuthType: tls.VerifyClientCertIfGiven,
	CRLVerifier:    verifier, // optional crlcache.Verifier
}
defer info.Close()

tlsLn, err := transport.NewTLSListener(ln, info) // handshakes in the background
if err != nil {
	_ = ln.Close() // left open when the TLS config fails to load
	return err
}
srv := &http.Server{Handler: h, TLSConfig: info.Config()}
return srv.Serve(tlsLn)

NewKeepAliveListener wraps a listener so accepted TCP connections get keepalive probes after 30s idle, 15s apart, up to 9; with scheme "https" it also wraps connections with tls.Server (lazy handshake) using the supplied tls.Config.

Both listeners return Accept errors of the wrapped listener to the caller unchanged, so servers such as net/http, grpc and cmux retry temporary errors (for example EMFILE). The TLS listener keeps accepting after an error and stops when the wrapped listener returns net.ErrClosed or when it is closed itself; always Close it.

Index

func NewKeepAliveListener

func NewKeepAliveListener(l net.Listener, scheme string, tlscfg *tls.Config) (net.Listener, error)

NewKeepAliveListener wraps l so that accepted connections get TCP keepalive: 30s idle, then up to 9 probes 15s apart. With scheme "https" the connection is also wrapped with tls.Server(tlscfg) (handshake happens lazily on first I/O) and tlscfg must be non-nil, otherwise an error is returned. Connections without SetKeepAliveConfig (*net.TCPConn has it; Unix sockets do not) are returned without keepalive; a failure to set the socket options is logged and the connection is still returned, as net.TCPListener does for its default keepalive. Accept errors of l are returned unchanged, so callers such as net/http, grpc and cmux can still retry temporary errors. Be careful when wrapping the returned listener with another listener: packages like net/http expect Accept to return *tls.Conn.

func NewTLSListener

func NewTLSListener(l net.Listener, tlsinfo *TLSInfo) (net.Listener, error)

NewTLSListener wraps l so that every accepted connection is TLS-handshaked in its own goroutine before Accept returns it; connections that fail the handshake or the CRL check (when tlsinfo.CRLVerifier is set) are closed and reported to tlsinfo.HandshakeFailure. It calls tlsinfo.ServerTLSWithReloader, so the tls.Config is available afterwards via tlsinfo.Config(). If tlsinfo is nil or Empty, l is closed and an error returned; if ServerTLSWithReloader fails, its error is returned and l is left open. The caller must Close the returned listener; Close blocks until the accept loop and pending handshakes finish. HandshakeTimeout defaults to 10s; a negative value disables it. The deadline is cleared before a successful connection is returned.

An Accept error of l other than net.ErrClosed does not stop the listener: it is returned unchanged by the next Accept call, so the caller decides whether to retry (net/http and grpc back off on temporary errors such as EMFILE), and accepting continues after it. A wrapped listener that reports its closure with another error, such as a cmux listener, keeps the accept loop running until Close; net/http and grpc close the listener when such an error stops them.

type TLSInfo

TLSInfo is the file-based TLS configuration of a server listener. ServerTLSWithReloader builds and caches the tls.Config; Close releases the reloader. It is not safe for concurrent use while being initialized.

Client certificate policy beyond ClientAuthType and CRLVerifier (for example a required subject) is not configured here: call ServerTLSWithReloader first and set VerifyConnection on the returned config before the listener serves. Close drops the config, so a later ServerTLSWithReloader call returns a new one without it.

type TLSInfo struct {
    // CertFile and KeyFile are the PEM server certificate chain and key; required.
    CertFile string
    KeyFile  string
    // ClientCAFile is a PEM bundle used to verify client certificates.
    // When empty, TrustedCAFile is used for that purpose as well.
    ClientCAFile string
    // TrustedCAFile is a PEM bundle used as RootCAs (and ClientCAs when
    // ClientCAFile is empty). When empty, OS roots are used.
    TrustedCAFile string
    // ClientAuthType is passed to tls.Config.ClientAuth (default NoClientCert).
    ClientAuthType tls.ClientAuthType
    // CRLVerifier, when set, is consulted by NewTLSListener for every
    // certificate in the client's verified chains; a Revoked status rejects
    // the connection, errors and Unknown are logged and allowed.
    CRLVerifier crlcache.Verifier

    // HandshakeFailure is optionally called when a connection fails to handshake. The
    // connection will be closed immediately afterwards.
    HandshakeFailure func(*tls.Conn, error)

    // HandshakeTimeout bounds each eager TLS handshake. Zero uses
    // limits.DefaultHandshakeTimeout; a negative duration disables the deadline.
    HandshakeTimeout time.Duration

    // CipherSuites optionally restricts the enabled TLS 1.2 cipher suites, by
    // crypto/tls name; if empty, Go uses its default list. The order is
    // ignored: Go picks the preferred mutually supported suite itself.
    // tlsconfig.UpdateCipherSuites rejects insecure and TLS 1.3 names.
    CipherSuites []string
    // contains filtered or unexported fields
}

func (*TLSInfo) Close

func (info *TLSInfo) Close()

Close stops the certificate reloader and drops the cached tls.Config. It is safe to call when ServerTLSWithReloader was never called.

func (*TLSInfo) Config

func (info *TLSInfo) Config() *tls.Config

Config returns the tls.Config built by ServerTLSWithReloader, or nil if it has not been called (or after Close).

func (*TLSInfo) Empty

func (info *TLSInfo) Empty() bool

Empty reports whether CertFile or KeyFile is missing, i.e. TLS cannot be served.

func (*TLSInfo) ServerTLSWithReloader

func (info *TLSInfo) ServerTLSWithReloader() (*tls.Config, error)

ServerTLSWithReloader builds (once) and returns the server tls.Config from the files, applies CipherSuites, and installs a KeypairReloader polling every 5 minutes as GetCertificate. It returns an error if the certificate has already expired. Subsequent calls return the cached config. A call that fails caches nothing, so a later call loads the files again.

func (*TLSInfo) String

func (info *TLSInfo) String() string

String returns a one-line summary of the file paths and client auth mode.

Generated by gomarkdoc