diff --git a/cmd/derper/depaware.txt b/cmd/derper/depaware.txt index 5fa3d6e72..41299c5cf 100644 --- a/cmd/derper/depaware.txt +++ b/cmd/derper/depaware.txt @@ -95,7 +95,7 @@ tailscale.com/cmd/derper dependencies: (generated by github.com/tailscale/depawa tailscale.com/ipn/ipnstate from tailscale.com/client/local+ tailscale.com/kube/kubetypes from tailscale.com/envknob tailscale.com/metrics from tailscale.com/cmd/derper+ - tailscale.com/net/bakedroots from tailscale.com/net/tlsdial + tailscale.com/net/bakedroots from tailscale.com/net/tlsdial+ tailscale.com/net/connectproxy from tailscale.com/cmd/derper tailscale.com/net/dnscache from tailscale.com/derp/derphttp tailscale.com/net/ktimeout from tailscale.com/cmd/derper diff --git a/cmd/tailscale/depaware.txt b/cmd/tailscale/depaware.txt index 21eb8396b..d6c816f27 100644 --- a/cmd/tailscale/depaware.txt +++ b/cmd/tailscale/depaware.txt @@ -226,7 +226,7 @@ tailscale.com/cmd/tailscale dependencies: (generated by github.com/tailscale/dep tailscale.com/licenses from tailscale.com/client/web+ tailscale.com/metrics from tailscale.com/tsweb+ tailscale.com/net/ace from tailscale.com/cmd/tailscale/cli - tailscale.com/net/bakedroots from tailscale.com/net/tlsdial + tailscale.com/net/bakedroots from tailscale.com/net/tlsdial+ tailscale.com/net/captivedetection from tailscale.com/feature/captiveportal/netcheckhook tailscale.com/net/dnscache from tailscale.com/control/controlhttp+ tailscale.com/net/dnsfallback from tailscale.com/control/controlhttp+ diff --git a/cmd/tailscaled/depaware-min.txt b/cmd/tailscaled/depaware-min.txt index e2b05de32..7c1f2637b 100644 --- a/cmd/tailscaled/depaware-min.txt +++ b/cmd/tailscaled/depaware-min.txt @@ -83,7 +83,7 @@ tailscale.com/cmd/tailscaled dependencies: (generated by github.com/tailscale/de tailscale.com/logpolicy from tailscale.com/cmd/tailscaled+ tailscale.com/logtail from tailscale.com/cmd/tailscaled+ tailscale.com/logtail/filch from tailscale.com/log/sockstatlog+ - tailscale.com/net/bakedroots from tailscale.com/net/tlsdial + tailscale.com/net/bakedroots from tailscale.com/net/tlsdial+ 💣 tailscale.com/net/batching from tailscale.com/wgengine/magicsock tailscale.com/net/dns from tailscale.com/cmd/tailscaled+ tailscale.com/net/dns/publicdns from tailscale.com/net/dns+ diff --git a/cmd/tailscaled/depaware-minbox.txt b/cmd/tailscaled/depaware-minbox.txt index 7d819c987..68d281fd5 100644 --- a/cmd/tailscaled/depaware-minbox.txt +++ b/cmd/tailscaled/depaware-minbox.txt @@ -100,7 +100,7 @@ tailscale.com/cmd/tailscaled dependencies: (generated by github.com/tailscale/de tailscale.com/logtail from tailscale.com/cmd/tailscaled+ tailscale.com/logtail/filch from tailscale.com/log/sockstatlog+ tailscale.com/net/ace from tailscale.com/cmd/tailscale/cli - tailscale.com/net/bakedroots from tailscale.com/net/tlsdial + tailscale.com/net/bakedroots from tailscale.com/net/tlsdial+ 💣 tailscale.com/net/batching from tailscale.com/wgengine/magicsock tailscale.com/net/dns from tailscale.com/cmd/tailscaled+ tailscale.com/net/dns/publicdns from tailscale.com/net/dns+ diff --git a/feature/dnsresolvecache/dnsresolvecache.go b/feature/dnsresolvecache/dnsresolvecache.go index c7295a45a..65d36ec9f 100644 --- a/feature/dnsresolvecache/dnsresolvecache.go +++ b/feature/dnsresolvecache/dnsresolvecache.go @@ -8,6 +8,22 @@ // plane. It is intended to eventually replace the DERP-based // bootstrap DNS in net/dnsfallback. // +// To keep bogus answers (say, from a captive portal's DNS server) off +// disk, a resolution is not written when it happens. It is instead +// held in memory as pending until a TLS connection to one of the +// resolution's IPs presents a certificate chain that is valid for +// that hostname; only then is the record flushed to disk. The chain +// is checked independently of the connection's own TLS configuration, +// which for the control plane's Noise connection deliberately +// tolerates interception. A captive portal cannot present a valid +// certificate for a hostname it is impersonating, so its answers are +// never persisted. That is also the +// invalidation contract: a hostname's file is only ever written or +// replaced by a newer resolution that was itself verified this way; +// there is no expiry. Verification currently comes from +// [dnscache.TLSDialer] (used by the control plane connection), so +// other hostnames resolve normally but are not persisted. +// // A file is rewritten only when its contents change, so its // modification time records when the answer last changed, not when // it was last confirmed. @@ -40,6 +56,7 @@ import ( "tailscale.com/net/dnscache" "tailscale.com/types/logger" "tailscale.com/util/mak" + "tailscale.com/util/set" ) func init() { @@ -47,15 +64,24 @@ func init() { dnscache.HookSetCacheDir.Set(setCacheDir) dnscache.HookPersistResolution.Set(persist) dnscache.HookLookupDiskCache.Set(lookup) + dnscache.HookHostVerified.Set(hostVerified) } var ( - mu sync.Mutex // guards the variables below - cacheDir string // empty until the first successful setCacheDir call - logf logger.Logf // non-nil once cacheDir is set - lastWritten map[string]string // hostname => digest of last JSON written + mu sync.Mutex // guards the variables below + cacheDir string // empty until the first successful setCacheDir call + logf logger.Logf // non-nil once cacheDir is set + lastWritten map[string]string // hostname => digest of last JSON written + pending map[string]pendingRec // hostname => resolution awaiting TLS verification ) +// pendingRec is a marshaled resolution awaiting TLS verification of +// one of its IPs before being written to disk. +type pendingRec struct { + j []byte // marshaled record + ips set.Set[netip.Addr] +} + // record is the JSON structure of each persisted per-hostname file. type record struct { Resolver string // resolver source of the answer: "forward", "cloud", or "fallback" @@ -95,18 +121,20 @@ func filePath(host string) string { return filepath.Join(cacheDir, "dns-"+host+".json") } -// persist writes the resolution of host to disk, unless the on-disk -// contents would be unchanged. It implements -// [dnscache.HookPersistResolution]. +// persist records the resolution of host as pending, to be written to +// disk by hostVerified once one of its IPs passes TLS certificate +// verification for host. It implements [dnscache.HookPersistResolution]. func persist(host, resolver string, ips []netip.Addr) { host = strings.ToLower(host) if !validHostname(host) || len(ips) == 0 { return } rec := record{Resolver: resolver} + ipSet := make(set.Set[netip.Addr]) ips = slices.Clone(ips) slices.SortFunc(ips, netip.Addr.Compare) for _, ip := range slices.Compact(ips) { + ipSet.Add(ip) if ip.Is4() { rec.A = append(rec.A, ip) } else { @@ -117,20 +145,48 @@ func persist(host, resolver string, ips []netip.Addr) { if err != nil { return } - digest := sha256.Sum256(j) mu.Lock() defer mu.Unlock() if cacheDir == "" { return } + mak.Set(&pending, host, pendingRec{j: j, ips: ipSet}) +} + +// hostVerified flushes the pending resolution of host to disk if ip +// is one of its addresses. It implements [dnscache.HookHostVerified]. +func hostVerified(host string, ip netip.Addr) { + host = strings.ToLower(host) + if !validHostname(host) { + return + } + mu.Lock() + defer mu.Unlock() + p, ok := pending[host] + if !ok || !p.ips.Contains(ip.Unmap()) { + // Nothing pending, or the verified connection didn't use an + // IP from the pending resolution (e.g. an older resolution's + // IP, or a bogus record whose IPs never verify). Keep any + // pending record for a later handshake on a member IP. + return + } + delete(pending, host) + writeLocked(host, p.j) +} + +// writeLocked writes j to host's cache file, unless the contents +// would be unchanged. The caller must hold mu, and cacheDir must be +// non-empty. +func writeLocked(host string, j []byte) { + digest := sha256.Sum256(j) path := filePath(host) if last, ok := lastWritten[host]; ok { if last == string(digest[:]) { return } } else if old, err := os.ReadFile(path); err == nil && bytes.Equal(old, j) { - // First resolution since process start and the file already + // First write since process start and the file already // matches; skip the write to preserve its modtime. mak.Set(&lastWritten, host, string(digest[:])) return diff --git a/feature/dnsresolvecache/dnsresolvecache_test.go b/feature/dnsresolvecache/dnsresolvecache_test.go index 32d848699..6c43ab631 100644 --- a/feature/dnsresolvecache/dnsresolvecache_test.go +++ b/feature/dnsresolvecache/dnsresolvecache_test.go @@ -25,6 +25,7 @@ func setDirForTest(t *testing.T) string { cacheDir = "" logf = nil lastWritten = nil + pending = nil mu.Unlock() }) return dir @@ -37,6 +38,13 @@ func mustIPs(ss ...string) (ips []netip.Addr) { return ips } +// persistVerified is persist plus a TLS verification of the first IP, +// which is what flushes the record to disk. +func persistVerified(host, resolver string, ips []netip.Addr) { + persist(host, resolver, ips) + hostVerified(host, ips[0]) +} + func mtime(t *testing.T, path string) time.Time { t.Helper() fi, err := os.Stat(path) @@ -49,7 +57,7 @@ func mtime(t *testing.T, path string) time.Time { func TestPersistAndLookup(t *testing.T) { dir := setDirForTest(t) - persist("Ctrl.Example.COM", "forward", mustIPs("4.4.4.4", "2600::2", "1.1.1.1", "2600::1", "1.1.1.1")) + persistVerified("Ctrl.Example.COM", "forward", mustIPs("4.4.4.4", "2600::2", "1.1.1.1", "2600::1", "1.1.1.1")) path := filepath.Join(dir, "dns-ctrl.example.com.json") got, err := os.ReadFile(path) @@ -79,12 +87,12 @@ func TestNoRewriteWhenUnchanged(t *testing.T) { path := filepath.Join(dir, "dns-ctrl.example.com.json") old := time.Now().Add(-time.Hour).Round(time.Second) - persist("ctrl.example.com", "forward", mustIPs("1.1.1.1")) + persistVerified("ctrl.example.com", "forward", mustIPs("1.1.1.1")) if err := os.Chtimes(path, old, old); err != nil { t.Fatal(err) } - persist("ctrl.example.com", "forward", mustIPs("1.1.1.1")) + persistVerified("ctrl.example.com", "forward", mustIPs("1.1.1.1")) if got := mtime(t, path); !got.Equal(old) { t.Errorf("unchanged persist rewrote file; mtime = %v, want %v", got, old) } @@ -94,12 +102,12 @@ func TestNoRewriteWhenUnchanged(t *testing.T) { mu.Lock() lastWritten = nil mu.Unlock() - persist("ctrl.example.com", "forward", mustIPs("1.1.1.1")) + persistVerified("ctrl.example.com", "forward", mustIPs("1.1.1.1")) if got := mtime(t, path); !got.Equal(old) { t.Errorf("unchanged persist after restart rewrote file; mtime = %v, want %v", got, old) } - persist("ctrl.example.com", "forward", mustIPs("2.2.2.2")) + persistVerified("ctrl.example.com", "forward", mustIPs("2.2.2.2")) if got := mtime(t, path); got.Equal(old) { t.Error("changed persist did not rewrite file") } @@ -121,7 +129,7 @@ func TestInvalidHostnames(t *testing.T) { "example.com.", // trailing dot: valid DNS, but not a name we store "bad*char.example.com", } { - persist(host, "forward", mustIPs("1.1.1.1")) + persistVerified(host, "forward", mustIPs("1.1.1.1")) if _, ok := lookup(host); ok { t.Errorf("lookup(%q) unexpectedly succeeded", host) } @@ -135,6 +143,59 @@ func TestInvalidHostnames(t *testing.T) { } } +func TestVerifyBeforePersist(t *testing.T) { + dir := setDirForTest(t) + path := filepath.Join(dir, "dns-ctrl.example.com.json") + + // An unverified resolution writes nothing. + persist("ctrl.example.com", "forward", mustIPs("1.1.1.1", "2600::1")) + if _, err := os.Stat(path); err == nil { + t.Fatal("file written before TLS verification") + } + + // Verifying an IP that is not part of the pending resolution + // neither writes nor discards the pending record. + hostVerified("ctrl.example.com", netip.MustParseAddr("9.9.9.9")) + if _, err := os.Stat(path); err == nil { + t.Fatal("file written after verification of non-member IP") + } + + // Verifying a member IP flushes the whole record, both families. + hostVerified("ctrl.example.com", netip.MustParseAddr("2600::1")) + got, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + const want = `{"Resolver":"forward","A":["1.1.1.1"],"AAAA":["2600::1"]}` + if string(got) != want { + t.Errorf("file contents = %q; want %q", got, want) + } + + // Re-verifying with nothing pending is a no-op. + old := time.Now().Add(-time.Hour).Round(time.Second) + if err := os.Chtimes(path, old, old); err != nil { + t.Fatal(err) + } + hostVerified("ctrl.example.com", netip.MustParseAddr("1.1.1.1")) + if got := mtime(t, path); !got.Equal(old) { + t.Error("verification with nothing pending rewrote file") + } + + // A new-but-unverified resolution leaves the old file intact; + // verification then updates it. + persist("ctrl.example.com", "forward", mustIPs("2.2.2.2")) + if got := mtime(t, path); !got.Equal(old) { + t.Error("unverified resolution rewrote file") + } + hostVerified("ctrl.example.com", netip.MustParseAddr("2.2.2.2")) + if ips, ok := lookup("ctrl.example.com"); !ok || !slices.Equal(ips, mustIPs("2.2.2.2")) { + t.Errorf("lookup after verified change = %v, %v; want [2.2.2.2], true", ips, ok) + } + + // Verification with an invalid hostname is a no-op. + hostVerified("../evil", netip.MustParseAddr("2.2.2.2")) +} + func TestLookupCorruptFile(t *testing.T) { dir := setDirForTest(t) if err := os.WriteFile(filepath.Join(dir, "dns-ctrl.example.com.json"), []byte("not json"), 0600); err != nil { @@ -151,6 +212,7 @@ func TestSetCacheDirFirstCallWins(t *testing.T) { cacheDir = "" logf = nil lastWritten = nil + pending = nil mu.Unlock() }) dir1 := t.TempDir() @@ -159,7 +221,7 @@ func TestSetCacheDirFirstCallWins(t *testing.T) { // A second call is a no-op; the first directory stays in use. setCacheDir(dir2, t.Logf) - persist("ctrl.example.com", "forward", mustIPs("1.1.1.1")) + persistVerified("ctrl.example.com", "forward", mustIPs("1.1.1.1")) if _, err := os.Stat(filepath.Join(dir1, "dns-ctrl.example.com.json")); err != nil { t.Errorf("file not written to first dir: %v", err) } @@ -170,7 +232,7 @@ func TestSetCacheDirFirstCallWins(t *testing.T) { func TestDisabled(t *testing.T) { // No setCacheDir call: both directions are no-ops. - persist("ctrl.example.com", "forward", mustIPs("1.1.1.1")) + persistVerified("ctrl.example.com", "forward", mustIPs("1.1.1.1")) if _, ok := lookup("ctrl.example.com"); ok { t.Error("lookup unexpectedly succeeded with no cache dir set") } diff --git a/net/dnscache/dnscache.go b/net/dnscache/dnscache.go index 5dc43184c..74b29207d 100644 --- a/net/dnscache/dnscache.go +++ b/net/dnscache/dnscache.go @@ -8,6 +8,7 @@ package dnscache import ( "context" "crypto/tls" + "crypto/x509" "errors" "fmt" "log" @@ -22,6 +23,7 @@ import ( "tailscale.com/envknob" "tailscale.com/feature" "tailscale.com/feature/buildfeatures" + "tailscale.com/net/bakedroots" "tailscale.com/net/netx" "tailscale.com/syncs" "tailscale.com/types/logger" @@ -40,7 +42,9 @@ var HookSetCacheDir feature.Hook[func(dir string, logf logger.Logf)] // HookPersistResolution optionally points to the dnsresolvecache // feature's function to record a successful DNS resolution of host // to disk. The resolver argument is one of the "forward", "cloud", -// or "fallback" resolver source names. +// or "fallback" resolver source names. The feature defers the actual +// disk write until [HookHostVerified] confirms one of the +// resolution's IPs. var HookPersistResolution feature.Hook[func(host, resolver string, ips []netip.Addr)] // HookLookupDiskCache optionally points to the dnsresolvecache @@ -49,6 +53,16 @@ var HookPersistResolution feature.Hook[func(host, resolver string, ips []netip.A // failed, before falling back to the DERP-based bootstrap DNS. var HookLookupDiskCache feature.Hook[func(host string) ([]netip.Addr, bool)] +// HookHostVerified optionally points to the dnsresolvecache +// feature's function to record that a TLS connection to host, at the +// given remote IP, presented a certificate chain that is valid for +// host. That is checked independently of the connection's own TLS +// config, which may deliberately tolerate interception (as the +// control plane Noise connection does). The feature uses this to +// flush a pending resolution of host to disk only once one of its +// IPs has been cryptographically verified to be host. +var HookHostVerified feature.Hook[func(host string, ip netip.Addr)] + // Resolver source names, as passed to [HookPersistResolution] and // used for deciding fallback behavior in Resolver.lookupIP. const ( @@ -669,10 +683,54 @@ func TLSDialer(fwd netx.DialFunc, dnsCache *Resolver, tlsConfigBase *tls.Config) // DNS mechanism. return nil, err } + // Tell the dnsresolvecache feature (if linked in) that the + // remote IP presented a valid certificate for host. The chain + // is checked here, independently of whatever verification the + // tls.Config did during the handshake, because some callers + // (notably controlhttp, which runs Noise atop whatever + // transport it gets) deliberately tolerate invalid TLS + // certificates; an intercepted connection must not mark the + // DNS resolution as verified. + if buildfeatures.HasDNSResolveCache { + if f, ok := HookHostVerified.GetOk(); ok && certValidForHost(tlsConn.ConnectionState(), host, cfg.RootCAs) { + if ap, err := netip.ParseAddrPort(tcpConn.RemoteAddr().String()); err == nil { + f(host, ap.Addr().Unmap()) + } + } + } return tlsConn, nil } } +// certValidForHost reports whether cs's peer certificate chain is +// valid for host, verifying against roots if non-nil (a caller's +// explicitly configured trust anchors), else against the system +// roots. In either case the baked-in Let's Encrypt roots are also +// tried, as net/tlsdial's Config does. +func certValidForHost(cs tls.ConnectionState, host string, roots *x509.CertPool) bool { + if len(cs.PeerCertificates) == 0 { + return false + } + opts := x509.VerifyOptions{ + DNSName: host, + Roots: roots, // nil means system roots + Intermediates: x509.NewCertPool(), + } + for _, cert := range cs.PeerCertificates[1:] { + opts.Intermediates.AddCert(cert) + } + if _, err := cs.PeerCertificates[0].Verify(opts); err == nil { + return true + } + if buildfeatures.HasBakedRoots { + opts.Roots = bakedroots.Get() + if _, err := cs.PeerCertificates[0].Verify(opts); err == nil { + return true + } + } + return false +} + func cloneTLSConfig(cfg *tls.Config) *tls.Config { if cfg == nil { return &tls.Config{} diff --git a/net/dnscache/dnscache_test.go b/net/dnscache/dnscache_test.go index c7e215ba9..f35fe6df8 100644 --- a/net/dnscache/dnscache_test.go +++ b/net/dnscache/dnscache_test.go @@ -5,9 +5,16 @@ package dnscache import ( "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" "errors" "flag" "fmt" + "math/big" "net" "net/netip" "reflect" @@ -408,3 +415,161 @@ func TestDiskCacheHooks(t *testing.T) { } }) } + +func newTestCert(t *testing.T, dnsName string) (tls.Certificate, *x509.Certificate) { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{CommonName: dnsName}, + DNSNames: []string{dnsName}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + BasicConstraintsValid: true, + IsCA: true, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + parsed, err := x509.ParseCertificate(der) + if err != nil { + t.Fatal(err) + } + return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key}, parsed +} + +// startTLSServer starts a TLS server on 127.0.0.1 serving cert and +// returns its port. +func startTLSServer(t *testing.T, cert tls.Certificate) (port string) { + t.Helper() + ln, err := tls.Listen("tcp", "127.0.0.1:0", &tls.Config{Certificates: []tls.Certificate{cert}}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + go func() { + c.(*tls.Conn).Handshake() + c.Close() + }() + } + }() + _, port, err = net.SplitHostPort(ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + return port +} + +func TestTLSDialerHostVerifiedHook(t *testing.T) { + lo := netip.MustParseAddr("127.0.0.1") + resolver := &Resolver{ + Logf: t.Logf, + LookupIPForTest: func(ctx context.Context, host string) ([]netip.Addr, error) { + return []netip.Addr{lo}, nil + }, + } + var std net.Dialer + + type verifiedCall struct { + host string + ip netip.Addr + } + var got []verifiedCall + defer HookHostVerified.SetForTest(func(host string, ip netip.Addr) { + got = append(got, verifiedCall{host, ip}) + })() + + t.Run("verified", func(t *testing.T) { + got = nil + cert, parsed := newTestCert(t, "ctrl.example.com") + port := startTLSServer(t, cert) + pool := x509.NewCertPool() + pool.AddCert(parsed) + + td := TLSDialer(std.DialContext, resolver, &tls.Config{RootCAs: pool}) + c, err := td(t.Context(), "tcp", "ctrl.example.com:"+port) + if err != nil { + t.Fatal(err) + } + defer c.Close() + want := []verifiedCall{{"ctrl.example.com", lo}} + if !reflect.DeepEqual(got, want) { + t.Errorf("verified calls = %+v; want %+v", got, want) + } + }) + + t.Run("insecure-no-hook", func(t *testing.T) { + got = nil + cert, _ := newTestCert(t, "other.example.com") + port := startTLSServer(t, cert) + + // Handshake succeeds due to InsecureSkipVerify, but without + // certificate verification the hook must not fire. + td := TLSDialer(std.DialContext, resolver, &tls.Config{InsecureSkipVerify: true}) + c, err := td(t.Context(), "tcp", "ctrl.example.com:"+port) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if len(got) != 0 { + t.Errorf("hook fired despite InsecureSkipVerify: %+v", got) + } + }) + + t.Run("intercepted-no-hook", func(t *testing.T) { + got = nil + cert, _ := newTestCert(t, "ctrl.example.com") + port := startTLSServer(t, cert) + + // An interception-tolerant config in the style of controlhttp: + // a VerifyConnection hook that swallows all verification + // errors, because Noise doesn't need TLS to be honest. The + // handshake succeeds even though the cert chain is untrusted, + // and the hook must not fire. (Regression test for the review + // concern that VerifyConnection != nil was treated as proof of + // verification.) + td := TLSDialer(std.DialContext, resolver, &tls.Config{ + InsecureSkipVerify: true, + VerifyConnection: func(tls.ConnectionState) error { return nil }, + }) + c, err := td(t.Context(), "tcp", "ctrl.example.com:"+port) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if len(got) != 0 { + t.Errorf("hook fired on intercepted connection: %+v", got) + } + }) + + t.Run("bad-cert-no-hook", func(t *testing.T) { + got = nil + cert, parsed := newTestCert(t, "other.example.com") + port := startTLSServer(t, cert) + pool := x509.NewCertPool() + pool.AddCert(parsed) + + // Cert is trusted but for the wrong name: handshake fails and + // the hook must not fire. + td := TLSDialer(std.DialContext, resolver, &tls.Config{RootCAs: pool}) + if c, err := td(t.Context(), "tcp", "ctrl.example.com:"+port); err == nil { + c.Close() + t.Fatal("dial unexpectedly succeeded with wrong-name cert") + } + if len(got) != 0 { + t.Errorf("hook fired despite failed verification: %+v", got) + } + }) +}