package sourcehttp import ( "bufio" "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/tls" "crypto/x509" "errors" "io" "math/big" "net" "net/http" "net/netip" "testing" "time" ) type resolverFunc func(context.Context, string, string) ([]netip.Addr, error) func (f resolverFunc) LookupNetIP(c context.Context, n, h string) ([]netip.Addr, error) { return f(c, n, h) } func TestForbiddenDNSAnswersNeverDial(t *testing.T) { for _, host := range []string{"finance.yahoo.com", "www.cnbc.com", "feed.quanwenrss.com"} { for _, value := range []string{"0.0.0.0", "10.0.0.1", "100.64.0.1", "127.0.0.1", "169.254.1.1", "172.16.0.1", "192.168.0.1", "192.0.0.9", "192.0.2.1", "198.18.0.1", "198.51.100.1", "203.0.113.1", "224.0.0.1", "240.0.0.1", "255.255.255.255", "::", "::1", "fc00::1", "fe80::1", "ff02::1", "2001:db8::1", "2002:0808:0808::1", "64:ff9b::808:808", "2001::1", "3fff::1", "::ffff:127.0.0.1"} { t.Run(host+"/"+value, func(t *testing.T) { dials := 0 tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) { return []netip.Addr{netip.MustParseAddr(value)}, nil }), func(context.Context, string, string) (net.Conn, error) { dials++; return nil, errors.New("fixture") }) // HTTP cannot reach a socket or send a request when DNS is rejected. req, _ := http.NewRequest("GET", "https://"+host+"/fixture", nil) if _, err := tr.RoundTrip(req); err == nil || dials != 0 { t.Fatal("forbidden DNS answer reached dial") } }) } } } func TestDNSFailsClosedAndNumericPinning(t *testing.T) { for _, answers := range [][]netip.Addr{nil, {netip.MustParseAddr("8.8.8.8"), netip.MustParseAddr("127.0.0.1")}, {netip.Addr{}}, {netip.MustParseAddr("fe80::1%fixture")}} { dials := 0 tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) { return answers, nil }), func(context.Context, string, string) (net.Conn, error) { dials++; return nil, errors.New("fixture") }) if _, err := tr.DialContext(context.Background(), "tcp", "finance.yahoo.com:443"); err == nil || dials != 0 { t.Fatal("invalid/mixed answer allowed") } } for _, value := range []string{"8.8.8.8", "2606:4700:4700::1111", "::ffff:8.8.8.8"} { lookups, dials := 0, 0 tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) { lookups++ return []netip.Addr{netip.MustParseAddr(value)}, nil }), func(_ context.Context, _ string, address string) (net.Conn, error) { dials++ if address != net.JoinHostPort(netip.MustParseAddr(value).Unmap().String(), "443") { t.Fatal("dial was not pinned") } return nil, errors.New("fixture") }) tr.DialContext(context.Background(), "tcp", "finance.yahoo.com:443") if lookups != 1 || dials != 1 || tr.Proxy != nil { t.Fatal("resolver/dial/proxy contract failed") } } } func TestPinnedTLSRetainsSNIAndHost(t *testing.T) { for _, host := range []string{"finance.yahoo.com", "www.cnbc.com", "feed.quanwenrss.com"} { t.Run(host, func(t *testing.T) { key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) template := &x509.Certificate{SerialNumber: big.NewInt(1), DNSNames: []string{host}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}} der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key) if err != nil { t.Fatal("certificate fixture failed") } roots := x509.NewCertPool() cert, _ := x509.ParseCertificate(der) roots.AddCert(cert) observed := make(chan bool, 1) tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) { return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil }), func(_ context.Context, _ string, address string) (net.Conn, error) { if address != "8.8.8.8:443" { t.Error("unpinned dial") } client, server := net.Pipe() go func() { defer server.Close() server.SetDeadline(time.Now().Add(3 * time.Second)) conn := tls.Server(server, &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}}) r, err := http.ReadRequest(bufio.NewReader(conn)) if err != nil { observed <- false return } observed <- r.Host == host && conn.ConnectionState().ServerName == host io.WriteString(conn, "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") }() return client, nil }) tr.TLSClientConfig = &tls.Config{RootCAs: roots} defer tr.CloseIdleConnections() req, _ := http.NewRequest("GET", "https://"+host+"/fixture", nil) resp, err := tr.RoundTrip(req) if err != nil { t.Fatal("pinned TLS fixture failed") } resp.Body.Close() if !<-observed { t.Fatal("TLS SNI or Host changed") } }) } } func TestEveryNewConnectionRevalidatesDNS(t *testing.T) { for _, host := range []string{"finance.yahoo.com", "www.cnbc.com", "feed.quanwenrss.com"} { lookups, dials := 0, 0 tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) { lookups++ if lookups == 1 { return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil } return []netip.Addr{netip.MustParseAddr("127.0.0.1")}, nil }), func(context.Context, string, string) (net.Conn, error) { dials++; return nil, errors.New("fixture") }) tr.DialContext(context.Background(), "tcp", net.JoinHostPort(host, "443")) tr.DialContext(context.Background(), "tcp", net.JoinHostPort(host, "443")) if lookups != 2 || dials != 1 { t.Fatal("rebound DNS reached dial") } } } func TestResolverErrorsAndDestinationGuardsNeverDial(t *testing.T) { lookups, dials := 0, 0 tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) { lookups++ return nil, errors.New("private resolver error") }), func(context.Context, string, string) (net.Conn, error) { dials++; return nil, errors.New("fixture") }) for _, address := range []string{"finance.yahoo.com:443", "www.cnbc.com:443", "finance.yahoo.com:80", "finance.yahoo.com:444", "127.0.0.1:443", "[::1]:443", "finance.yahoo.com.evil.invalid:443"} { if _, err := tr.DialContext(context.Background(), "tcp", address); err != errUnavailable { t.Fatal("unsafe or raw connection error") } } if lookups != 2 || dials != 0 { t.Fatal("destination guard or failed DNS allowed dial") } }