From 116c1d207bf01343eda453c86a63a3b8a6eacfb8 Mon Sep 17 00:00:00 2001 From: James Tucker Date: Mon, 26 Oct 2026 20:50:01 +0000 Subject: [PATCH] ssh/tailssh: release reverse-forward cancellation callbacks Close the specific forwarded listener on connection cancellation and stop its callback when the accept loop exits. Canceling a forward no longer retains a connection-lifetime waiter or looks up a replacement listener by address. Test repeated cancel and rebind operations on one connection, along with callback cleanup when the listener closes independently. Make the existing connection-cancellation test fail if its listener stays open. Updates tailscale/corp#50380 Change-Id: Ife7fb0acde012b0abf1a8d804b9c6a8994ee5703 Signed-off-by: James Tucker (cherry picked from commit 055c809d5f67d4f224d3562f5c9df1bedd89c13f) --- ssh/tailssh/fwdmonitor.go | 14 ++-- ssh/tailssh/fwdmonitor_test.go | 18 ++--- ssh/tailssh/fwdtcp_listener_test.go | 109 ++++++++++++++++++++++++++++ 3 files changed, 122 insertions(+), 19 deletions(-) create mode 100644 ssh/tailssh/fwdtcp_listener_test.go diff --git a/ssh/tailssh/fwdmonitor.go b/ssh/tailssh/fwdmonitor.go index af64eccb7..0cf6461e6 100644 --- a/ssh/tailssh/fwdmonitor.go +++ b/ssh/tailssh/fwdmonitor.go @@ -339,16 +339,12 @@ func (h *fwdTCPHandler) HandleSSHRequest(ctx gliderssh.Context, _ *gliderssh.Ser h.mu.Lock() h.forwards[addr] = ln h.mu.Unlock() + // Close this listener when the SSH connection ends. Stop watching + // the connection when the accept loop exits, including on cancellation + // of this forward while the connection remains open. + stop := context.AfterFunc(ctx, func() { ln.Close() }) go func() { - <-ctx.Done() - h.mu.Lock() - fln, ok := h.forwards[addr] - h.mu.Unlock() - if ok { - fln.Close() - } - }() - go func() { + defer stop() defer func() { h.mu.Lock() if h.forwards[addr] == ln { diff --git a/ssh/tailssh/fwdmonitor_test.go b/ssh/tailssh/fwdmonitor_test.go index 1235acd5d..82cb47f4a 100644 --- a/ssh/tailssh/fwdmonitor_test.go +++ b/ssh/tailssh/fwdmonitor_test.go @@ -501,18 +501,16 @@ func TestFwdTCPHandler(t *testing.T) { t.Errorf("echo = %q; want %q", got, want) } - // Canceling the request's context closes the listener through the - // conn's ctx-done goroutine. + // Connection cancellation must close the forwarded listener. cancel() - deadline := time.Now().Add(5 * time.Second) - for time.Now().Before(deadline) { - if conn, err := net.DialTimeout("tcp", fwdAddr, time.Second); err != nil { - break // listener closed - } else { - conn.Close() - time.Sleep(50 * time.Millisecond) + eventually(t, 5*time.Second, "forwarded listener remained open after cancellation", func() bool { + conn, err := net.DialTimeout("tcp", fwdAddr, time.Second) + if err != nil { + return true } - } + conn.Close() + return false + }) // Non-loopback binds are rejected without the gateway-ports knob… ctx2, cancel2 := fwdTestCtx(fwdTestSSHConn{}) diff --git a/ssh/tailssh/fwdtcp_listener_test.go b/ssh/tailssh/fwdtcp_listener_test.go new file mode 100644 index 000000000..15ec76280 --- /dev/null +++ b/ssh/tailssh/fwdtcp_listener_test.go @@ -0,0 +1,109 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build (linux && !android) || (darwin && !ios) || freebsd || openbsd + +package tailssh + +import ( + "context" + "net" + "strconv" + "testing" + "time" + + gliderssh "github.com/tailscale/gliderssh" + gossh "golang.org/x/crypto/ssh" + "tailscale.com/tailcfg" +) + +// fwdCleanupContext reports when the listener removes its cancellation callback. +// fwdTestContext does not expose the underlying context's private values, so +// context.AfterFunc uses this method to register the callback. +type fwdCleanupContext struct { + gliderssh.Context + + // stopped receives the result of each call to the stop function returned + // by AfterFunc. The result is true if the callback was prevented from running. + // The test must provide a non-nil channel with at least one buffer slot. + stopped chan bool +} + +func (c *fwdCleanupContext) AfterFunc(f func()) func() bool { + stop := context.AfterFunc(c.Context, f) + return func() bool { + stopped := stop() + c.stopped <- stopped + return stopped + } +} + +func TestFwdTCPListenerCleanup(t *testing.T) { + c := newFwdTestConn(t, fwdTestIdentity(t), &tailcfg.SSHAction{ + Accept: true, + AllowRemotePortForwarding: true, + }) + base, cancel := fwdTestCtx(fwdTestSSHConn{}) + defer cancel() + ctx := &fwdCleanupContext{Context: base, stopped: make(chan bool, 1)} + h := &fwdTCPHandler{conn: c} + + // Reuse one address on the same SSH connection. Canceling each forward + // must release its listener and cancellation callback, not retain them + // until the SSH connection closes. + var port uint32 + for _, mode := range []string{"request", "request", "listener-close"} { + req := &gossh.Request{ + Type: "tcpip-forward", + Payload: gossh.Marshal(fwdRemoteForwardRequest{BindAddr: "127.0.0.1", BindPort: port}), + } + ok, payload := h.HandleSSHRequest(ctx, nil, req) + if !ok { + t.Fatalf("tcpip-forward: %s", payload) + } + var reply fwdRemoteForwardSuccess + if err := gossh.Unmarshal(payload, &reply); err != nil { + t.Fatal(err) + } + if reply.BindPort == 0 || port != 0 && reply.BindPort != port { + t.Fatalf("bound port = %d, want nonzero and unchanged from %d", reply.BindPort, port) + } + port = reply.BindPort + addr := net.JoinHostPort("127.0.0.1", strconv.Itoa(int(port))) + h.mu.Lock() + ln := h.forwards[addr] + h.mu.Unlock() + if ln == nil { + t.Fatal("listener was not registered") + } + switch mode { + case "request": + ok, _ := h.HandleSSHRequest(ctx, nil, &gossh.Request{ + Type: "cancel-tcpip-forward", + Payload: gossh.Marshal(fwdRemoteForwardCancelRequest{BindAddr: "127.0.0.1", BindPort: port}), + }) + if !ok { + t.Fatal("cancel-tcpip-forward failed") + } + case "listener-close": + ln.Close() + } + select { + case stopped := <-ctx.stopped: + if !stopped { + t.Errorf("%s: cancellation callback was not stopped", mode) + } + case <-time.After(5 * time.Second): + t.Fatalf("%s: listener did not release its cancellation callback", mode) + } + h.mu.Lock() + remaining := len(h.forwards) + h.mu.Unlock() + if remaining != 0 { + t.Fatalf("%s: %d listeners remain", mode, remaining) + } + if ctx.Err() != nil { + t.Fatal("canceling a forward closed the SSH connection context") + } + } +}