diff --git a/derp/derphttp/derphttp_ipcert_test.go b/derp/derphttp/derphttp_ipcert_test.go new file mode 100644 index 000000000..66c17a57d --- /dev/null +++ b/derp/derphttp/derphttp_ipcert_test.go @@ -0,0 +1,208 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package derphttp_test + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "math/big" + "net" + "net/http" + "net/netip" + "testing" + "time" + + "tailscale.com/derp/derphttp" + "tailscale.com/derp/derpserver" + "tailscale.com/net/netmon" + "tailscale.com/tailcfg" + "tailscale.com/types/key" +) + +// TestBareIPCert tests that a DERP node can be reached by IP address +// alone, with no DNS name, using a CA-issued cert whose only SANs are +// IP addresses (as LetsEncrypt's short-lived IP certs are). +func TestBareIPCert(t *testing.T) { + ca, caKey := newTestCA(t) + roots := x509.NewCertPool() + roots.AddCert(ca) + + tests := []struct { + name string + listen string // listen address + certIPs []string + node tailcfg.DERPNode // RegionID and DERPPort filled in + wantError bool + }{ + { + name: "v4-hostname", + listen: "127.0.0.1:0", + certIPs: []string{"127.0.0.1"}, + node: tailcfg.DERPNode{HostName: "127.0.0.1"}, + }, + { + name: "v4-hostname-and-ipv4", + listen: "127.0.0.1:0", + certIPs: []string{"127.0.0.1"}, + node: tailcfg.DERPNode{HostName: "127.0.0.1", IPv4: "127.0.0.1", IPv6: "none"}, + }, + { + name: "v4-certname", + listen: "127.0.0.1:0", + certIPs: []string{"127.0.0.1"}, + node: tailcfg.DERPNode{HostName: "derp.invalid", CertName: "127.0.0.1", IPv4: "127.0.0.1", IPv6: "none"}, + }, + { + name: "v4-wrong-ip", + listen: "127.0.0.1:0", + certIPs: []string{"127.0.0.2"}, + node: tailcfg.DERPNode{HostName: "127.0.0.1"}, + wantError: true, + }, + { + name: "v6-hostname", + listen: "[::1]:0", + certIPs: []string{"::1"}, + node: tailcfg.DERPNode{HostName: "::1"}, + }, + { + name: "v6-hostname-and-ipv6", + listen: "[::1]:0", + certIPs: []string{"::1"}, + node: tailcfg.DERPNode{HostName: "::1", IPv4: "none", IPv6: "::1"}, + }, + { + name: "v6-certname", + listen: "[::1]:0", + certIPs: []string{"::1"}, + node: tailcfg.DERPNode{HostName: "derp.invalid", CertName: "::1", IPv4: "none", IPv6: "::1"}, + }, + { + name: "v4-certname-wrong-ip", + listen: "127.0.0.1:0", + certIPs: []string{"127.0.0.2"}, + node: tailcfg.DERPNode{HostName: "derp.invalid", CertName: "127.0.0.1", IPv4: "127.0.0.1", IPv6: "none"}, + wantError: true, + }, + { + name: "v6-wrong-ip", + listen: "[::1]:0", + certIPs: []string{"::2"}, + node: tailcfg.DERPNode{HostName: "::1"}, + wantError: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ln, err := net.Listen("tcp", tt.listen) + if err != nil { + t.Skipf("Listen: %v", err) + } + defer ln.Close() + + leaf := newTestLeaf(t, ca, caKey, tt.certIPs) + ds := derpserver.New(key.NewNode(), t.Logf) + defer ds.Close() + mux := http.NewServeMux() + mux.Handle("/derp", derpserver.Handler(ds)) + hs := &http.Server{ + Handler: mux, + TLSConfig: &tls.Config{ + GetCertificate: func(hi *tls.ClientHelloInfo) (*tls.Certificate, error) { + if _, err := netip.ParseAddr(tt.node.HostName); err == nil && hi.ServerName != "" { + t.Errorf("unexpected SNI %q", hi.ServerName) + } + return leaf, nil + }, + }, + } + ds.ModifyTLSConfigToAddMetaCert(hs.TLSConfig) + go hs.ServeTLS(ln, "", "") + defer hs.Close() + + node := tt.node + node.RegionID = 900 + node.DERPPort = ln.Addr().(*net.TCPAddr).Port + reg := &tailcfg.DERPRegion{RegionID: 900, RegionCode: "test", Nodes: []*tailcfg.DERPNode{&node}} + + dc := derphttp.NewRegionClient(key.NewNode(), t.Logf, netmon.NewStatic(), func() *tailcfg.DERPRegion { return reg }) + defer dc.Close() + dc.TLSConfig = &tls.Config{RootCAs: roots} + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + err = dc.Connect(ctx) + if tt.wantError { + if err == nil { + t.Fatal("Connect succeeded; want error") + } + t.Logf("got expected error: %v", err) + return + } + if err != nil { + t.Fatalf("Connect: %v", err) + } + }) + } +} + +func newTestCA(t *testing.T) (*x509.Certificate, *ecdsa.PrivateKey) { + t.Helper() + priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{CommonName: "Test Root CA"}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageCertSign, + BasicConstraintsValid: true, + IsCA: true, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &priv.PublicKey, priv) + if err != nil { + t.Fatal(err) + } + cert, err := x509.ParseCertificate(der) + if err != nil { + t.Fatal(err) + } + return cert, priv +} + +// newTestLeaf returns a cert signed by ca with only IP address SANs, +// like a LetsEncrypt IP address cert. +func newTestLeaf(t *testing.T, ca *x509.Certificate, caKey *ecdsa.PrivateKey, ips []string) *tls.Certificate { + t.Helper() + priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(2), + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + } + for _, s := range ips { + tmpl.IPAddresses = append(tmpl.IPAddresses, net.ParseIP(s)) + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, ca, &priv.PublicKey, caKey) + if err != nil { + t.Fatal(err) + } + leaf, err := x509.ParseCertificate(der) + if err != nil { + t.Fatal(err) + } + return &tls.Certificate{Certificate: [][]byte{der, ca.Raw}, PrivateKey: priv, Leaf: leaf} +} diff --git a/net/tlsdial/tlsdial.go b/net/tlsdial/tlsdial.go index 417c925b7..cf0de4245 100644 --- a/net/tlsdial/tlsdial.go +++ b/net/tlsdial/tlsdial.go @@ -20,6 +20,7 @@ import ( "log" "net" "net/http" + "net/netip" "os" "strings" "sync" @@ -78,7 +79,9 @@ func Config(ht *health.Tracker, base *tls.Config) *tls.Config { } else { conf = base.Clone() } - conf.RootCAs = nil // we do our own verification in VerifyConnection + // RootCAs is unused by crypto/tls once InsecureSkipVerify is set below, + // as we do our own verification in VerifyConnection. It's left in place + // so SetConfigExpectedCert can find the extra roots. // Note: we do NOT set conf.ServerName here (as we accidentally did // previously), as this path is also used when dialing an HTTPS proxy server @@ -114,6 +117,20 @@ func Config(ht *health.Tracker, base *tls.Config) *tls.Config { conf.InsecureSkipVerify = true conf.VerifyConnection = func(cs tls.ConnectionState) (retErr error) { dialedHost := cs.ServerName + if dialedHost == "" { + // crypto/tls sends no SNI for IP address literals, so + // cs.ServerName is empty when dialing by IP. Use the IP + // from conf.ServerName instead, which is set when conf + // was passed to tls.Client directly. But net/http clones + // conf before setting ServerName, so that case and a + // truly empty ServerName have no name to verify against + // and must fail, as x509 verification with an empty + // DNSName skips the hostname check. + if _, err := netip.ParseAddr(conf.ServerName); err != nil { + return errors.New("tlsdial: no server name to verify cert against") + } + dialedHost = conf.ServerName + } if dialedHost == "log.tailscale.com" && hostinfo.IsNATLabGuestVM() { // Allow log.tailscale.com TLS MITM for integration tests when @@ -151,10 +168,10 @@ func Config(ht *health.Tracker, base *tls.Config) *tls.Config { // // TODO(bradfitz): plumb down the selfSignedIssuer as a // structured health warning argument. - ht.SetTLSConnectionError(cs.ServerName, fmt.Errorf("likely intercepted connection; certificate is self-signed by %v", selfSignedIssuer)) + ht.SetTLSConnectionError(dialedHost, fmt.Errorf("likely intercepted connection; certificate is self-signed by %v", selfSignedIssuer)) } else { // Ensure we clear any error state for this ServerName. - ht.SetTLSConnectionError(cs.ServerName, nil) + ht.SetTLSConnectionError(dialedHost, nil) if selfSignedIssuer != "" { // Log the self-signed issuer, but don't treat it as an error. log.Printf("tlsdial: warning: server cert for %q passed x509 validation but is self-signed by %q", dialedHost, selfSignedIssuer) diff --git a/net/tlsdial/tlsdial_test.go b/net/tlsdial/tlsdial_test.go index 9ef0f7688..62cce237e 100644 --- a/net/tlsdial/tlsdial_test.go +++ b/net/tlsdial/tlsdial_test.go @@ -4,13 +4,17 @@ package tlsdial import ( + "crypto/tls" + "crypto/x509" "io" "net" "net/http" + "net/http/httptest" "os" "os/exec" "path/filepath" "runtime" + "strings" "sync/atomic" "testing" @@ -110,3 +114,91 @@ func TestFallbackRootWorks(t *testing.T) { func sayHi(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "hi") } + +// TestIPServerName tests that a ServerName that's an IP address literal +// is verified against the cert's IP SANs, even though crypto/tls sends +// no SNI for it and so leaves ConnectionState.ServerName empty. +func TestIPServerName(t *testing.T) { + srv := httptest.NewTLSServer(http.HandlerFunc(sayHi)) // cert for 127.0.0.1, ::1, example.com + defer srv.Close() + roots := x509.NewCertPool() + roots.AddCert(srv.Certificate()) + + // The wrong-IP cases only check for "certificate" in the error, as + // the error text varies by platform: tlsdial returns the system + // verifier's error, which on macOS and Windows is about the test + // CA being unknown rather than about the name mismatch. + for _, tt := range []struct { + serverName string + wantErr string // or empty for success + }{ + {"127.0.0.1", ""}, + {"::1", ""}, + {"example.com", ""}, + {"127.0.0.2", "certificate"}, + {"::2", "certificate"}, + {"", "no server name"}, + } { + conf := Config(nil, &tls.Config{RootCAs: roots}) + conf.ServerName = tt.serverName + err := handshake(t, srv, conf) + if tt.wantErr == "" { + if err != nil { + t.Errorf("ServerName %q: %v", tt.serverName, err) + } + } else if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Errorf("ServerName %q: got error %v; want error containing %q", tt.serverName, err, tt.wantErr) + } + } + + // net/http clones the tls.Config before setting ServerName, so + // tlsdial can't learn which IP was dialed and must fail. + tr := &http.Transport{ + TLSClientConfig: Config(nil, &tls.Config{RootCAs: roots}), + DisableKeepAlives: true, + } + res, err := (&http.Client{Transport: tr}).Get(srv.URL) + if err == nil { + res.Body.Close() + t.Fatal("net/http GET by IP succeeded; want error") + } + if !strings.Contains(err.Error(), "no server name") { + t.Fatalf("net/http GET by IP: got %v; want no server name error", err) + } +} + +// TestSetConfigExpectedCertExtraRoots tests that SetConfigExpectedCert +// uses the extra roots passed to [Config]. +func TestSetConfigExpectedCertExtraRoots(t *testing.T) { + srv := httptest.NewTLSServer(http.HandlerFunc(sayHi)) // cert for 127.0.0.1, ::1, example.com + defer srv.Close() + roots := x509.NewCertPool() + roots.AddCert(srv.Certificate()) + + for _, tt := range []struct { + certName string + wantErr bool + }{ + {"example.com", false}, + {"127.0.0.1", false}, + {"example.org", true}, + {"127.0.0.2", true}, + } { + conf := Config(nil, &tls.Config{RootCAs: roots}) + conf.ServerName = "front.example" + SetConfigExpectedCert(conf, tt.certName) + if err := handshake(t, srv, conf); (err != nil) != tt.wantErr { + t.Errorf("certName %q: err = %v; want error = %v", tt.certName, err, tt.wantErr) + } + } +} + +// handshake does a TLS handshake with srv using conf. +func handshake(t *testing.T, srv *httptest.Server, conf *tls.Config) error { + c, err := net.Dial("tcp", srv.Listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer c.Close() + return tls.Client(c, conf).Handshake() +}