diff --git a/cmd/k8s-operator/depaware.txt b/cmd/k8s-operator/depaware.txt index 2046595ef..68c0c14e3 100644 --- a/cmd/k8s-operator/depaware.txt +++ b/cmd/k8s-operator/depaware.txt @@ -94,7 +94,7 @@ tailscale.com/cmd/k8s-operator dependencies: (generated by github.com/tailscale/ 💣 github.com/modern-go/reflect2 from github.com/json-iterator/go github.com/munnerz/goautoneg from k8s.io/kube-openapi/pkg/handler3+ github.com/opencontainers/go-digest from github.com/distribution/reference - github.com/pires/go-proxyproto from tailscale.com/ipn/ipnlocal+ + github.com/pires/go-proxyproto from tailscale.com/ipn/ipnlocal github.com/pkg/errors from tailscale.com/cmd/k8s-operator+ github.com/pmezard/go-difflib/difflib from k8s.io/apimachinery/pkg/util/diff github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil from github.com/prometheus/client_golang/prometheus/promhttp diff --git a/cmd/k8s-proxy/k8s-proxy.go b/cmd/k8s-proxy/k8s-proxy.go index bf7427486..915e840ff 100644 --- a/cmd/k8s-proxy/k8s-proxy.go +++ b/cmd/k8s-proxy/k8s-proxy.go @@ -52,12 +52,6 @@ import ( "tailscale.com/tsnet" ) -const ( - // proxyProtocolV2 enables PROXY protocol v2 to preserve original client - // connection info after TLS termination. - proxyProtocolV2 = 2 -) - func main() { encoderCfg := zap.NewProductionEncoderConfig() encoderCfg.EncodeTime = zapcore.RFC3339TimeEncoder @@ -561,9 +555,8 @@ func setServeConfig(ctx context.Context, lc *local.Client, cm *certs.CertManager name: { TCP: map[uint16]*ipn.TCPPortHandler{ 443: { - TCPForward: "localhost:80", - TerminateTLS: serviceSNI, - ProxyProtocol: proxyProtocolV2, + TCPForward: "localhost:80", + TerminateTLS: serviceSNI, }, }, }, diff --git a/ipn/ipnlocal/serve.go b/ipn/ipnlocal/serve.go index 814c1bb40..19b3ff982 100644 --- a/ipn/ipnlocal/serve.go +++ b/ipn/ipnlocal/serve.go @@ -38,6 +38,7 @@ import ( "go4.org/mem" "tailscale.com/envknob" "tailscale.com/ipn" + "tailscale.com/net/netaddr" "tailscale.com/net/netmon" "tailscale.com/net/netutil" "tailscale.com/syncs" @@ -752,8 +753,17 @@ func (b *LocalBackend) tcpHandlerForServeTCP(tcph ipn.TCPPortHandlerView, dport conn = tlsConn } - // TODO(bradfitz): do the RegisterIPPortIdentity and - // UnregisterIPPortIdentity stuff that netstack does + // Register the client's address so a loopback backend can WhoIs it. + // Funnel sources are internet addresses, so they never get an identity. + if la, ok := backConn.LocalAddr().(*net.TCPAddr); ok && la.IP.IsLoopback() && httpCtx.Funnel == nil { + backLocal := netaddr.Unmap(la.AddrPort()) + if err := b.sys.ProxyMapper().RegisterIPPortIdentity("tcp", backLocal, srcAddr.Addr().Unmap()); err != nil { + b.logf("localbackend: could not register TCP mapping %v: %v", backLocal, err) + return nil + } + defer b.sys.ProxyMapper().UnregisterIPPortIdentity("tcp", backLocal) + } + return b.forwardTCPWithProxyProtocol(conn, backConn, tcph.ProxyProtocol(), srcAddr, dport, backDst) } } diff --git a/ipn/ipnlocal/serve_test.go b/ipn/ipnlocal/serve_test.go index 8681cd975..3f545b78b 100644 --- a/ipn/ipnlocal/serve_test.go +++ b/ipn/ipnlocal/serve_test.go @@ -37,6 +37,7 @@ import ( "tailscale.com/health" "tailscale.com/ipn" "tailscale.com/ipn/store/mem" + "tailscale.com/net/netaddr" "tailscale.com/net/netmon" "tailscale.com/net/tsdial" "tailscale.com/syncs" @@ -2955,3 +2956,117 @@ func TestForwardTCPHalfClose(t *testing.T) { }) } } + +// TestTCPForwardWhoIs checks that a backend reached through a TCP forward +// to localhost can find the client with a WhoIs of the connection's remote +// address, and only for as long as the connection is open. A Funnel client, +// or a backend on a non-loopback address, must never get an identity. +func TestTCPForwardWhoIs(t *testing.T) { + tests := []struct { + name string + listen string + localhost bool // forward to localhost: rather than the listener's IP + funnel *funnelFlow + hostIP bool // listen on a non-loopback IPv4 address of this host + }{ + {name: "ipv4", listen: "127.0.0.1:0"}, + {name: "ipv6", listen: "[::1]:0"}, + {name: "localhost", listen: "127.0.0.1:0", localhost: true}, + {name: "funnel_gets_no_identity", listen: "127.0.0.1:0", funnel: &funnelFlow{Host: "foo.example.ts.net:443"}}, + {name: "non_loopback_gets_no_identity", hostIP: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if tt.hostIP { + addrs, _ := net.InterfaceAddrs() + i := slices.IndexFunc(addrs, func(a net.Addr) bool { + ipnet, ok := a.(*net.IPNet) + return ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil + }) + if i < 0 { + t.Skip("no non-loopback IPv4 address") + } + tt.listen = net.JoinHostPort(addrs[i].(*net.IPNet).IP.String(), "0") + } + ln, err := net.Listen("tcp", tt.listen) + if err != nil { + t.Skipf("listen %s: %v", tt.listen, err) + } + defer ln.Close() + target := ln.Addr().String() + if tt.localhost { + ips, _ := net.DefaultResolver.LookupNetIP(t.Context(), "ip", "localhost") + if !slices.ContainsFunc(ips, func(ip netip.Addr) bool { return ip.Unmap() == netip.AddrFrom4([4]byte{127, 0, 0, 1}) }) { + t.Skipf("localhost resolves to %v, not 127.0.0.1", ips) + } + _, port, _ := net.SplitHostPort(target) + target = net.JoinHostPort("localhost", port) + } + + b := newTestBackend(t) + b.logf = tstest.WhileTestRunningLogger(t) + if tt.hostIP { + // netns binds non-localhost dials to the default interface on macOS and Windows. + b.dialer.SetSystemDialer(new(net.Dialer).DialContext) + } + conf := &ipn.ServeConfig{ + TCP: map[uint16]*ipn.TCPPortHandler{ + 3128: {TCPForward: target}, + }, + } + if err := b.SetServeConfig(conf, ""); err != nil { + t.Fatal("setting serve config:", err) + } + + // 100.150.151.152 is "some-peer" in the netmap from newTestBackend. + handler := b.tcpHandlerForServe(3128, netip.MustParseAddrPort("100.150.151.152:12345"), tt.funnel) + if handler == nil { + t.Fatal("tcpHandlerForServe returned nil handler") + } + clientConn, serverConn := net.Pipe() + defer clientConn.Close() + handlerDone := make(chan error, 1) + go func() { + handlerDone <- handler(serverConn) + }() + + // Fail rather than hang if the forward never reaches the listener. + ln.(*net.TCPListener).SetDeadline(time.Now().Add(5 * time.Second)) + backConn, err := ln.Accept() + if err != nil { + t.Fatal(err) + } + defer backConn.Close() + + // Data only flows once the mapping is registered. + go clientConn.Write([]byte("hello")) + if _, err := io.ReadFull(backConn, make([]byte, len("hello"))); err != nil { + t.Fatalf("read failed: %v", err) + } + + backRemote := netaddr.Unmap(backConn.RemoteAddr().(*net.TCPAddr).AddrPort()) + wantNode := tt.funnel == nil && !tt.hostIP + n, _, ok := b.WhoIs("tcp", backRemote) + switch { + case !wantNode && ok: + t.Errorf("WhoIs(%v) = %q, want no node", backRemote, n.ComputedName()) + case wantNode && !ok: + t.Fatalf("WhoIs(%v) found no node, want some-peer", backRemote) + case wantNode && n.ComputedName() != "some-peer": + t.Errorf("WhoIs(%v) = %q, want %q", backRemote, n.ComputedName(), "some-peer") + } + + // The forward half-closes, so it only ends once both sides close. + clientConn.Close() + backConn.Close() + select { + case <-handlerDone: + case <-time.After(5 * time.Second): + t.Fatal("handler did not finish in time") + } + if n, _, ok := b.WhoIs("tcp", backRemote); ok { + t.Errorf("WhoIs(%v) = %q after the connection closed, want no node", backRemote, n.ComputedName()) + } + }) + } +} diff --git a/k8s-operator/api-proxy/proxy.go b/k8s-operator/api-proxy/proxy.go index beada6709..1835b8321 100644 --- a/k8s-operator/api-proxy/proxy.go +++ b/k8s-operator/api-proxy/proxy.go @@ -21,7 +21,6 @@ import ( "strings" "time" - "github.com/pires/go-proxyproto" "go.uber.org/zap" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apiserver/pkg/endpoints/request" @@ -99,6 +98,7 @@ func NewAPIServerProxy(zlog *zap.SugaredLogger, restConfig *rest.Config, ts *tsn upstreamURL: u, ts: ts, sendEventFunc: sessionrecording.SendEvent, + listenFunc: net.Listen, } ap.rp = &httputil.ReverseProxy{ Rewrite: func(pr *httputil.ProxyRequest) { @@ -152,19 +152,12 @@ func (ap *APIServerProxy) Run(ctx context.Context) error { NextProtos: []string{"http/1.1"}, } } else { + // The serve TCP forward registers each conn with the proxy mapper, so whoIs on RemoteAddr finds the caller. var err error - baseLn, err := net.Listen("tcp", "localhost:80") + proxyLn, err = ap.listenFunc("tcp", "localhost:80") if err != nil { return fmt.Errorf("could not listen on :80: %w", err) } - proxyLn = &proxyproto.Listener{ - Listener: baseLn, - ReadHeaderTimeout: 10 * time.Second, - ConnPolicy: proxyproto.ConnPolicyFunc(func(opts proxyproto.ConnPolicyOptions) (proxyproto.Policy, - error) { - return proxyproto.REQUIRE, nil - }), - } serve = ap.hs.Serve } @@ -203,6 +196,7 @@ type APIServerProxy struct { upstreamURL *url.URL sendEventFunc func(ap netip.AddrPort, event io.Reader, dial netx.DialFunc) error + listenFunc func(network, address string) (net.Listener, error) } // serveDefault is the default handler for Kubernetes API server requests. diff --git a/k8s-operator/api-proxy/proxy_test.go b/k8s-operator/api-proxy/proxy_test.go index 9fa0b68a0..ded1f9636 100644 --- a/k8s-operator/api-proxy/proxy_test.go +++ b/k8s-operator/api-proxy/proxy_test.go @@ -6,7 +6,10 @@ package apiproxy import ( + "bufio" + "context" "encoding/json" + "io" "net" "net/http" "net/http/httptest" @@ -14,7 +17,9 @@ import ( "net/netip" "net/url" "reflect" + "sync" "testing" + "time" "github.com/google/go-cmp/cmp" "go.uber.org/zap" @@ -456,6 +461,100 @@ func TestCrossOriginRequests(t *testing.T) { } } +func TestRunForgedProxyHeader(t *testing.T) { + zl, err := zap.NewDevelopment() + if err != nil { + t.Fatal(err) + } + + // Only the forged source resolves, as a netmap address does in LocalBackend.WhoIs. + forgedIP := netip.MustParseAddr("100.64.0.9") + var mu sync.Mutex + var whoIsAddrs []string + lal := memnet.Listen("local-tailscaled.sock:80") + defer lal.Close() + localAPI := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + addr := r.URL.Query().Get("addr") + mu.Lock() + whoIsAddrs = append(whoIsAddrs, addr) + mu.Unlock() + if ap, err := netip.ParseAddrPort(addr); err != nil || ap.Addr() != forgedIP { + http.Error(w, "no match for IP:port", http.StatusNotFound) + return + } + json.NewEncoder(w).Encode(&apitype.WhoIsResponse{ + Node: &tailcfg.Node{Name: "admin-node.ts.net."}, + UserProfile: &tailcfg.UserProfile{LoginName: "admin@example.com"}, + }) + })} + defer localAPI.Close() + go localAPI.Serve(lal) + + var upstreamReqs int + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + upstreamReqs++ + mu.Unlock() + })) + defer upstream.Close() + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + ap := &APIServerProxy{ + log: zl.Sugar(), + lc: &local.Client{Dial: lal.Dial}, + authMode: true, + upstreamURL: must.Get(url.Parse(upstream.URL)), + listenFunc: func(network, address string) (net.Listener, error) { + return ln, nil + }, + } + ap.rp = &httputil.ReverseProxy{ + Rewrite: func(pr *httputil.ProxyRequest) { + ap.addImpersonationHeadersAsRequired(pr.Out) + }, + } + ctx, cancel := context.WithCancel(t.Context()) + runErr := make(chan error, 1) + go func() { runErr <- ap.Run(ctx) }() + defer func() { + cancel() + <-runErr + }() + + c, err := net.Dial("tcp", ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer c.Close() + c.SetDeadline(time.Now().Add(10 * time.Second)) + io.WriteString(c, "PROXY TCP4 "+forgedIP.String()+" 100.100.100.100 12345 443\r\n"+ + "GET /api/v1/namespaces/kube-system/secrets HTTP/1.1\r\n"+ + "Host: localhost\r\n"+ + "Connection: close\r\n\r\n") + resp, err := http.ReadResponse(bufio.NewReader(c), nil) + if err != nil { + t.Fatalf("reading response: %v", err) + } + resp.Body.Close() + if resp.StatusCode == http.StatusOK { + t.Errorf("forged request got %s, want an error", resp.Status) + } + + mu.Lock() + defer mu.Unlock() + for _, addr := range whoIsAddrs { + if ap, err := netip.ParseAddrPort(addr); err == nil && ap.Addr() == forgedIP { + t.Errorf("whoIs was asked about %q from the PROXY header", addr) + } + } + if upstreamReqs > 0 { + t.Errorf("upstream got %d requests, want 0", upstreamReqs) + } +} + func whoResp(capMap map[string][]string) *apitype.WhoIsResponse { resp := &apitype.WhoIsResponse{ CapMap: tailcfg.PeerCapMap{},