diff --git a/ssh/tailssh/fdleak_test.go b/ssh/tailssh/fdleak_test.go index 3d58ed75a..1105bd4cd 100644 --- a/ssh/tailssh/fdleak_test.go +++ b/ssh/tailssh/fdleak_test.go @@ -268,7 +268,7 @@ func ambientFds(t *testing.T) map[int]bool { // with the live pty's master. A beyond-set fd that was already open in // the test process when the test started is runner-inherited ambient // state and is reported, not failed; a beyond-set fd acquired since, -// or any fd targeting the live pty's master or slave, fails. +// or any fd targeting the live PTY master or PTY child endpoint, fails. func assertSessionFdsIsolated( t *testing.T, dump sessionFdsDump, diff --git a/ssh/tailssh/incubator.go b/ssh/tailssh/incubator.go index e0b6257ef..9d397fa92 100644 --- a/ssh/tailssh/incubator.go +++ b/ssh/tailssh/incubator.go @@ -1008,39 +1008,66 @@ func (ss *sshSession) launchProcess() error { return err } - // We need to be able to close stdin and stdout separately later so make - // dups. Use F_DUPFD_CLOEXEC rather than dup(2): a plain dup does not set - // FD_CLOEXEC, so the pty master would be inherited by every other SSH - // session's child process started while this session is alive. A leaked - // master keeps the pty open after this session ends, so its slave never - // hangs up and processes writing to it (e.g. a tmux server) block forever. - // - // The resize goroutine owns the second dup, so a window-change - // request acts on a descriptor held open for its goroutine's - // lifetime. - outDup, err := unix.FcntlInt(pty.Fd(), unix.F_DUPFD_CLOEXEC, 0) - if err != nil { - pty.Close() - tty.Close() - return err + defer pty.Close() + // Use independently closeable, pollable master descriptors for stdin, + // stdout, and window changes. The original master is not used for I/O. + var masters [3]*os.File + for i := range masters { + masters[i], err = dupPTYMaster(pty) + if err != nil { + for _, f := range masters { + if f != nil { + f.Close() + } + } + tty.Close() + return err + } } - resizeDup, err := unix.FcntlInt(pty.Fd(), unix.F_DUPFD_CLOEXEC, 0) - if err != nil { - unix.Close(outDup) - pty.Close() - tty.Close() - return err - } - go resizeWindow(os.NewFile(uintptr(resizeDup), pty.Name()), winCh) + ss.ptyResize = masters[2] + go resizeWindow(ss.ctx, masters[2], winCh) - ss.wrStdin = pty - ss.rdStdout = os.NewFile(uintptr(outDup), pty.Name()) + ss.wrStdin = masters[0] + ss.rdStdout = masters[1] ss.rdStderr = nil // not available for pty ss.childPipes = []io.Closer{tty} return nil } +// dupPTYMaster duplicates a PTY master with CLOEXEC and O_NONBLOCK set before +// os.NewFile registers it with the runtime poller. Descriptor operations on the +// returned file must use SyscallConn to synchronize with Close. +func dupPTYMaster(f *os.File) (*os.File, error) { + raw, err := f.SyscallConn() + if err != nil { + return nil, err + } + fd := -1 + var dupErr error + if err := raw.Control(func(src uintptr) { + fd, dupErr = unix.FcntlInt(src, unix.F_DUPFD_CLOEXEC, 0) + if dupErr == nil { + dupErr = unix.SetNonblock(fd, true) + } + }); err != nil { + return nil, err + } + if dupErr != nil { + if fd != -1 { + unix.Close(fd) + } + return nil, dupErr + } + dup := os.NewFile(uintptr(fd), f.Name()) + // Reject descriptors that the runtime cannot poll: Close must interrupt I/O. + if err := dup.SetReadDeadline(time.Time{}); err != nil { + dup.Close() + return nil, fmt.Errorf("PTY master is not pollable: %w", err) + } + return dup, nil +} + // sessionViaMonitor reports whether this session's child is exec'd by // the conn's ssh-monitor instead of being started directly by // tailscaled. The monitor route requires a tailscaled binary; plan9 @@ -1049,20 +1076,40 @@ func (ss *sshSession) sessionViaMonitor() bool { return ss.conn.srv.tailscaledPath != "" } -// resizeWindow applies window-change requests to the session's pty -// master. It stops when the SSH channel closes its window channel or -// when the ioctl on the master fails. f is this goroutine's own -// descriptor of the master, held open for the goroutine's lifetime. -func resizeWindow(f *os.File, winCh <-chan gliderssh.Window) { +// resizeWindow applies window changes until cancellation, channel closure, +// or a non-EINTR ioctl error. It closes its PTY master descriptor on return. +func resizeWindow(ctx context.Context, f *os.File, winCh <-chan gliderssh.Window) { defer f.Close() - for win := range winCh { - if err := unix.IoctlSetWinsize(int(f.Fd()), syscall.TIOCSWINSZ, &unix.Winsize{ - Row: uint16(win.Height), - Col: uint16(win.Width), - Xpixel: uint16(win.WidthPixels), - Ypixel: uint16(win.HeightPixels), - }); err != nil { + raw, err := f.SyscallConn() + if err != nil { + return + } + for { + select { + case <-ctx.Done(): return + case win, ok := <-winCh: + if !ok { + return + } + var ioctlErr error + // Control prevents concurrent Close from releasing the descriptor + // while the ioctl is using it. + if err := raw.Control(func(fd uintptr) { + for { + ioctlErr = unix.IoctlSetWinsize(int(fd), syscall.TIOCSWINSZ, &unix.Winsize{ + Row: uint16(win.Height), + Col: uint16(win.Width), + Xpixel: uint16(win.WidthPixels), + Ypixel: uint16(win.HeightPixels), + }) + if !errors.Is(ioctlErr, unix.EINTR) || ctx.Err() != nil { + break + } + } + }); err != nil || ioctlErr != nil { + return + } } } } @@ -1130,7 +1177,7 @@ var opcodeShortName = map[uint8]string{ } // startWithPTY starts the session with a pseudo-terminal as its stdio. -// On the monitor path, the slave descriptors are passed via SCM_RIGHTS. +// On the monitor path, the PTY child descriptors are passed via SCM_RIGHTS. func (ss *sshSession) startWithPTY(envFile *os.File) (ptyFile, tty *os.File, err error) { ptyReq := ss.ptyReq cmd := ss.cmd diff --git a/ssh/tailssh/monitor_linux.go b/ssh/tailssh/monitor_linux.go index 5d972f0a4..280e828a2 100644 --- a/ssh/tailssh/monitor_linux.go +++ b/ssh/tailssh/monitor_linux.go @@ -13,7 +13,7 @@ import ( ) // monChildAttr returns the SysProcAttr for one monitor child. A ctty -// child gets Setsid+Setctty with the pty slave as its fd 0; Setpgid is +// child gets Setsid+Setctty with the PTY child endpoint as fd 0; Setpgid is // set only for non-ctty children. Pdeathsig is advisory: it fires on // the exit of the creating thread, not the process, per golang/go#27505. func monChildAttr(ctty bool) *syscall.SysProcAttr { diff --git a/ssh/tailssh/process_unix.go b/ssh/tailssh/process_unix.go index 1c0504179..a7e9ecaf9 100644 --- a/ssh/tailssh/process_unix.go +++ b/ssh/tailssh/process_unix.go @@ -14,6 +14,7 @@ import ( "path/filepath" "runtime" "syscall" + "time" gliderssh "github.com/tailscale/gliderssh" ) @@ -108,17 +109,27 @@ func (ss *sshSession) waitProcess() (exitCode int, err error) { return 1, err } -// hangupProcess asks the session's process to terminate because the -// session is over. On the monitor path this is hangupMonitorProcess. -// On the direct path it is a single SIGHUP to the child pid. +// hangupProcess closes the PTY or sends SIGHUP, then schedules SIGKILL +// if the session process has not exited. func (ss *sshSession) hangupProcess() { + if ss.ptyReq != nil { + // Close every PTY master descriptor so the terminal driver sends SIGHUP. + closeAll(ss.wrStdin, ss.rdStdout, ss.ptyResize) + } if ss.hangupMonitorProcess() { return } - // SIGHUP = POSIX terminal-disconnect semantics; OpenSSH gets it - // implicitly via PTY-master close (session.c:2246), we send it - // explicitly because non-PTY sessions use pipes. - ss.cmd.Process.Signal(syscall.SIGHUP) + if ss.cmd == nil || ss.cmd.Process == nil { + return + } + p := ss.cmd.Process + // The process handle synchronizes signaling with exit and reaping. + if ss.ptyReq == nil { + p.Signal(syscall.SIGHUP) + } + time.AfterFunc(knobDuration(sshHupEscalation(), defaultHupEscalation), func() { + p.Signal(syscall.SIGKILL) + }) } // systemHostKeyFile returns the path of the system's OpenSSH host key of the diff --git a/ssh/tailssh/sessmonitor.go b/ssh/tailssh/sessmonitor.go index 5caee0ea7..ac35d5628 100644 --- a/ssh/tailssh/sessmonitor.go +++ b/ssh/tailssh/sessmonitor.go @@ -118,8 +118,8 @@ func (ss *sshSession) waitMonitorProcess() (code int, ok bool, err error) { } } -// hangupMonitorProcess sends SIGHUP, then SIGKILL after hangupEscalation if the -// child has not exited. It returns false for directly launched sessions. +// hangupMonitorProcess sends SIGHUP for non-PTY sessions and schedules SIGKILL +// if the child has not exited. It returns false for directly launched sessions. func (ss *sshSession) hangupMonitorProcess() bool { if ss.monChild.PID == 0 { return false @@ -130,12 +130,14 @@ func (ss *sshSession) hangupMonitorProcess() bool { // been reused, so tailscaled must not signal them directly. return true } - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - if err := mc.Signal(ctx, ss.monChild, "SIGHUP"); err != nil { - ss.logf("ssh: SIGHUP session process group: %v", err) + if ss.ptyReq == nil { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := mc.Signal(ctx, ss.monChild, "SIGHUP"); err != nil { + ss.logf("ssh: SIGHUP session process group: %v", err) + } } - time.AfterFunc(hangupEscalation, func() { ss.escalateMonitorProcess(mc) }) + time.AfterFunc(knobDuration(sshHupEscalation(), hangupEscalation), func() { ss.escalateMonitorProcess(mc) }) return true } diff --git a/ssh/tailssh/sessmonitor_test.go b/ssh/tailssh/sessmonitor_test.go index 7de212537..af1ec15a5 100644 --- a/ssh/tailssh/sessmonitor_test.go +++ b/ssh/tailssh/sessmonitor_test.go @@ -341,8 +341,8 @@ func TestSessionMonitorExitStatusOrder(t *testing.T) { } // TestSessionMonitorPTY drives a pty session through the monitor: the -// slave fds travel to the monitor via SCM_RIGHTS, the monitor applies -// Setsid+Setctty (slave as fd 0), and the client's window-change requests +// PTY child descriptors travel to the monitor via SCM_RIGHTS, which applies +// Setsid+Setctty with the PTY child endpoint as fd 0. Window-change requests // are applied by the resizeWindow goroutine's own master descriptor. The // client requests a pty at 10x40, the child reports its size, then the // window is changed to 24x80 and the child reports the new size, pinning diff --git a/ssh/tailssh/ssh_shutdown_test.go b/ssh/tailssh/ssh_shutdown_test.go new file mode 100644 index 000000000..9fbdf1de4 --- /dev/null +++ b/ssh/tailssh/ssh_shutdown_test.go @@ -0,0 +1,178 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build linux || darwin + +package tailssh + +import ( + "bytes" + "fmt" + "net/netip" + "os" + "os/user" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" + "time" + + "tailscale.com/envknob" + "tailscale.com/net/memnet" + "tailscale.com/tailcfg" + testssh "tailscale.com/tempfork/sshtest/ssh" + "tailscale.com/tstest" +) + +// setShutdownKnob sets a teardown timeout for the test and restores its +// previous positive value or the default during cleanup. +func setShutdownKnob(t *testing.T, knob func() time.Duration, envVar string, val time.Duration) { + t.Helper() + old := knob() + envknob.Setenv(envVar, val.String()) + t.Cleanup(func() { + if old > 0 { + envknob.Setenv(envVar, old.String()) + } else { + // Non-positive values select the default timeout. + envknob.Setenv(envVar, "") + } + }) +} + +// TestShutdownWithLingeringDescendant runs an SSH command whose shell exits +// while a descendant in a separate session keeps stdout and stderr open. +// Shutdown must return after the I/O drain timeout, before the longer server +// shutdown timeout. A PID file confirms the descendant started and permits +// cleanup without terminating unrelated processes. +func TestShutdownWithLingeringDescendant(t *testing.T) { + if runtime.GOOS != "linux" { + t.Skipf("skipping on %q; requires the setsid command-line utility", runtime.GOOS) + } + setShutdownKnob(t, sshIODrainTimeout, "TS_SSH_IO_DRAIN_TIMEOUT", time.Second) + setShutdownKnob(t, sshShutdownTimeout, "TS_SSH_SHUTDOWN_TIMEOUT", 5*time.Second) + setShutdownKnob(t, sshHupEscalation, "TS_SSH_HUP_ESCALATION", 500*time.Millisecond) + + u, err := user.Current() + if err != nil { + t.Fatal(err) + } + acceptRule := newSSHRule(&tailcfg.SSHAction{ + Accept: true, + Message: "Welcome to Tailscale SSH!", + }) + // Permit the current user explicitly, including root in privileged tests. + acceptRule.SSHUsers = map[string]string{u.Username: u.Username} + s := &server{ + lb: &localState{sshEnabled: true, matchingRule: acceptRule, varRoot: t.TempDir()}, + logf: tstest.WhileTestRunningLogger(t), + } + src := netip.MustParseAddrPort("100.100.100.101:2231") + dst := netip.MustParseAddrPort("100.100.100.102:22") + sc, dc := memnet.NewTCPConn(src, dst, 1024) + + pidFile := filepath.Join(t.TempDir(), "descendant.pid") + t.Cleanup(func() { + if b, err := os.ReadFile(pidFile); err == nil { + if pid, err := strconv.Atoi(strings.TrimSpace(string(b))); err == nil && pid > 0 { + if p, err := os.FindProcess(pid); err == nil { + p.Kill() + } + } + } + }) + defer sc.Close() + defer dc.Close() + + var clientLog bytes.Buffer // Written by the client goroutine. + clientDone := make(chan struct{}) + go func() { + defer close(clientDone) + cfg := &testssh.ClientConfig{ + User: u.Username, + HostKeyCallback: testssh.InsecureIgnoreHostKey(), + } + c, chans, reqs, err := testssh.NewClientConn(sc, sc.RemoteAddr().String(), cfg) + if err != nil { + fmt.Fprintf(&clientLog, "client connect: %v\n", err) + return + } + client := testssh.NewClient(c, chans, reqs) + defer client.Close() + sess, err := client.NewSession() + if err != nil { + fmt.Fprintf(&clientLog, "client session: %v\n", err) + return + } + defer sess.Close() + // The descendant starts a separate session and keeps stdio open + // after the shell exits. + out, err := sess.CombinedOutput(fmt.Sprintf("setsid sh -c 'echo $$ > %s; exec sleep 60' & exit 0", pidFile)) + fmt.Fprintf(&clientLog, "client output %q, err %v\n", out, err) + }() + + srvDone := make(chan error, 1) + go func() { + srvDone <- s.HandleSSHConn(dc) + }() + + // Wait for the descendant to start. + waitFor := time.Now().Add(10 * time.Second) + for { + if b, err := os.ReadFile(pidFile); err == nil && len(b) > 0 { + break + } + select { + case <-clientDone: + t.Fatalf("client finished before descendant started: %s; server error: %v", clientLog.String(), <-srvDone) + default: + } + if time.Now().After(waitFor) { + t.Fatal("descendant did not start") + } + time.Sleep(10 * time.Millisecond) + } + + const maxShutdown = 4 * time.Second + t0 := time.Now() + s.Shutdown() + if d := time.Since(t0); d > maxShutdown { + t.Errorf("Shutdown took %v with a wedged session; want within %v", d, maxShutdown) + } + + select { + case <-clientDone: + case <-time.After(maxShutdown): + t.Fatal("client did not finish after Shutdown") + } + t.Logf("%s", clientLog.String()) + if err := <-srvDone; err != nil { + t.Errorf("HandleSSHConn: %v", err) + } +} + +// TestShutdownAbandonsStuckSession attaches a session that cannot finish until +// test cleanup detaches it. Shutdown must return within its time limit on both +// calls, even though the session WaitGroup remains nonzero. +func TestShutdownAbandonsStuckSession(t *testing.T) { + setShutdownKnob(t, sshShutdownTimeout, "TS_SSH_SHUTDOWN_TIMEOUT", 500*time.Millisecond) + + s := &server{logf: tstest.WhileTestRunningLogger(t)} + c := &conn{srv: s} + ss := &sshSession{conn: c, sharedID: "sess-stuck"} + if !s.attachSessionToConnIfNotShutdown(ss) { + t.Fatal("session was not attached") + } + t.Cleanup(func() { c.detachSession(ss) }) + + const maxShutdown = 3 * time.Second + t0 := time.Now() + s.Shutdown() + if d := time.Since(t0); d > maxShutdown { + t.Errorf("Shutdown took %v with a stuck session; want within %v", d, maxShutdown) + } + + // Repeated Shutdown calls must also return. + s.Shutdown() +} diff --git a/ssh/tailssh/ssh_shutdown_unix_test.go b/ssh/tailssh/ssh_shutdown_unix_test.go new file mode 100644 index 000000000..5d0e170a0 --- /dev/null +++ b/ssh/tailssh/ssh_shutdown_unix_test.go @@ -0,0 +1,367 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build (linux && !android) || (darwin && !ios) + +package tailssh + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/creack/pty" + gliderssh "github.com/tailscale/gliderssh" + "golang.org/x/crypto/ssh" + "golang.org/x/sys/unix" + "tailscale.com/tstest" +) + +// TestPTYMaster checks descriptor flags, deadline support, and interruption of +// a pending read separately. Each subtest keeps the PTY child open without writing +// to it, so reads cannot complete from output or terminal hangup. +func TestPTYMaster(t *testing.T) { + open := func(t *testing.T) (master, ptyChild *os.File, ptyChildNonblocking bool) { + t.Helper() + original, ptyChild, err := pty.Open() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ptyChild.Close() }) + defer original.Close() + raw, err := ptyChild.SyscallConn() + if err != nil { + t.Fatal(err) + } + if err := raw.Control(func(fd uintptr) { + flags, err := unix.FcntlInt(fd, unix.F_GETFL, 0) + if err != nil { + t.Fatal(err) + } + ptyChildNonblocking = flags&unix.O_NONBLOCK != 0 + }); err != nil { + t.Fatal(err) + } + master, err = dupPTYMaster(original) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { master.Close() }) + return master, ptyChild, ptyChildNonblocking + } + t.Run("flags", func(t *testing.T) { + master, ptyChild, ptyChildNonblocking := open(t) + for _, tc := range []struct { + f *os.File + nonblocking bool + }{{master, true}, {ptyChild, ptyChildNonblocking}} { + raw, err := tc.f.SyscallConn() + if err != nil { + t.Fatal(err) + } + if err := raw.Control(func(fd uintptr) { + flags, err := unix.FcntlInt(fd, unix.F_GETFL, 0) + if err != nil || (flags&unix.O_NONBLOCK != 0) != tc.nonblocking { + t.Errorf("%s: status flags = %#x, %v; want nonblocking=%v", tc.f.Name(), flags, err, tc.nonblocking) + } + flags, err = unix.FcntlInt(fd, unix.F_GETFD, 0) + if err != nil || flags&unix.FD_CLOEXEC == 0 { + t.Errorf("%s: descriptor flags = %#x, %v; want FD_CLOEXEC", tc.f.Name(), flags, err) + } + }); err != nil { + t.Fatal(err) + } + } + }) + t.Run("read-deadline", func(t *testing.T) { + master, _, _ := open(t) + if err := master.SetReadDeadline(time.Now().Add(20 * time.Millisecond)); err != nil { + t.Fatal(err) + } + var buf [1]byte + if _, err := master.Read(buf[:]); !errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatalf("Read error = %v; want deadline exceeded", err) + } + }) + t.Run("close-interrupts-read", func(t *testing.T) { + master, _, _ := open(t) + raw, err := master.SyscallConn() + if err != nil { + t.Fatal(err) + } + waiting := make(chan struct{}) + done := make(chan error, 1) + go func() { + var buf [1]byte + notified := false + done <- raw.Read(func(fd uintptr) bool { + var err error + for { + _, err = unix.Read(int(fd), buf[:]) + if !errors.Is(err, unix.EINTR) { + break + } + } + if !errors.Is(err, unix.EAGAIN) { + return true + } + // The read operation holds the descriptor and has reached EAGAIN. + if !notified { + close(waiting) + notified = true + } + return false + }) + }() + select { + case <-waiting: + case err := <-done: + t.Fatalf("Read completed without blocking: %v", err) + case <-time.After(5 * time.Second): + t.Fatal("Read did not reach EAGAIN") + } + master.Close() + select { + case err := <-done: + if err == nil { + t.Error("pending Read succeeded after Close") + } + case <-time.After(5 * time.Second): + t.Fatal("Close did not interrupt the pending read") + } + }) +} + +// TestSessionMonitorCancellation cancels a live SSH session after its shell +// installs a HUP trap. The trap writes a file outside the terminal, which must +// appear before SIGKILL escalation. The client must receive the cancellation +// message before channel close, and a second session must use the same live +// connection and monitor. Both PTY and pipe-backed sessions are exercised. +func TestSessionMonitorCancellation(t *testing.T) { + for _, isPTY := range []bool{false, true} { + t.Run(fmt.Sprintf("pty=%v", isPTY), func(t *testing.T) { + setShutdownKnob(t, sshHupEscalation, "TS_SSH_HUP_ESCALATION", 30*time.Second) + sessions := make(chan *sshSession, 1) + addr := newMonitorSessionServer(t, func(c *conn, s gliderssh.Session) { + ss := c.newSSHSession(s) + sessions <- ss + ss.run() + }) + client, err := ssh.Dial("tcp", addr, &ssh.ClientConfig{ + HostKeyCallback: ssh.InsecureIgnoreHostKey(), + Timeout: 10 * time.Second, + }) + if err != nil { + t.Fatal(err) + } + defer client.Close() + s, err := client.NewSession() + if err != nil { + t.Fatal(err) + } + defer s.Close() + if isPTY { + if err := s.RequestPty("xterm", 24, 80, nil); err != nil { + t.Fatal(err) + } + } + stdin, err := s.StdinPipe() + if err != nil { + t.Fatal(err) + } + defer stdin.Close() + out, err := s.StdoutPipe() + if err != nil { + t.Fatal(err) + } + var stderr bytes.Buffer + s.Stderr = &stderr + marker := filepath.Join(t.TempDir(), "hup") + command := fmt.Sprintf("trap 'echo hup > %s; exit 42' HUP; echo ready; while :; do read line; done", marker) + if err := s.Start(command); err != nil { + t.Fatal(err) + } + if line, err := bufio.NewReader(out).ReadString('\n'); err != nil || strings.TrimSpace(line) != "ready" { + t.Fatalf("ready marker = %q, %v", line, err) + } + ss := <-sessions + const message = "test session canceled" + ss.cancelCtx(userVisibleError{error: context.Canceled, msg: message}) + if err := tstest.WaitFor(5*time.Second, func() error { + b, err := os.ReadFile(marker) + if err != nil { + return err + } + if strings.TrimSpace(string(b)) != "hup" { + return fmt.Errorf("HUP marker = %q", b) + } + return nil + }); err != nil { + t.Fatalf("hangup did not precede escalation: %v", err) + } + if err := s.Wait(); err == nil { + t.Fatal("session exited without a hangup status") + } else if ee, ok := err.(*ssh.ExitError); !ok || (ee.ExitStatus() != 42 && ee.ExitStatus() != 128+int(unix.SIGHUP)) { + t.Fatalf("session error = %v; want trap exit 42 or SIGHUP", err) + } + if got := strings.Count(stderr.String(), message); got != 1 { + t.Fatalf("stderr = %q; want one cancellation message", stderr.String()) + } + next, err := client.NewSession() + if err != nil { + t.Fatal(err) + } + defer next.Close() + if out, err := next.CombinedOutput("echo alive"); err != nil || strings.TrimSpace(string(out)) != "alive" { + t.Fatalf("second session output = %q, %v", out, err) + } + }) + } +} + +// TestSessionMonitorNormalExit verifies that process completion stops the +// cancellation watcher without waiting for connection closure. Two commands +// on one connection must each deliver output, exit status, EOF, and close. +func TestSessionMonitorNormalExit(t *testing.T) { + frames := make(chan []string, 1) + addr := newMonitorSessionServer(t, func(c *conn, s gliderssh.Session) { + r := &frameRecorder{Session: s} + c.newSSHSession(r).run() + frames <- r.got() + }) + client, err := ssh.Dial("tcp", addr, &ssh.ClientConfig{ + HostKeyCallback: ssh.InsecureIgnoreHostKey(), + Timeout: 10 * time.Second, + }) + if err != nil { + t.Fatal(err) + } + defer client.Close() + for range 2 { + s, err := client.NewSession() + if err != nil { + t.Fatal(err) + } + defer s.Close() + var out []byte + done := make(chan error, 1) + go func() { + var err error + out, err = s.CombinedOutput("echo output; exit 7") + done <- err + }() + select { + case err := <-done: + if ee, ok := err.(*ssh.ExitError); !ok || ee.ExitStatus() != 7 { + t.Fatalf("session error = %v; want exit 7", err) + } + case <-time.After(10 * time.Second): + t.Fatal("normal exit waited for connection closure") + } + if strings.TrimSpace(string(out)) != "output" { + t.Fatalf("output = %q; want output", out) + } + select { + case got := <-frames: + if !slices.Equal(got, []string{"exit-status", "eof", "close"}) { + t.Fatalf("normal exit frames = %v", got) + } + case <-time.After(5 * time.Second): + t.Fatal("session handler did not finish") + } + } +} + +// TestOutputDrainTimeoutAbortsChannel sends one byte more than the SSH receive +// window without reading client stdout. The child exits, but its final output +// write cannot finish. The server must close the channel without EOF after the +// drain timeout. Reading buffered output afterward verifies that the receive +// window was full rather than the command failing before the pending write. +func TestOutputDrainTimeoutAbortsChannel(t *testing.T) { + setShutdownKnob(t, sshIODrainTimeout, "TS_SSH_IO_DRAIN_TIMEOUT", 100*time.Millisecond) + result := make(chan []string, 1) + addr := newMonitorSessionServer(t, func(c *conn, session gliderssh.Session) { + frames := &frameRecorder{Session: session} + c.newSSHSession(frames).run() + result <- frames.got() + }) + client, err := ssh.Dial("tcp", addr, &ssh.ClientConfig{ + HostKeyCallback: ssh.InsecureIgnoreHostKey(), + Timeout: 10 * time.Second, + }) + if err != nil { + t.Fatal(err) + } + defer client.Close() + s, err := client.NewSession() + if err != nil { + t.Fatal(err) + } + defer s.Close() + out, err := s.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err := s.Start("head -c 2097153 /dev/zero"); err != nil { + t.Fatal(err) + } + select { + case frames := <-result: + if slices.Contains(frames, "eof") { + t.Fatalf("drain timeout sent EOF with a pending write: %v", frames) + } + if len(frames) < 2 || frames[0] != "exit-status" || frames[1] != "close" { + t.Fatalf("timeout frames = %v; want exit-status then close", frames) + } + case <-time.After(10 * time.Second): + t.Fatal("output drain timeout did not abort the session") + } + if n, err := io.Copy(io.Discard, out); err != nil || n != 2<<20 { + t.Fatalf("received %d bytes, %v; want the full 2 MiB window", n, err) + } + if err := s.Wait(); err != nil { + t.Fatal(err) + } +} + +// TestResizeWindowCancellation keeps the resize channel open and cancels the +// session context. The resize worker must close its master descriptor and exit +// without waiting for another window-change request. +func TestResizeWindowCancellation(t *testing.T) { + master, ptyChild, err := pty.Open() + if err != nil { + t.Fatal(err) + } + defer master.Close() + defer ptyChild.Close() + f, err := dupPTYMaster(master) + if err != nil { + t.Fatal(err) + } + defer f.Close() + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + done := make(chan struct{}) + go func() { + defer close(done) + resizeWindow(ctx, f, make(chan gliderssh.Window)) + }() + cancel() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("resize worker did not stop on cancellation") + } + if _, err := f.Stat(); !errors.Is(err, os.ErrClosed) { + t.Fatalf("resize descriptor Stat error = %v; want os.ErrClosed", err) + } +} diff --git a/ssh/tailssh/tailssh.go b/ssh/tailssh/tailssh.go index c31f211cc..f352fc700 100644 --- a/ssh/tailssh/tailssh.go +++ b/ssh/tailssh/tailssh.go @@ -60,6 +60,11 @@ var ( sshForwardGatewayPorts = envknob.RegisterBool("TS_SSH_FORWARD_GATEWAY_PORTS") sshDisablePTY = envknob.RegisterBool("TS_SSH_DISABLE_PTY") + // Session teardown timeouts. Unset or non-positive values use the defaults. + sshShutdownTimeout = envknob.RegisterDuration("TS_SSH_SHUTDOWN_TIMEOUT") + sshIODrainTimeout = envknob.RegisterDuration("TS_SSH_IO_DRAIN_TIMEOUT") + sshHupEscalation = envknob.RegisterDuration("TS_SSH_HUP_ESCALATION") + // sshLoginGraceTime is the TS_SSH_LOGIN_GRACE_TIME knob. It is // the maximum allowed duration between accepting a connection and // completing authentication, like sshd's LoginGraceTime. It defaults @@ -76,6 +81,20 @@ var ( hookSSHLoginSuccess feature.Hook[func(logf logger.Logf, c *conn)] ) +const ( + defaultShutdownTimeout = 10 * time.Second + defaultIODrainTimeout = 30 * time.Second + defaultHupEscalation = 5 * time.Second +) + +// knobDuration returns v if positive, or def otherwise. +func knobDuration(v, def time.Duration) time.Duration { + if v <= 0 { + return def + } + return v +} + const ( // forcePasswordSuffix is the suffix at the end of a username that forces // Tailscale SSH into password authentication mode to work around buggy SSH @@ -216,9 +235,8 @@ func (srv *server) HandleSSHConn(nc net.Conn) error { return nil } -// Shutdown closes all active connections and waits for their sessions to exit. -// Closing the raw transport also interrupts authentication and cancels pending -// HoldAndDelegate requests. +// Shutdown closes active connections and waits up to sshShutdownTimeout for +// sessions to finish. Session goroutines may remain running after it returns. func (srv *server) Shutdown() { srv.mu.Lock() srv.shutdownCalled = true @@ -226,7 +244,26 @@ func (srv *server) Shutdown() { c.closeConn() } srv.mu.Unlock() - srv.sessionWaitGroup.Wait() + srv.awaitSessionsDone() +} + +// awaitSessionsDone waits up to sshShutdownTimeout for attached sessions to +// finish. It reports whether all sessions finished before the timeout. +func (srv *server) awaitSessionsDone() bool { + done := make(chan struct{}) + go func() { + // Wait continues after the timeout until all sessions detach. + srv.sessionWaitGroup.Wait() + close(done) + }() + timeout := knobDuration(sshShutdownTimeout(), defaultShutdownTimeout) + select { + case <-done: + return true + case <-time.After(timeout): + srv.logf("ssh: sessions did not finish within %v of shutdown; abandoning them", timeout) + return false + } } // OnPolicyChange terminates any active connections and sessions that no @@ -883,21 +920,12 @@ type sshSession struct { rdStdout io.ReadCloser rdStderr io.ReadCloser // rdStderr is nil for pty sessions ptyReq *gliderssh.Pty // non-nil for pty sessions + ptyResize io.Closer // PTY master descriptor used for window changes // childPipes is a list of pipes that need to be closed when the process exits. // For pty sessions, this is the tty fd. // For non-pty sessions, this is the stdin, stdout, stderr fds. childPipes []io.Closer - - // We use this sync.Once to ensure that we only terminate the process once, - // either it exits itself or is terminated - exitOnce sync.Once - - // exitHandled is closed when killProcessOnContextDone finishes writing any - // termination message to the client. run() waits on this before calling - // ss.Exit to ensure the message is flushed before the SSH channel is torn - // down. It is initialized by run() before starting killProcessOnContextDone. - exitHandled chan struct{} } func (ss *sshSession) vlogf(format string, args ...any) { @@ -1325,26 +1353,29 @@ func (c *conn) fetchSSHAction(ctx context.Context, url string) (*tailcfg.SSHActi } } -// killProcessOnContextDone waits for ss.ctx to be done and kills the process, -// unless the process has already exited. -func (ss *sshSession) killProcessOnContextDone() { - defer close(ss.exitHandled) - <-ss.ctx.Done() - // Either the process has already exited, in which case this does nothing. - // Or, the process is still running in which case this will kill it. - ss.exitOnce.Do(func() { - err := context.Cause(ss.ctx) - if serr, ok := err.(SSHTerminationError); ok { - msg := serr.SSHTerminationMessage() - if msg != "" { - io.WriteString(ss.Stderr(), "\r\n\r\n"+msg+"\r\n\r\n") - } +// killProcessOnContextDone reports cancellation and terminates the session +// process. processDone stops it when the process exits normally. +func (ss *sshSession) killProcessOnContextDone(processDone <-chan struct{}) { + select { + case <-ss.ctx.Done(): + case <-processDone: + if ss.ctx.Err() == nil { + return } + } + err := context.Cause(ss.ctx) + if serr, ok := err.(SSHTerminationError); ok { + if msg := serr.SSHTerminationMessage(); msg != "" { + io.WriteString(ss.Stderr(), "\r\n\r\n"+msg+"\r\n\r\n") + } + } + select { + case <-processDone: + return + default: ss.logf("terminating SSH session from %v: %v", ss.conn.info.src.Addr(), err) - // We don't need to wait for the process here, sshSession.run() - // does the waiting regardless of termination reason. ss.hangupProcess() - }) + } } // isNotFoundOrExecutable reports whether err is a launchProcess @@ -1481,8 +1512,12 @@ func (ss *sshSession) run() { ss.Exit(exitCode) return } - ss.exitHandled = make(chan struct{}) - go ss.killProcessOnContextDone() + processDone := make(chan struct{}) + terminationDone := make(chan struct{}) + go func() { + defer close(terminationDone) + ss.killProcessOnContextDone(processDone) + }() // Wait for both output streams before sending CHANNEL_EOF. // Do not wait for stdin: clients may keep it open until CHANNEL_CLOSE. @@ -1518,17 +1553,9 @@ func (ss *sshSession) run() { exitCode, err := ss.waitProcess() - if ss.ctx.Err() != nil { - // Cancellation (e.g. recording upload failure) wrote a - // termination message via killProcessOnContextDone; wait - // for it before Exit closes the channel for writes. - <-ss.exitHandled - } - - // This will either make the SSH Termination goroutine be a no-op, - // or itself will be a no-op because the process was killed by the - // aforementioned goroutine. - ss.exitOnce.Do(func() {}) + close(processDone) + // Finish any cancellation message before sending exit-status or EOF. + <-terminationDone switch { case err != nil: @@ -1547,7 +1574,22 @@ func (ss *sshSession) run() { // stream's tail. ss.Exit(exitCode) closeAll(ss.childPipes...) - wg.Wait() + // Bound the I/O drain because descendants may keep stdio open after + // the session process exits. + ioDone := make(chan struct{}) + go func() { + wg.Wait() + close(ioDone) + }() + drainTimeout := knobDuration(sshIODrainTimeout(), defaultIODrainTimeout) + select { + case <-ioDone: + case <-time.After(drainTimeout): + ss.logf("ssh: session I/O did not drain within %v; closing channel", drainTimeout) + ss.Close() + closeAll(ss.wrStdin, ss.rdStdout, ss.rdStderr, ss.ptyResize) + return + } ss.CloseWrite() }