diff --git a/tailcat_ssh_unix.go b/tailcat_ssh_unix.go index 978563e8b..8d6b10a22 100644 --- a/tailcat_ssh_unix.go +++ b/tailcat_ssh_unix.go @@ -132,12 +132,32 @@ func runWithPTY(sess ssh.Session, cmd *exec.Cmd, ptyReq ssh.Pty, winCh <-chan ss }() } + // If the client goes away while the command is still running, hang + // it up as OpenSSH does, rather than leaving it (and the pty) running + // with nobody attached. The child is a session leader (Setsid), so + // its process group ID is its PID. + stopHangup := make(chan struct{}) + hangupDone := make(chan struct{}) + go func() { + defer close(hangupDone) + select { + case <-sess.Context().Done(): + unix.Kill(-cmd.Process.Pid, unix.SIGHUP) + case <-stopHangup: + } + }() + // I/O: session ↔ pty master. go func() { io.Copy(ptmx, sess) // stdin }() io.Copy(sess, ptmx) // stdout (blocks until pty closes) + // Stop the hangup goroutine before Wait reaps the child, so it can't + // signal a process group whose ID has since been reused. + close(stopHangup) + <-hangupDone + if err := cmd.Wait(); err != nil { sess.Exit(exitCode(err)) return diff --git a/tailcat_ssh_unix_test.go b/tailcat_ssh_unix_test.go new file mode 100644 index 000000000..9ab9f8389 --- /dev/null +++ b/tailcat_ssh_unix_test.go @@ -0,0 +1,62 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build (linux || darwin) && !ts_omit_ssh + +package tailcat_test + +import ( + "bufio" + "strconv" + "strings" + "syscall" + "testing" + "time" + + gossh "golang.org/x/crypto/ssh" +) + +// TestSSHPTYHangupOnDisconnect checks that a PTY session's process is +// hung up when the client's connection goes away, as with OpenSSH, +// rather than being left running with nobody attached to its terminal. +func TestSSHPTYHangupOnDisconnect(t *testing.T) { + t.Parallel() + env := setupSSHEnv(t) + + c := env.sshClient(t) + sess, err := c.NewSession() + if err != nil { + t.Fatal(err) + } + if err := sess.RequestPty("xterm", 24, 80, gossh.TerminalModes{}); err != nil { + t.Fatalf("RequestPty: %v", err) + } + stdout, err := sess.StdoutPipe() + if err != nil { + t.Fatal(err) + } + // The process prints its pid and then waits for input that never + // comes, like an idle interactive program. + if err := sess.Start("echo pid=$$; exec cat"); err != nil { + t.Fatalf("Start: %v", err) + } + line, err := bufio.NewReader(stdout).ReadString('\n') + if err != nil { + t.Fatalf("reading pid: %v", err) + } + pid, err := strconv.Atoi(strings.TrimSpace(strings.TrimPrefix(line, "pid="))) + if err != nil { + t.Fatalf("parsing pid from %q: %v", line, err) + } + t.Cleanup(func() { syscall.Kill(pid, syscall.SIGKILL) }) + + c.Close() // the client goes away without ending the session + + deadline := time.Now().Add(10 * time.Second) + for syscall.Kill(pid, 0) == nil { + if time.Now().After(deadline) { + t.Fatalf("pid %d still running 10s after the client disconnected", pid) + } + time.Sleep(50 * time.Millisecond) + } +}