diff --git a/ssh/tailssh/monitor.go b/ssh/tailssh/monitor.go index a158caa29..d0ee923b9 100644 --- a/ssh/tailssh/monitor.go +++ b/ssh/tailssh/monitor.go @@ -70,6 +70,15 @@ type monChild struct { // killAt is the SIGKILL deadline. While nonzero, the leader remains // unreaped to prevent PID and process-group reuse. killAt time.Time + + // notified is whether the child's exit has been reported, possibly + // before reaping. + notified bool + + // exited is whether exitWS holds the wait status of the unreaped + // child. See [exitWatcher]. + exited bool + exitWS unix.WaitStatus } // beginTermination sends SIGHUP and sets the SIGKILL deadline once. @@ -101,6 +110,10 @@ type monitor struct { // gracefulClose records receipt of an explicit close request. gracefulClose bool + // exits reports session children's exits before they are reaped, + // where the platform supports it. + exits exitWatcher + // pendingFds holds relayed dial/listen descriptors, keyed by request // ID, from the reply write until tailscaled's fdack receipt. See // replyFD and the monitor_rpc.go header for the darwin kernel @@ -527,6 +540,7 @@ func (m *monitor) handleExec(f rpcFrame, fds []int) { } // Its pgid is its pid. See monChildAttr. m.children[cmd.Process.Pid] = &monChild{pgid: cmd.Process.Pid, id: f.ID} + m.exits.watch(cmd.Process.Pid) m.reply(rpcExecReply(f.ID, cmd.Process.Pid)) } @@ -733,9 +747,24 @@ func (m *monitor) replyFD(f rpcFrame, fds ...int) { // sweep reaps exited children from the given set and removes them from both // the set and m.children. If notify is true, it reports session exit statuses. func (m *monitor) sweep(children map[int]*monChild, notify bool) { + m.exits.drain(m.children) + // Discard exit records of children reaped below, so none can be + // attributed to a later child reusing the pid. + defer m.exits.drain(m.children) for pid, c := range children { + child := monitorProcess{PID: pid, ID: c.id} if !c.killAt.IsZero() { - continue // Retain the leader until group SIGKILL. + // Retain the leader until group SIGKILL, but report its + // exit as soon as it is known so the session can end + // without waiting out the grace period. + if !c.exited { + c.exitWS, c.exited = zombieWaitStatus(pid) + } + if notify && !c.oneshot && !c.notified && c.exited { + m.notifyExit(child, monExitCode(c.exitWS)) + c.notified = true + } + continue } var ws unix.WaitStatus wpid, err := unix.Wait4(pid, &ws, unix.WNOHANG, nil) @@ -746,8 +775,8 @@ func (m *monitor) sweep(children map[int]*monChild, notify bool) { delete(children, pid) delete(m.children, pid) case wpid == pid: - if notify && !c.oneshot { - m.notifyExit(monitorProcess{PID: pid, ID: c.id}, monExitCode(ws)) + if notify && !c.oneshot && !c.notified { + m.notifyExit(child, monExitCode(ws)) } delete(children, pid) delete(m.children, pid) @@ -844,6 +873,7 @@ func (m *monitor) teardown() { } } } + m.exits.close() m.conn.c.Close() } diff --git a/ssh/tailssh/monitor_exits_darwin.go b/ssh/tailssh/monitor_exits_darwin.go new file mode 100644 index 000000000..2cf77f398 --- /dev/null +++ b/ssh/tailssh/monitor_exits_darwin.go @@ -0,0 +1,12 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build !ios + +package tailssh + +import "golang.org/x/sys/unix" + +// noteExitFflags requests NOTE_EXIT events carrying the wait status. +// See [exitWatcher]. +const noteExitFflags = unix.NOTE_EXIT | unix.NOTE_EXITSTATUS diff --git a/ssh/tailssh/monitor_exits_freebsd.go b/ssh/tailssh/monitor_exits_freebsd.go new file mode 100644 index 000000000..44fc0629d --- /dev/null +++ b/ssh/tailssh/monitor_exits_freebsd.go @@ -0,0 +1,10 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package tailssh + +import "golang.org/x/sys/unix" + +// noteExitFflags requests NOTE_EXIT events, which always carry the wait +// status on FreeBSD. See [exitWatcher]. +const noteExitFflags = unix.NOTE_EXIT diff --git a/ssh/tailssh/monitor_exits_kqueue.go b/ssh/tailssh/monitor_exits_kqueue.go new file mode 100644 index 000000000..1b143943d --- /dev/null +++ b/ssh/tailssh/monitor_exits_kqueue.go @@ -0,0 +1,97 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build (darwin && !ios) || freebsd + +package tailssh + +import ( + "golang.org/x/sys/unix" +) + +// exitWatcher learns session children's wait statuses without reaping +// them, so a terminated session's exit can be reported while its leader +// stays unreaped until group SIGKILL. +// +// It registers an EVFILT_PROC NOTE_EXIT filter per child on a kqueue, +// which the kernel triggers at exit with the wait status in the event +// data. The monitor loop wakes on the child's SIGCHLD, posted after the +// NOTE_EXIT event, and drains the kqueue without blocking from +// [monitor.sweep], so no goroutine reads it. +// +// The zero value is ready to use. The kqueue is created on first use. +type exitWatcher struct { + kq int // kqueue descriptor, valid if open + open bool // kq is open + failed bool // kqueue creation failed; watch nothing +} + +// watch registers for pid's exit. Failure leaves pid to be reported +// when it is reaped. +func (w *exitWatcher) watch(pid int) { + if !w.open { + if w.failed { + return + } + kq, err := unix.Kqueue() + if err != nil { + w.failed = true + return + } + unix.CloseOnExec(kq) + w.kq, w.open = kq, true + } + ev := unix.Kevent_t{ + Ident: uint64(pid), + Filter: unix.EVFILT_PROC, + Flags: unix.EV_ADD | unix.EV_ONESHOT, + Fflags: noteExitFflags, + } + // ESRCH means pid is already gone, so it is reaped and reported + // by the next sweep. + unix.Kevent(w.kq, []unix.Kevent_t{ev}, nil, nil) +} + +// drain records the wait status of each exited child in children +// without blocking. Events for pids not in children, already reaped, +// are discarded. +func (w *exitWatcher) drain(children map[int]*monChild) { + if !w.open { + return + } + var evs [16]unix.Kevent_t + var zero unix.Timespec + for { + n, err := unix.Kevent(w.kq, nil, evs[:], &zero) + if err != nil || n <= 0 { + return + } + for _, ev := range evs[:n] { + // On macOS, Data holds the wait status only if the event + // reports NOTE_EXITSTATUS. + if ev.Filter != unix.EVFILT_PROC || ev.Fflags¬eExitFflags != noteExitFflags || ev.Flags&unix.EV_ERROR != 0 { + continue + } + if c, ok := children[int(ev.Ident)]; ok { + c.exitWS, c.exited = unix.WaitStatus(ev.Data), true + } + } + if n < len(evs) { + return + } + } +} + +// close releases the kqueue. +func (w *exitWatcher) close() { + if w.open { + unix.Close(w.kq) + w.open = false + } +} + +// zombieWaitStatus reports false. These platforms learn exit statuses +// from [exitWatcher] instead. +func zombieWaitStatus(pid int) (ws unix.WaitStatus, ok bool) { + return 0, false +} diff --git a/ssh/tailssh/monitor_exits_linux_test.go b/ssh/tailssh/monitor_exits_linux_test.go new file mode 100644 index 000000000..1d2942b82 --- /dev/null +++ b/ssh/tailssh/monitor_exits_linux_test.go @@ -0,0 +1,65 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build linux && !android + +package tailssh + +import ( + "os/exec" + "syscall" + "testing" + "time" +) + +// TestZombieWaitStatus checks that zombieWaitStatus reads exited and +// killed children's wait statuses without reaping them. +func TestZombieWaitStatus(t *testing.T) { + for _, tc := range []struct { + name string + script string + wantExit int // if !wantSignal + wantSignal bool // killed by SIGKILL + }{ + {name: "exit", script: "exit 7", wantExit: 7}, + {name: "killed", script: "kill -KILL $$", wantSignal: true}, + } { + t.Run(tc.name, func(t *testing.T) { + cmd := exec.Command("/bin/sh", "-c", tc.script) + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + pid := cmd.Process.Pid + if ws, ok := zombieWaitStatus(pid); ok && !ws.Exited() && !ws.Signaled() { + t.Fatalf("running child status = %#x", ws) + } + deadline := time.Now().Add(10 * time.Second) + for { + ws, ok := zombieWaitStatus(pid) + if ok { + if tc.wantSignal { + if !ws.Signaled() || ws.Signal() != syscall.SIGKILL { + t.Errorf("status = %#x; want killed by SIGKILL", ws) + } + } else if !ws.Exited() || ws.ExitStatus() != tc.wantExit { + t.Errorf("status = %#x; want exit %d", ws, tc.wantExit) + } + break + } + if time.Now().After(deadline) { + t.Fatal("child did not exit") + } + time.Sleep(10 * time.Millisecond) + } + // The child must still be unreaped, so Wait gets its status. + err := cmd.Wait() + if tc.wantSignal { + if cmd.ProcessState.Sys().(syscall.WaitStatus).Signal() != syscall.SIGKILL { + t.Errorf("Wait = %v; want SIGKILL", err) + } + } else if cmd.ProcessState.ExitCode() != tc.wantExit { + t.Errorf("Wait = %v; want exit %d", err, tc.wantExit) + } + }) + } +} diff --git a/ssh/tailssh/monitor_exits_openbsd.go b/ssh/tailssh/monitor_exits_openbsd.go new file mode 100644 index 000000000..e53b07e93 --- /dev/null +++ b/ssh/tailssh/monitor_exits_openbsd.go @@ -0,0 +1,22 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package tailssh + +import "golang.org/x/sys/unix" + +// exitWatcher does nothing on OpenBSD, so a terminated session's exit +// is reported when its leader is reaped at the end of the grace period. +// +// TODO(bradfitz): OpenBSD's kqueue NOTE_EXIT also reports the wait +// status. Use monitor_exits_kqueue.go here once it is tested on OpenBSD. +type exitWatcher struct{} + +func (*exitWatcher) watch(pid int) {} +func (*exitWatcher) drain(children map[int]*monChild) {} +func (*exitWatcher) close() {} + +// zombieWaitStatus reports false. See [exitWatcher]. +func zombieWaitStatus(pid int) (ws unix.WaitStatus, ok bool) { + return 0, false +} diff --git a/ssh/tailssh/monitor_linux.go b/ssh/tailssh/monitor_linux.go index 73eb990de..8646c4dbb 100644 --- a/ssh/tailssh/monitor_linux.go +++ b/ssh/tailssh/monitor_linux.go @@ -6,8 +6,12 @@ package tailssh import ( + "encoding/binary" "math" + "runtime" + "strings" "syscall" + "unsafe" "golang.org/x/sys/unix" ) @@ -50,3 +54,74 @@ func fwdChildAttr(ma monitorArgs) *syscall.SysProcAttr { Pdeathsig: unix.SIGHUP, } } + +// exitWatcher does nothing on Linux, where [zombieWaitStatus] reads an +// unreaped child's wait status directly. +type exitWatcher struct{} + +func (*exitWatcher) watch(pid int) {} +func (*exitWatcher) drain(children map[int]*monChild) {} +func (*exitWatcher) close() {} + +// zombieWaitStatus returns the wait status of child pid if it has exited +// but is not yet reaped, without reaping it, using waitid with WNOWAIT. +// The pid cannot be reused while the zombie remains unreaped. +// +// It doesn't read /proc//stat's exit_code field, which reads as 0 +// unless the caller may ptrace the child. A non-root monitor's PTY +// leader, login, runs as root. +func zombieWaitStatus(pid int) (ws unix.WaitStatus, ok bool) { + var info unix.Siginfo + for { + err := unix.Waitid(unix.P_PID, pid, &info, unix.WEXITED|unix.WNOWAIT|unix.WNOHANG, nil) + if err == unix.EINTR { + continue + } + if err != nil { + return 0, false + } + break + } + return siginfoWaitStatus(&info) +} + +// The kernel's siginfo_t is 128 bytes on every Linux architecture. +var _ [128]byte = [unsafe.Sizeof(unix.Siginfo{})]byte{} + +// siginfoWaitStatus converts a waitid result to a wait status. It reports +// false if no child had exited, which WNOHANG reports with si_pid zero. +// +// [unix.Siginfo] omits the SIGCHLD fields, so read them at their fixed +// offsets: after the si_signo, si_errno, and si_code ints (si_code second +// on MIPS), the union is pointer-aligned and starts with si_pid, si_uid, +// and si_status. +func siginfoWaitStatus(info *unix.Siginfo) (ws unix.WaitStatus, ok bool) { + b := (*[128]byte)(unsafe.Pointer(info)) + codeOff := 8 + if strings.HasPrefix(runtime.GOARCH, "mips") { + codeOff = 4 + } + unionOff := 12 + if unsafe.Sizeof(uintptr(0)) == 8 { + unionOff = 16 + } + get := func(off int) int32 { return int32(binary.NativeEndian.Uint32(b[off:])) } + if get(unionOff) == 0 { + return 0, false + } + status := uint32(get(unionOff + 8)) + const ( + cldExited = 1 // CLD_EXITED + cldKilled = 2 // CLD_KILLED + cldDumped = 3 // CLD_DUMPED + ) + switch get(codeOff) { + case cldExited: + return unix.WaitStatus(status&0xff) << 8, true + case cldKilled: + return unix.WaitStatus(status & 0x7f), true + case cldDumped: + return unix.WaitStatus(status&0x7f | 0x80), true + } + return 0, false +} diff --git a/ssh/tailssh/monitor_test.go b/ssh/tailssh/monitor_test.go index fff020f3f..8bfe0a2f7 100644 --- a/ssh/tailssh/monitor_test.go +++ b/ssh/tailssh/monitor_test.go @@ -471,6 +471,33 @@ func TestMonitorSignal(t *testing.T) { } } +// TestMonitorTerminateReportsExitEarly checks that a terminated child's +// exit is reported when it dies from SIGHUP, not when the monitor reaps +// it after the SIGKILL grace period. +func TestMonitorTerminateReportsExitEarly(t *testing.T) { + if runtime.GOOS == "openbsd" { + t.Skip("exit is reported after the grace period on OpenBSD; see monitor_exits_openbsd.go") + } + mc := startTestMonitor(t, os.Getuid(), os.Getgid(), testGroups(t)) + exits := collectExits(mc) + + pid, err := mc.Exec(mustCtx(t), []string{"/bin/sleep", "30"}, nil, "/", false, nil) + if err != nil { + t.Fatalf("exec sleep: %v", err) + } + const grace = 30 * time.Second + if err := mc.Terminate(mustCtx(t), pid, grace); err != nil { + t.Fatalf("terminate: %v", err) + } + n := waitExitNote(t, exits, grace/2) + if n.pid != pid { + t.Fatalf("exit notification pid = %d, want %d", n.pid, pid) + } + if want := 128 + int(unix.SIGHUP); n.code != want { + t.Fatalf("exit notification code = %d, want %d (128+SIGHUP)", n.code, want) + } +} + func mustCtx(t *testing.T) context.Context { t.Helper() ctx, cancel := testCtx() diff --git a/ssh/tailssh/ssh_shutdown_unix_test.go b/ssh/tailssh/ssh_shutdown_unix_test.go index 5d0e170a0..fbb05298a 100644 --- a/ssh/tailssh/ssh_shutdown_unix_test.go +++ b/ssh/tailssh/ssh_shutdown_unix_test.go @@ -141,90 +141,106 @@ func TestPTYMaster(t *testing.T) { }) } -// TestSessionMonitorCancellation cancels a live SSH session after its shell +// TestSessionMonitorCancellationPipe runs [testSessionMonitorCancellation] +// with a pipe-backed session. +func TestSessionMonitorCancellationPipe(t *testing.T) { + testSessionMonitorCancellation(t, false) +} + +// TestSessionMonitorCancellationPTY runs [testSessionMonitorCancellation] +// with a PTY-backed session. +func TestSessionMonitorCancellationPTY(t *testing.T) { + testSessionMonitorCancellation(t, true) +} + +// 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) - } - }) +// connection and monitor. The session is PTY-backed if isPTY. +func testSessionMonitorCancellation(t *testing.T, isPTY bool) { + const grace = 30 * time.Second + setShutdownKnob(t, sshHupEscalation, "TS_SSH_HUP_ESCALATION", grace) + 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) + } + waitStart := time.Now() + err = s.Wait() + // The monitor reports the leader's exit while it keeps the zombie + // for the grace period. See [exitWatcher]. + if d := time.Since(waitStart); d > grace/2 { + t.Errorf("session exit took %v; want it reported before the %v grace period ends", d, grace) + } + if 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) } }