...
 
Commits (5)
......@@ -391,6 +391,12 @@ func groupSiteConfigsByListenAddr(configs []*SiteConfig) (map[string][]*SiteConf
// parts of an address. The component parts may be
// updated to the correct values as setup proceeds,
// but the original value should never be changed.
//
// Important: In order for the fix for #2356 to work,
// if Host is an IP address, it must be in a
// normalized form (as presented by net.IP.String()).
// For SNI matching in general, it needs to be
// lowercase.
type Address struct {
Original, Scheme, Host, Port, Path string
}
......@@ -439,10 +445,17 @@ func (a Address) Normalize() Address {
if !CaseSensitivePath {
path = strings.ToLower(path)
}
host := a.Host
if ip := net.ParseIP(host); ip != nil {
// Ensure that it's in a normalized form if it's an IP address.
host = ip.String()
}
return Address{
Original: a.Original,
Scheme: strings.ToLower(a.Scheme),
Host: strings.ToLower(a.Host),
Host: strings.ToLower(host),
Port: a.Port,
Path: path,
}
......
......@@ -92,8 +92,10 @@ type UpstreamHost struct {
// This is an int32 so that we can use atomic operations to do concurrent
// reads & writes to this value. The default value of 0 indicates that it
// is healthy and any non-zero value indicates unhealthy.
Unhealthy int32
HealthCheckResult atomic.Value
Unhealthy int32
HealthCheckResult atomic.Value
UpstreamHeaderReplacements headerReplacements
DownstreamHeaderReplacements headerReplacements
}
// Down checks whether the upstream host is down or not.
......@@ -220,7 +222,7 @@ func (p Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
// set headers for request going upstream
if host.UpstreamHeaders != nil {
// modify headers for request that will be sent to the upstream host
mutateHeadersByRules(outreq.Header, host.UpstreamHeaders, replacer)
mutateHeadersByRules(outreq.Header, host.UpstreamHeaders, replacer, host.UpstreamHeaderReplacements)
if hostHeaders, ok := outreq.Header["Host"]; ok && len(hostHeaders) > 0 {
outreq.Host = hostHeaders[len(hostHeaders)-1]
}
......@@ -230,7 +232,7 @@ func (p Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
// headers coming back downstream
var downHeaderUpdateFn respUpdateFn
if host.DownstreamHeaders != nil {
downHeaderUpdateFn = createRespHeaderUpdateFn(host.DownstreamHeaders, replacer)
downHeaderUpdateFn = createRespHeaderUpdateFn(host.DownstreamHeaders, replacer, host.DownstreamHeaderReplacements)
}
// Before we retry the request we have to make sure
......@@ -372,13 +374,13 @@ func createUpstreamRequest(rw http.ResponseWriter, r *http.Request) (*http.Reque
return outreq, cancel
}
func createRespHeaderUpdateFn(rules http.Header, replacer httpserver.Replacer) respUpdateFn {
func createRespHeaderUpdateFn(rules http.Header, replacer httpserver.Replacer, replacements headerReplacements) respUpdateFn {
return func(resp *http.Response) {
mutateHeadersByRules(resp.Header, rules, replacer)
mutateHeadersByRules(resp.Header, rules, replacer, replacements)
}
}
func mutateHeadersByRules(headers, rules http.Header, repl httpserver.Replacer) {
func mutateHeadersByRules(headers, rules http.Header, repl httpserver.Replacer, replacements headerReplacements) {
for ruleField, ruleValues := range rules {
if strings.HasPrefix(ruleField, "+") {
for _, ruleValue := range ruleValues {
......@@ -396,4 +398,17 @@ func mutateHeadersByRules(headers, rules http.Header, repl httpserver.Replacer)
}
}
}
for ruleField, ruleValues := range replacements {
for _, ruleValue := range ruleValues {
// Replace variables in replacement string
replacement := repl.Replace(ruleValue.to)
original := headers.Get(ruleField)
if len(replacement) > 0 && len(original) > 0 {
// Replace matches in original string with replacement string
replaced := ruleValue.regexp.ReplaceAllString(original, replacement)
headers.Set(ruleField, replaced)
}
}
}
}
......@@ -31,6 +31,7 @@ import (
"path"
"path/filepath"
"reflect"
"regexp"
"runtime"
"strings"
"sync"
......@@ -724,6 +725,14 @@ func TestUpstreamHeadersUpdate(t *testing.T) {
"Clear-Me": {""},
"Host": {"{>Host}"},
}
regex1, _ := regexp.Compile("was originally")
regex2, _ := regexp.Compile("this")
regex3, _ := regexp.Compile("bad")
upstream.host.UpstreamHeaderReplacements = headerReplacements{
"Regex-Me": {headerReplacement{regex1, "am now"}, headerReplacement{regex2, "that"}},
"Regexreplace-Me": {headerReplacement{regex3, "{hostname}"}},
}
// set up proxy
p := &Proxy{
Next: httpserver.EmptyNext, // prevents panic in some cases when test fails
......@@ -740,18 +749,22 @@ func TestUpstreamHeadersUpdate(t *testing.T) {
r.Header.Add("Remove-Me", "Remove-Value")
r.Header.Add("Replace-Me", "Replace-Value")
r.Header.Add("Host", expectHost)
r.Header.Add("Regex-Me", "I was originally this")
r.Header.Add("Regexreplace-Me", "The host is bad")
p.ServeHTTP(w, r)
replacer := httpserver.NewReplacer(r, nil, "")
for headerKey, expect := range map[string][]string{
"Merge-Me": {"Initial", "Merge-Value"},
"Add-Me": {"Add-Value"},
"Add-Empty": nil,
"Remove-Me": nil,
"Replace-Me": {replacer.Replace("{hostname}")},
"Clear-Me": nil,
"Merge-Me": {"Initial", "Merge-Value"},
"Add-Me": {"Add-Value"},
"Add-Empty": nil,
"Remove-Me": nil,
"Replace-Me": {replacer.Replace("{hostname}")},
"Clear-Me": nil,
"Regex-Me": {"I am now that"},
"Regexreplace-Me": {"The host is " + replacer.Replace("{hostname}")},
} {
if got := actualHeaders[headerKey]; !reflect.DeepEqual(got, expect) {
t.Errorf("Upstream request does not contain expected %v header: expect %v, but got %v",
......@@ -775,6 +788,8 @@ func TestDownstreamHeadersUpdate(t *testing.T) {
w.Header().Add("Replace-Me", "Replace-Value")
w.Header().Add("Content-Type", "text/html")
w.Header().Add("Overwrite-Me", "Overwrite-Value")
w.Header().Add("Regex-Me", "I was originally this")
w.Header().Add("Regexreplace-Me", "The host is bad")
w.Write([]byte("Hello, client"))
}))
defer backend.Close()
......@@ -786,6 +801,13 @@ func TestDownstreamHeadersUpdate(t *testing.T) {
"-Remove-Me": {""},
"Replace-Me": {"{hostname}"},
}
regex1, _ := regexp.Compile("was originally")
regex2, _ := regexp.Compile("this")
regex3, _ := regexp.Compile("bad")
upstream.host.DownstreamHeaderReplacements = headerReplacements{
"Regex-Me": {headerReplacement{regex1, "am now"}, headerReplacement{regex2, "that"}},
"Regexreplace-Me": {headerReplacement{regex3, "{hostname}"}},
}
// set up proxy
p := &Proxy{
Next: httpserver.EmptyNext, // prevents panic in some cases when test fails
......@@ -806,12 +828,14 @@ func TestDownstreamHeadersUpdate(t *testing.T) {
actualHeaders := w.Header()
for headerKey, expect := range map[string][]string{
"Merge-Me": {"Initial", "Merge-Value"},
"Add-Me": {"Add-Value"},
"Remove-Me": nil,
"Replace-Me": {replacer.Replace("{hostname}")},
"Content-Type": {"text/css"},
"Overwrite-Me": {"Overwrite-Value"},
"Merge-Me": {"Initial", "Merge-Value"},
"Add-Me": {"Add-Value"},
"Remove-Me": nil,
"Replace-Me": {replacer.Replace("{hostname}")},
"Content-Type": {"text/css"},
"Overwrite-Me": {"Overwrite-Value"},
"Regex-Me": {"I am now that"},
"Regexreplace-Me": {"The host is " + replacer.Replace("{hostname}")},
} {
if got := actualHeaders[headerKey]; !reflect.DeepEqual(got, expect) {
t.Errorf("Downstream response does not contain expected %s header: expect %v, but got %v",
......
......@@ -28,6 +28,7 @@ package proxy
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"net"
......@@ -310,6 +311,25 @@ func (rp *ReverseProxy) UseInsecureTransport() {
}
}
// UseOwnCertificate is used to facilitate HTTPS proxying
// with locally provided certificate.
func (rp *ReverseProxy) UseOwnCACertificates(CaCertPool *x509.CertPool) {
if transport, ok := rp.Transport.(*http.Transport); ok {
if transport.TLSClientConfig == nil {
transport.TLSClientConfig = &tls.Config{}
}
transport.TLSClientConfig.RootCAs = CaCertPool
// No http2.ConfigureTransport() here.
// For now this is only added in places where
// an http.Transport is actually created.
} else if transport, ok := rp.Transport.(*h2quic.RoundTripper); ok {
if transport.TLSClientConfig == nil {
transport.TLSClientConfig = &tls.Config{}
}
transport.TLSClientConfig.RootCAs = CaCertPool
}
}
// ServeHTTP serves the proxied request to the upstream by performing a roundtrip.
// It is designed to handle websocket connection upgrades as well.
func (rp *ReverseProxy) ServeHTTP(rw http.ResponseWriter, outreq *http.Request, respUpdateFn respUpdateFn) error {
......
......@@ -17,13 +17,16 @@ package proxy
import (
"bytes"
"context"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/textproto"
"net/url"
"path"
"regexp"
"strconv"
"strings"
"sync"
......@@ -64,17 +67,39 @@ type staticUpstream struct {
Port string
ContentString string
}
WithoutPathPrefix string
IgnoredSubPaths []string
insecureSkipVerify bool
MaxFails int32
resolver srvResolver
WithoutPathPrefix string
IgnoredSubPaths []string
insecureSkipVerify bool
MaxFails int32
resolver srvResolver
upstreamHeaderReplacements headerReplacements
downstreamHeaderReplacements headerReplacements
CaCertPool *x509.CertPool
}
type srvResolver interface {
LookupSRV(context.Context, string, string, string) (string, []*net.SRV, error)
}
// headerReplacement stores a compiled regex matcher and a string replacer, for replacement rules
type headerReplacement struct {
regexp *regexp.Regexp
to string
}
// headerReplacements stores a mapping of canonical MIME header to headerReplacement
// Implements a subset of http.Header functions, to allow convenient addition and deletion of rules
type headerReplacements map[string][]headerReplacement
func (h headerReplacements) Add(key string, value headerReplacement) {
key = textproto.CanonicalMIMEHeaderKey(key)
h[key] = append(h[key], value)
}
func (h headerReplacements) Del(key string) {
delete(h, textproto.CanonicalMIMEHeaderKey(key))
}
// NewStaticUpstreams parses the configuration input and sets up
// static upstreams for the proxy middleware. The host string parameter,
// if not empty, is used for setting the upstream Host header for the
......@@ -84,18 +109,20 @@ func NewStaticUpstreams(c caddyfile.Dispenser, host string) ([]Upstream, error)
for c.Next() {
upstream := &staticUpstream{
from: "",
stop: make(chan struct{}),
upstreamHeaders: make(http.Header),
downstreamHeaders: make(http.Header),
Hosts: nil,
Policy: &Random{},
MaxFails: 1,
TryInterval: 250 * time.Millisecond,
MaxConns: 0,
KeepAlive: http.DefaultMaxIdleConnsPerHost,
Timeout: 30 * time.Second,
resolver: net.DefaultResolver,
from: "",
stop: make(chan struct{}),
upstreamHeaders: make(http.Header),
downstreamHeaders: make(http.Header),
Hosts: nil,
Policy: &Random{},
MaxFails: 1,
TryInterval: 250 * time.Millisecond,
MaxConns: 0,
KeepAlive: http.DefaultMaxIdleConnsPerHost,
Timeout: 30 * time.Second,
resolver: net.DefaultResolver,
upstreamHeaderReplacements: make(headerReplacements),
downstreamHeaderReplacements: make(headerReplacements),
}
if !c.Args(&upstream.from) {
......@@ -218,9 +245,11 @@ func (u *staticUpstream) NewHost(host string) (*UpstreamHost, error) {
return false
}
}(u),
WithoutPathPrefix: u.WithoutPathPrefix,
MaxConns: u.MaxConns,
HealthCheckResult: atomic.Value{},
WithoutPathPrefix: u.WithoutPathPrefix,
MaxConns: u.MaxConns,
HealthCheckResult: atomic.Value{},
UpstreamHeaderReplacements: u.upstreamHeaderReplacements,
DownstreamHeaderReplacements: u.downstreamHeaderReplacements,
}
baseURL, err := url.Parse(uh.Name)
......@@ -232,6 +261,9 @@ func (u *staticUpstream) NewHost(host string) (*UpstreamHost, error) {
if u.insecureSkipVerify {
uh.ReverseProxy.UseInsecureTransport()
}
if u.CaCertPool != nil {
uh.ReverseProxy.UseOwnCACertificates(u.CaCertPool)
}
return uh, nil
}
......@@ -425,23 +457,47 @@ func parseBlock(c *caddyfile.Dispenser, u *staticUpstream, hasSrv bool) error {
}
u.HealthCheck.ContentString = c.Val()
case "header_upstream":
var header, value string
if !c.Args(&header, &value) {
// When removing a header, the value can be optional.
if !strings.HasPrefix(header, "-") {
var header, value, replaced string
if c.Args(&header, &value, &replaced) {
// Don't allow - or + in replacements
if strings.HasPrefix(header, "-") || strings.HasPrefix(header, "+") {
return c.ArgErr()
}
r, err := regexp.Compile(value)
if err != nil {
return c.ArgErr()
}
u.upstreamHeaderReplacements.Add(header, headerReplacement{r, replaced})
} else {
if len(value) == 0 {
// When removing a header, the value can be optional.
if !strings.HasPrefix(header, "-") {
return c.ArgErr()
}
}
u.upstreamHeaders.Add(header, value)
}
u.upstreamHeaders.Add(header, value)
case "header_downstream":
var header, value string
if !c.Args(&header, &value) {
// When removing a header, the value can be optional.
if !strings.HasPrefix(header, "-") {
var header, value, replaced string
if c.Args(&header, &value, &replaced) {
// Don't allow - or + in replacements
if strings.HasPrefix(header, "-") || strings.HasPrefix(header, "+") {
return c.ArgErr()
}
r, err := regexp.Compile(value)
if err != nil {
return c.ArgErr()
}
u.downstreamHeaderReplacements.Add(header, headerReplacement{r, replaced})
} else {
if len(value) == 0 {
// When removing a header, the value can be optional.
if !strings.HasPrefix(header, "-") {
return c.ArgErr()
}
}
u.downstreamHeaders.Add(header, value)
}
u.downstreamHeaders.Add(header, value)
case "transparent":
// Note: X-Forwarded-For header is always being appended for proxy connections
// See implementation of createUpstreamRequest in proxy.go
......@@ -464,6 +520,32 @@ func parseBlock(c *caddyfile.Dispenser, u *staticUpstream, hasSrv bool) error {
u.IgnoredSubPaths = ignoredPaths
case "insecure_skip_verify":
u.insecureSkipVerify = true
case "ca_certificates":
caCertificates := c.RemainingArgs()
if len(caCertificates) == 0 {
return c.ArgErr()
}
pool := x509.NewCertPool()
caCertificatesAdded := make(map[string]struct{})
for _, caFile := range caCertificates {
// don't add cert to pool more than once
if _, ok := caCertificatesAdded[caFile]; ok {
continue
}
caCertificatesAdded[caFile] = struct{}{}
// Any client with a certificate from this CA will be allowed to connect
caCrt, err := ioutil.ReadFile(caFile)
if err != nil {
return err
}
if !pool.AppendCertsFromPEM(caCrt) {
return fmt.Errorf("error loading CA certificate '%s': no certificates were successfully parsed", caFile)
}
}
u.CaCertPool = pool
case "keepalive":
if !c.NextArg() {
return c.ArgErr()
......
......@@ -325,6 +325,61 @@ func TestParseBlockTransparent(t *testing.T) {
}
}
func TestParseBlockRegex(t *testing.T) {
// tests for regex replacement of headers
r, _ := http.NewRequest("GET", "/", nil)
tests := []struct {
config string
}{
// Test #1: transparent preset with replacement of Host
{"proxy / localhost:8080 {\n transparent \nheader_upstream Host (.*) NewHost \n}"},
// Test #2: transparent preset with replacement of another param
{"proxy / localhost:8080 {\n transparent \nheader_upstream X-Test Tester \nheader_upstream X-Test Test Host \n}"},
// Test #3: transparent preset with multiple params
{"proxy / localhost:8080 {\n transparent \nheader_upstream X-Test Tester \nheader_upstream X-Test Test Host \nheader_upstream X-Test er ing \n}"},
}
for i, test := range tests {
upstreams, err := NewStaticUpstreams(caddyfile.NewDispenser("Testfile", strings.NewReader(test.config)), "")
if err != nil {
t.Errorf("Expected no error. Got: %s", err.Error())
}
for _, upstream := range upstreams {
headers := upstream.Select(r).UpstreamHeaderReplacements
switch i {
case 0:
if host, ok := headers["Host"]; !ok || host[0].to != "NewHost" {
t.Errorf("Test %d: Incorrect Host replacement: %v", i+1, host[0])
}
case 1:
if v, ok := headers["X-Test"]; !ok {
t.Errorf("Test %d: Incorrect X-Test replacement", i+1)
} else {
if v[0].to != "Host" {
t.Errorf("Test %d: Incorrect X-Test replacement: %v", i+1, v[0])
}
}
case 2:
if v, ok := headers["X-Test"]; !ok {
t.Errorf("Test %d: Incorrect X-Test replacement", i+1)
} else {
if v[0].to != "Host" {
t.Errorf("Test %d: Incorrect X-Test replacement: %v", i+1, v[0])
}
if v[1].to != "ing" {
t.Errorf("Test %d: Incorrect X-Test replacement: %v", i+1, v[1])
}
}
default:
t.Error("Testing error")
}
}
}
}
func TestHealthSetUp(t *testing.T) {
// tests for insecure skip verify
tests := []struct {
......
......@@ -35,6 +35,12 @@ type Config struct {
// designated for; can contain wildcard characters
// according to RFC 6125 §6.4.3 - this field MUST
// be set in order for things to work as expected
//
// Important: In order for the fix for #2356 to work,
// if Host is an IP address, it must be in a
// normalized form (as presented by net.IP.String()).
// For SNI matching in general, it needs to be
// lowercase.
Hostname string
// Whether TLS is enabled
......
......@@ -19,6 +19,7 @@ import (
"errors"
"fmt"
"log"
"net"
"net/http"
"net/url"
"strings"
......@@ -34,18 +35,28 @@ import (
// method to get a config by matching its hostname).
type configGroup map[string]*Config
// getConfig gets the config by the first key match for name.
// In other words, "sub.foo.bar" will get the config for "*.foo.bar"
// if that is the closest match. If no match is found, the first
// (random) config will be loaded, which will defer any TLS alerts
// to the certificate validation (this may or may not be ideal;
// let's talk about it if this becomes problematic).
//
// This function follows nearly the same logic to lookup
// a hostname as the getCertificate function uses.
func (cg configGroup) getConfig(name string) *Config {
func certificateIDFromHello(clientHello *tls.ClientHelloInfo) (name string) {
name = strings.TrimSpace(clientHello.ServerName)
// Per #2356, if lacking SNI, attempt to find certificate
// that matches local IP address.
if name == "" {
addr := clientHello.Conn.LocalAddr()
if s, ok := addr.(*net.TCPAddr); ok {
name = s.IP.String()
} else if s, ok := addr.(*net.UDPAddr); ok {
name = s.IP.String()
} else if s, ok := addr.(*net.IPAddr); ok {
name = s.IP.String()
}
}
// IP addresses should be lowercased, too
name = strings.ToLower(name)
return
}
func (cg configGroup) getConfig(name string) *Config {
// exact match? great, let's use it
if config, ok := cg[name]; ok {
return config
......@@ -79,8 +90,8 @@ func (cg configGroup) getConfig(name string) *Config {
//
// This method is safe for use as a tls.Config.GetConfigForClient callback.
func (cg configGroup) GetConfigForClient(clientHello *tls.ClientHelloInfo) (*tls.Config, error) {
config := cg.getConfig(clientHello.ServerName)
if config != nil {
name := certificateIDFromHello(clientHello)
if config := cg.getConfig(name); config != nil {
return config.tlsConfig, nil
}
return nil, nil
......@@ -112,7 +123,8 @@ func (cfg *Config) GetCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certif
}
// get the certificate and serve it up
cert, err := cfg.getCertDuringHandshake(strings.ToLower(clientHello.ServerName), true, true)
name := certificateIDFromHello(clientHello)
cert, err := cfg.getCertDuringHandshake(name, true, true)
if err == nil {
go telemetry.Increment("tls_handshake_count") // TODO: This is a "best guess" for now, we need something listener-level
}
......
......@@ -17,17 +17,61 @@ package caddytls
import (
"crypto/tls"
"crypto/x509"
"errors"
"net"
"testing"
"time"
)
// Mock net.Conn. Only job is to expose a local IP address.
type mockConn struct {
Addr net.Addr
}
func (conn mockConn) Read(b []byte) (n int, err error) {
return -1, errors.New("not implemented")
}
func (conn mockConn) Write(b []byte) (n int, err error) {
return -1, errors.New("not implemented")
}
func (conn mockConn) Close() error {
return errors.New("not implemented")
}
func (conn mockConn) LocalAddr() net.Addr {
return conn.Addr
}
func (conn mockConn) RemoteAddr() net.Addr {
return nil
}
func (conn mockConn) SetDeadline(t time.Time) error {
return errors.New("not implemented")
}
func (conn mockConn) SetReadDeadline(t time.Time) error {
return errors.New("not implemented")
}
func (conn mockConn) SetWriteDeadline(t time.Time) error {
return errors.New("not implemented")
}
func TestGetCertificate(t *testing.T) {
certCache := &certificateCache{cache: make(map[string]Certificate)}
cfg := &Config{Certificates: make(map[string]string), certCache: certCache}
hello := &tls.ClientHelloInfo{ServerName: "example.com"}
helloSub := &tls.ClientHelloInfo{ServerName: "sub.example.com"}
helloNoSNI := &tls.ClientHelloInfo{}
helloNoMatch := &tls.ClientHelloInfo{ServerName: "nomatch"} // TODO (see below)
var conn1 net.Conn = &mockConn{Addr: &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 60001, Zone: ""}}
var conn2 net.Conn = &mockConn{Addr: &net.TCPAddr{IP: net.ParseIP("127.0.0.2"), Port: 60001, Zone: ""}}
hello := &tls.ClientHelloInfo{Conn: conn1, ServerName: "example.com"}
helloSub := &tls.ClientHelloInfo{Conn: conn1, ServerName: "sub.example.com"}
helloNoSNI := &tls.ClientHelloInfo{Conn: conn1}
helloNoSNIFallback := &tls.ClientHelloInfo{Conn: conn2}
helloNoMatch := &tls.ClientHelloInfo{Conn: conn1, ServerName: "nomatch"} // TODO (see below)
// When cache is empty
if cert, err := cfg.GetCertificate(hello); err == nil {
......@@ -45,8 +89,8 @@ func TestGetCertificate(t *testing.T) {
} else if cert.Leaf.DNSNames[0] != "example.com" {
t.Errorf("Got wrong certificate with exact match; expected 'example.com', got: %v", cert)
}
if _, err := cfg.GetCertificate(helloNoSNI); err != nil {
t.Errorf("Got an error with no SNI but shouldn't have, when cert exists in cache: %v", err)
if _, err := cfg.GetCertificate(helloNoSNI); err == nil {
t.Error("Expected error with no SNI and single cert in cache")
}
// When retrieving wildcard certificate
......@@ -63,14 +107,30 @@ func TestGetCertificate(t *testing.T) {
}
// When cache is NOT empty but there's no SNI
if cert, err := cfg.GetCertificate(helloNoSNI); err != nil {
t.Errorf("Expected random certificate with no error when no SNI, got err: %v", err)
} else if cert == nil || len(cert.Leaf.DNSNames) == 0 {
t.Errorf("Expected random cert with no matches, got: %v", cert)
if _, err := cfg.GetCertificate(helloNoSNI); err == nil {
t.Error("Expected error with no SNI multiple certs in cache")
}
// When no certificate matches, raise an alert
if _, err := cfg.GetCertificate(helloNoMatch); err == nil {
t.Errorf("Expected an error when no certificate matched the SNI, got: %v", err)
t.Error("Expected an error when no certificate matched the SNI")
}
// When no SNI, find a certificate with a matching IP address
ipCert := Certificate{
Names: []string{"127.0.0.1"},
Certificate: tls.Certificate{Leaf: &x509.Certificate{IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}}},
Hash: "127.0.0.1",
}
cfg.cacheCertificate(ipCert)
if cert, err := cfg.GetCertificate(helloNoSNI); err != nil {
t.Errorf("Got an error but shouldn't have, when no SNI and cert for IP address exists in cache: %v", err)
} else if cert == nil || len(cert.Leaf.IPAddresses) == 0 || !cert.Leaf.IPAddresses[0].Equal(net.ParseIP("127.0.0.1")) {
t.Errorf("Got wrong cert when no SNI and cert for IP address exists in cache: %v", err)
}
// Raise an alert when no SNI and no matching IP address.
if _, err := cfg.GetCertificate(helloNoSNIFallback); err == nil {
t.Error("Expected an error when no certificate matched the IP address with no SNI")
}
}