From d6535a20daa57eb700153bd7ddf337ca644be245 Mon Sep 17 00:00:00 2001 From: Mike Jensen Date: Tue, 1 Dec 2026 06:59:39 -0700 Subject: [PATCH] cmd/k8s-proxy,ipn/ipnlocal,k8s-operator/api-proxy: drop PROXY protocol (#22754) (#22766) * cmd/k8s-proxy,ipn/ipnlocal,k8s-operator/api-proxy: drop PROXY protocol The API server proxy in cmd/k8s-proxy took the caller's address from the PROXY protocol header on its localhost listener, which any local process could write. This fixes this by removing the header from both sides, and making serve register each non-Funnel TCP forward to a loopback address with the proxy mapper (as netstack does), so WhoIs on the connection's real remote address returns the caller. Updates tailscale/corp#48697 Thank you Winfunc for reporting * ipn/ipnlocal,k8s-operator/api-proxy: add WhoIs and forged header tests Adds a test that WhoIs on the backend side of a serve TCP forward returns the source node while the forward is open and fails after it closes, for IPv4, IPv6 and localhost targets, and that a Funnel flow or a backend on a non-loopback address gets no node. Also adds a test that the API server proxy's plain HTTP listener does not take the caller from a PROXY header that a local client writes. Updates tailscale/corp#48697 --------- Change-Id: I9bd203355c68eb0e9f62755dbea908d7d5435105 (cherry picked from commit 65114d4eba38688e3d03d8a78371908c5f63d4c9) Signed-off-by: chaosinthecrd Co-authored-by: Tom Meadows --- cmd/k8s-operator/depaware.txt | 2 +- cmd/k8s-proxy/k8s-proxy.go | 11 +-- ipn/ipnlocal/serve.go | 14 +++- ipn/ipnlocal/serve_test.go | 115 +++++++++++++++++++++++++++ k8s-operator/api-proxy/proxy.go | 14 +--- k8s-operator/api-proxy/proxy_test.go | 100 +++++++++++++++++++++++ 6 files changed, 234 insertions(+), 22 deletions(-) diff --git a/cmd/k8s-operator/depaware.txt b/cmd/k8s-operator/depaware.txt index 7ed8e04f0..f0b16563b 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 acda50ef2..de548356a 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" @@ -731,8 +732,17 @@ func (b *LocalBackend) tcpHandlerForServeTCP(tcph ipn.TCPPortHandlerView, dport }, nil)) } - // 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 ae9495937..b0c74b437 100644 --- a/ipn/ipnlocal/serve_test.go +++ b/ipn/ipnlocal/serve_test.go @@ -36,6 +36,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" @@ -2761,3 +2762,117 @@ func TestGetTLSServeCertForPortLowercasesSNI(t *testing.T) { t.Error("unconfigured name: got cert, want error") } } + +// 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..a9c0e4235 100644 --- a/k8s-operator/api-proxy/proxy_test.go +++ b/k8s-operator/api-proxy/proxy_test.go @@ -6,6 +6,8 @@ package apiproxy import ( + "bufio" + "context" "encoding/json" "net" "net/http" @@ -14,7 +16,9 @@ import ( "net/netip" "net/url" "reflect" + "sync" "testing" + "time" "github.com/google/go-cmp/cmp" "go.uber.org/zap" @@ -473,3 +477,99 @@ func raw(in ...string) []tailcfg.RawMessage { } return out } + +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)) + if _, err := c.Write([]byte("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")); err != nil { + t.Fatalf("writing request: %v", err) + } + 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) + } +}