Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support TLS SNI with hostnames #186

Merged
merged 8 commits into from
Jan 20, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions cert/cert.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package cert

import (
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
)

func FromBytes(data []byte) (*x509.Certificate, error) {
cert, err := decodeCertificatePEM(data)
if err != nil {
return nil, fmt.Errorf("unable to decode certificate: %w", err)
}

return cert, nil
}

func decodeCertificatePEM(data []byte) (*x509.Certificate, error) {
const certificateBlockType = "CERTIFICATE"

var block *pem.Block
for {
block, data = pem.Decode(data)
if block == nil {
return nil, errors.New("failed to parse certificate PEM")
kylehodgetts marked this conversation as resolved.
Show resolved Hide resolved
}
// append only certificates
if block.Type == certificateBlockType {
return x509.ParseCertificate(block.Bytes)
}
if len(data) == 0 {
break
}
}
return nil, fmt.Errorf("data did not contain a valid certificate")
}
1 change: 0 additions & 1 deletion controllers/envoyfleet_resources.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,6 @@ func (e *EnvoyFleetResources) generateDeployment() {
},
},
}
return
}

func (e *EnvoyFleetResources) generateService() {
Expand Down
210 changes: 153 additions & 57 deletions envoy/config/listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@ package config

import (
"fmt"
"strings"

core "github.com/envoyproxy/go-control-plane/envoy/config/core/v3"
listener "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3"
hcm "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3"
tls "github.com/envoyproxy/go-control-plane/envoy/extensions/transport_sockets/tls/v3"
"github.com/envoyproxy/go-control-plane/pkg/wellknown"
"google.golang.org/protobuf/types/known/anypb"

"github.com/kubeshop/kusk-gateway/cert"
)

const (
Expand Down Expand Up @@ -68,44 +71,13 @@ type Certificate struct {
Key string
}

// AddHTTPManagerFilterChains inserts HTTP Manager as the listener filter chain(s)
// If certificates are present an additional TLS-enabled filter chain is added and protocol type detection is enabled with TLS Inspector Listener filter.
func (l *listenerBuilder) AddHTTPManagerFilterChains(httpConnectionManager *hcm.HttpConnectionManager, tlsConfig TLS) error {
anyHTTPManagerConfig, err := anypb.New(httpConnectionManager)
if err != nil {
return fmt.Errorf("failed to add http manager to the filter chain: cannot convert to Any message type: %w", err)
}
hcmFilter := &listener.Filter{
Name: wellknown.HTTPConnectionManager,
ConfigType: &listener.Filter_TypedConfig{TypedConfig: anyHTTPManagerConfig},
}
// Plain HTTP manager filter chain
hcmPlainChain := &listener.FilterChain{
Filters: []*listener.Filter{hcmFilter},
}
l.addListenerFilterChain(hcmPlainChain)

if len(tlsConfig.Certificates) == 0 {
return nil
}

// When certificates are present, we add an additional Listener filter chain that is selected when the connection protocol type is tls.
// HTTP Manager configuration is the same.
// Enable TLS Inspector in the Listener to detect plain http or tls requests.
l.addListenerFilter(&listener.ListenerFilter{Name: wellknown.TLSInspector})

// Make sure plain http manager filter chain is selected when protocol type is raw_buffer (not tls).
hcmPlainChain.FilterChainMatch = &listener.FilterChainMatch{TransportProtocol: "raw_buffer"}

// Secure (TLS) HTTP manager filter chain.
// Selected when the connection type is tls.
hcmSecureChain := &listener.FilterChain{
FilterChainMatch: &listener.FilterChainMatch{TransportProtocol: "tls"},
Filters: []*listener.Filter{hcmFilter},
}

tlsCerts := make([]*tls.TlsCertificate, len(tlsConfig.Certificates))
for _, cert := range tlsConfig.Certificates {
func makeHTTPSFilterChain(
certificates []Certificate,
tlsParams *tls.TlsParameters,
anyHttpConnectionManager *anypb.Any,
) (*listener.FilterChain, error) {
tlsCerts := make([]*tls.TlsCertificate, len(certificates))
for _, cert := range certificates {

tlsCert := &tls.TlsCertificate{
CertificateChain: &core.DataSource{
Expand All @@ -117,12 +89,93 @@ func (l *listenerBuilder) AddHTTPManagerFilterChains(httpConnectionManager *hcm.
}

if err := tlsCert.Validate(); err != nil {
return fmt.Errorf("invalid tls certificate: %w", err)
return nil, fmt.Errorf("invalid tls certificate: %w", err)
}

tlsCerts = append(tlsCerts, tlsCert)
}

tlsDownstreamContext := &tls.DownstreamTlsContext{
CommonTlsContext: &tls.CommonTlsContext{
TlsCertificates: tlsCerts,
TlsParams: tlsParams,
},
}

anyTls, err := anypb.New(tlsDownstreamContext)
if err != nil {
return nil, fmt.Errorf("unable to marshal TLS config to typed struct: %w", err)
}

return &listener.FilterChain{
FilterChainMatch: &listener.FilterChainMatch{TransportProtocol: "tls"},
Filters: []*listener.Filter{
{
Name: wellknown.HTTPConnectionManager,
ConfigType: &listener.Filter_TypedConfig{TypedConfig: anyHttpConnectionManager},
},
},
TransportSocket: &core.TransportSocket{
Name: wellknown.TransportSocketTLS,
ConfigType: &core.TransportSocket_TypedConfig{TypedConfig: anyTls},
},
}, nil
}

func makeHTTPSFilterChainWithHosts(
certificate Certificate,
hosts []string,
tlsParams *tls.TlsParameters,
anyHttpConnectionManager *anypb.Any,
) (*listener.FilterChain, error) {
tlsCert := &tls.TlsCertificate{
CertificateChain: &core.DataSource{
Specifier: &core.DataSource_InlineString{InlineString: certificate.Cert},
},
PrivateKey: &core.DataSource{
Specifier: &core.DataSource_InlineString{InlineString: certificate.Key},
},
}

if err := tlsCert.Validate(); err != nil {
return nil, fmt.Errorf("invalid tls certificate: %w", err)
}

tlsDownstreamContext := &tls.DownstreamTlsContext{
CommonTlsContext: &tls.CommonTlsContext{
TlsCertificates: []*tls.TlsCertificate{tlsCert},
TlsParams: tlsParams,
},
}

if err := tlsDownstreamContext.Validate(); err != nil {
return nil, fmt.Errorf("invalid tls downstream context: %w", err)
}

anyTls, err := anypb.New(tlsDownstreamContext)
if err != nil {
return nil, fmt.Errorf("unable to marshal TLS config to typed struct: %w", err)
}

return &listener.FilterChain{
FilterChainMatch: &listener.FilterChainMatch{
TransportProtocol: "tls",
ServerNames: hosts,
},
Filters: []*listener.Filter{
{
Name: wellknown.HTTPConnectionManager,
ConfigType: &listener.Filter_TypedConfig{TypedConfig: anyHttpConnectionManager},
},
},
TransportSocket: &core.TransportSocket{
Name: wellknown.TransportSocketTLS,
ConfigType: &core.TransportSocket_TypedConfig{TypedConfig: anyTls},
},
}, nil
}

func getTLSParameters(tlsConfig TLS) (*tls.TlsParameters, error) {
tlsParams := &tls.TlsParameters{}

if len(tlsConfig.CipherSuites) > 0 {
Expand All @@ -132,49 +185,92 @@ func (l *listenerBuilder) AddHTTPManagerFilterChains(httpConnectionManager *hcm.
if tlsConfig.TlsMinimumProtocolVersion != "" {
tlsProtocolValue, ok := tls.TlsParameters_TlsProtocol_value[tlsConfig.TlsMinimumProtocolVersion]
if !ok {
return fmt.Errorf("unsupported tls protocol version %s", tlsConfig.TlsMinimumProtocolVersion)
return nil, fmt.Errorf("unsupported tls protocol version %s", tlsConfig.TlsMinimumProtocolVersion)
}
tlsParams.TlsMinimumProtocolVersion = tls.TlsParameters_TlsProtocol(tlsProtocolValue)
}

if tlsConfig.TlsMaximumProtocolVersion != "" {
tlsProtocolValue, ok := tls.TlsParameters_TlsProtocol_value[tlsConfig.TlsMaximumProtocolVersion]
if !ok {
return fmt.Errorf("unsupported tls protocol version %s", tlsConfig.TlsMaximumProtocolVersion)
return nil, fmt.Errorf("unsupported tls protocol version %s", tlsConfig.TlsMaximumProtocolVersion)
}
tlsParams.TlsMinimumProtocolVersion = tls.TlsParameters_TlsProtocol(tlsProtocolValue)
}

if err := tlsParams.Validate(); err != nil {
return fmt.Errorf("invalid tls parameters: %w", err)
return nil, fmt.Errorf("invalid tls parameters: %w", err)
}

tlsDownstreamContext := &tls.DownstreamTlsContext{
CommonTlsContext: &tls.CommonTlsContext{
TlsCertificates: tlsCerts,
TlsParams: tlsParams,
},
return tlsParams, nil
}

// AddHTTPManagerFilterChains inserts HTTP Manager as the listener filter chain(s)
// If certificates are present an additional TLS-enabled filter chain is added and protocol type detection is enabled with TLS Inspector Listener filter.
func (l *listenerBuilder) AddHTTPManagerFilterChains(httpConnectionManager *hcm.HttpConnectionManager, tlsConfig TLS) error {
anyHTTPManagerConfig, err := anypb.New(httpConnectionManager)
if err != nil {
return fmt.Errorf("failed to add http manager to the filter chain: cannot convert to Any message type: %w", err)
}
hcmFilter := &listener.Filter{
Name: wellknown.HTTPConnectionManager,
ConfigType: &listener.Filter_TypedConfig{TypedConfig: anyHTTPManagerConfig},
}
// Plain HTTP manager filter chain
hcmPlainChain := &listener.FilterChain{
Filters: []*listener.Filter{hcmFilter},
}
l.addListenerFilterChain(hcmPlainChain)

if err := tlsDownstreamContext.Validate(); err != nil {
return fmt.Errorf("invalid tls downstream context: %w", err)
if len(tlsConfig.Certificates) == 0 {
return nil
}

anyTls, err := anypb.New(tlsDownstreamContext)
// When certificates are present, we add an additional Listener filter chain that is selected when the connection protocol type is tls.
// HTTP Manager configuration is the same.
// Enable TLS Inspector in the Listener to detect plain http or tls requests.
l.addListenerFilter(&listener.ListenerFilter{Name: wellknown.TLSInspector})

// Make sure plain http manager filter chain is selected when protocol type is raw_buffer (not tls).
hcmPlainChain.FilterChainMatch = &listener.FilterChainMatch{TransportProtocol: "raw_buffer"}

tlsParams, err := getTLSParameters(tlsConfig)
if err != nil {
return fmt.Errorf("unable to marshal TLS config to typed struct: %w", err)
return fmt.Errorf("unable to get TLS Parameters: %w", err)
}

hcmSecureChain.TransportSocket = &core.TransportSocket{
Name: wellknown.TransportSocketTLS,
ConfigType: &core.TransportSocket_TypedConfig{TypedConfig: anyTls},
certsWithHost := map[string]Certificate{}
certsWithNoHost := []Certificate{}

for _, tlsCert := range tlsConfig.Certificates {
c, err := cert.FromBytes([]byte(tlsCert.Cert))
if err != nil {
return fmt.Errorf("unable to get certificate: %w", err)
}

if len(c.DNSNames) > 0 {
certsWithHost[strings.Join(c.DNSNames, ",")] = tlsCert
} else {
certsWithNoHost = append(certsWithNoHost, tlsCert)
}
}

for dnsNames, certificate := range certsWithHost {
filterChain, err := makeHTTPSFilterChainWithHosts(certificate, strings.Split(dnsNames, ","), tlsParams, anyHTTPManagerConfig)
if err != nil {
return fmt.Errorf("unable to make HTTPS filter chain with hosts: %w", err)
}
l.addListenerFilterChain(filterChain)
}

if err := hcmPlainChain.Validate(); err != nil {
return fmt.Errorf("invalid secure listener chain: %w", err)
// Secure (TLS) HTTP manager filter chain.
// Selected when the connection type is tls.
filterChain, err := makeHTTPSFilterChain(certsWithNoHost, tlsParams, anyHTTPManagerConfig)
if err != nil {
return fmt.Errorf("unable to make HTTPS filter chain: %w", err)
}

l.addListenerFilterChain(hcmSecureChain)
l.addListenerFilterChain(filterChain)

return nil
}
Expand Down