From fb7712ece20a04c8f8612dab4f7733ddfa6faa83 Mon Sep 17 00:00:00 2001 From: James Tucker Date: Fri, 30 Oct 2026 04:16:23 +0000 Subject: [PATCH] ssh/tailssh: stop killing session processes on graceful disconnects Monitor teardown SIGHUPed and SIGKILLed every remembered child group when the transport closed. sshd signals nothing at a non-PTY session end; background jobs with redirected stdio survive and reparent to init. Clients rely on that: VS Code Remote-SSH starts its remote server as a plain background job in the session's group and expects it to outlive connection drops, and tailscale upgrades run as non-PTY execs whose work should survive a daemon restart. Use an explicit graceful monitor close to preserve session jobs on ordinary disconnect and daemon shutdown. Close PTY masters normally, letting the terminal driver signal the foreground group, but do not signal non-PTY jobs. Remove Linux Pdeathsig from session children; forwarding children retain it and always die with the connection. Commit duration and recording-failure termination to the monitor before publishing cancellation or writing the termination message. The monitor owns per-session HUP-to-KILL escalation even after the leader exits or the connection closes. Revocation arms connection-wide cleanup. Pin every termination target's leader until after SIGKILL, including during teardown, so group signaling cannot hit reused PIDs. Select teardown targets explicitly and leave graceful survivors alone. Unexpected RPC loss fails closed. If a termination mandate cannot be delivered, close the RPC rather than subsequently requesting graceful teardown; this may also kill sibling jobs on a broken channel. Keep both the escalation and monitor shutdown waits bounded. Add coverage for default-HUP graceful survivors, actual duration and recording-failure termination followed by immediate disconnect, sibling survival, HUP-exiting leaders with immune group members, broken RPCs, and leader pinning through teardown's SIGKILL pass. Fixes #22076 Signed-off-by: James Tucker Change-Id: I70b4ef40035330dd542d256ba79d889a12426a74 (cherry picked from commit 1334899864168f2801ffe4c69d4d6b231b3b9506) Signed-off-by: James Tucker --- ssh/tailssh/connmonitor.go | 16 +- ssh/tailssh/fwdchild.go | 3 +- ssh/tailssh/incubator_plan9.go | 7 +- ssh/tailssh/monitor.go | 162 +++++++++++++++------ ssh/tailssh/monitor_client.go | 40 ++++- ssh/tailssh/monitor_lifecycle_test.go | 96 +++++++----- ssh/tailssh/monitor_linux.go | 23 ++- ssh/tailssh/monitor_rpc.go | 36 +++-- ssh/tailssh/monitor_teardown_linux_test.go | 85 +++++++++++ ssh/tailssh/monitor_termination_test.go | 76 ++++++++++ ssh/tailssh/monitor_test.go | 12 +- ssh/tailssh/monitor_watchdog_linux_test.go | 5 + ssh/tailssh/process_state_darwin_test.go | 18 +++ ssh/tailssh/process_state_linux_test.go | 28 ++++ ssh/tailssh/process_unix.go | 16 +- ssh/tailssh/session_termination_test.go | 158 ++++++++++++++++++++ ssh/tailssh/sessmonitor.go | 34 ++--- ssh/tailssh/sessmonitor_test.go | 159 +++++++++++--------- ssh/tailssh/tailssh.go | 55 +++++-- 19 files changed, 798 insertions(+), 231 deletions(-) create mode 100644 ssh/tailssh/monitor_teardown_linux_test.go create mode 100644 ssh/tailssh/monitor_termination_test.go create mode 100644 ssh/tailssh/process_state_darwin_test.go create mode 100644 ssh/tailssh/process_state_linux_test.go create mode 100644 ssh/tailssh/session_termination_test.go diff --git a/ssh/tailssh/connmonitor.go b/ssh/tailssh/connmonitor.go index 43b280bb6..a850c7d9b 100644 --- a/ssh/tailssh/connmonitor.go +++ b/ssh/tailssh/connmonitor.go @@ -6,11 +6,13 @@ package tailssh import ( + "context" "errors" "fmt" "os" "strconv" "sync" + "time" ) // connMonitorState owns the connection's process monitor. It is started @@ -96,10 +98,9 @@ func (c *conn) monitorCreds() (uid, gid uint32, groups []uint32, err error) { return uint32(u64), uint32(g64), groups, nil } -// closeConnMonitor closes the conn's monitor, if one was spawned. It -// runs from HandleSSHConn's defer after the SSH connection is done. -// Closing the RPC channel triggers the monitor's teardown in monitor.go. -// Closing a second time is a no-op. +// closeConnMonitor closes the connection monitor, if any. +// If monitorKillAll is set, teardown must terminate all session children. +// Subsequent calls have no effect. func (c *conn) closeConnMonitor() { c.monitor.mu.Lock() mc := c.monitor.mon @@ -109,6 +110,13 @@ func (c *conn) closeConnMonitor() { if mc == nil { return } + if c.monitorKillAll.Load() { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + if err := mc.KillAll(ctx); err != nil { + c.logf("ssh: arming monitor kill-all: %v", err) + } + cancel() + } if err := mc.Close(); err != nil { c.logf("ssh: closing connection monitor: %v", err) } diff --git a/ssh/tailssh/fwdchild.go b/ssh/tailssh/fwdchild.go index 3eda5c3be..a2100feee 100644 --- a/ssh/tailssh/fwdchild.go +++ b/ssh/tailssh/fwdchild.go @@ -147,7 +147,8 @@ func fwdSpawnChild(m *monitor, spec fwdChildSpec) (*exec.Cmd, *net.UnixConn, err // which surfaces as the op's error. var attr *syscall.SysProcAttr if os.Getuid() != 0 && uint64(m.args.uid) == uint64(os.Getuid()) && uint64(m.args.gid) == uint64(os.Getgid()) { - attr = monChildAttr(false) // Setpgid, and Pdeathsig on linux. Identity is inherited. + attr = fwdChildAttr(m.args) + attr.Credential = nil // Inherit credentials but retain Pdeathsig. } else { attr = fwdChildAttr(m.args) // born unprivileged (Credential) in its own group } diff --git a/ssh/tailssh/incubator_plan9.go b/ssh/tailssh/incubator_plan9.go index 6e4d02a61..63b4a5745 100644 --- a/ssh/tailssh/incubator_plan9.go +++ b/ssh/tailssh/incubator_plan9.go @@ -430,10 +430,9 @@ func (ss *sshSession) waitMonitorProcess() (code int, ok bool, err error) { return 0, false, nil } -// hangupMonitorProcess is the plan9 seam of the monitor session path. -// It always reports false, so sessions hang up their directly-started -// child. -func (ss *sshSession) hangupMonitorProcess() bool { +// hangupMonitorProcess returns false on Plan 9, which launches children directly. +// See [sshSession.hangupProcess]. +func (ss *sshSession) hangupMonitorProcess(mandated bool) bool { return false } diff --git a/ssh/tailssh/monitor.go b/ssh/tailssh/monitor.go index 19677d1cc..a158caa29 100644 --- a/ssh/tailssh/monitor.go +++ b/ssh/tailssh/monitor.go @@ -19,9 +19,9 @@ // localUser, is fixed in argv at spawn. Only the event loop touches // the RPC channel, the child table, and file descriptors. // -// RPC EOF or an external SIGHUP tears the connection down. Every child -// group is SIGHUPed, then a bounded reap sweep runs, and surviving -// groups are SIGKILLed before the monitor exits. +// Graceful close preserves session children unless termination is required. +// RPC loss and external SIGHUP terminate all children. Forwarding children +// always terminate. package tailssh @@ -53,8 +53,7 @@ const ( // result. On expiry the child's group is SIGKILLed. monFwdOpDeadline = 10 * time.Second - // monTeardownReap bounds each reap phase in teardown. The monitor - // stops waiting after this interval even if children remain. + // monTeardownReap bounds the teardown grace period and reap wait. monTeardownReap = 2 * time.Second ) @@ -67,6 +66,24 @@ type monChild struct { pgid int // the child's process group. Equal to its pid. id int64 // exec request ID, or zero for a forwarding child oneshot bool // dialer or listener child. Outcome carried by the op reply. + + // killAt is the SIGKILL deadline. While nonzero, the leader remains + // unreaped to prevent PID and process-group reuse. + killAt time.Time +} + +// beginTermination sends SIGHUP and sets the SIGKILL deadline once. +func (c *monChild) beginTermination(grace time.Duration) { + if c.killAt.IsZero() { + c.killAt = time.Now().Add(grace) + _ = killGroup(c.pgid, unix.SIGHUP) + } +} + +// kill sends SIGKILL and permits reaping the leader. +func (c *monChild) kill() { + _ = killGroup(c.pgid, unix.SIGKILL) + c.killAt = time.Time{} } // monitor is the running ssh-monitor process state, owned entirely by @@ -78,6 +95,12 @@ type monitor struct { hup chan os.Signal broken bool // a reply or notification write failed. Leave the loop. + // killAll requires teardown to terminate all session children. + killAll bool + + // gracefulClose records receipt of an explicit close request. + gracefulClose bool + // 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 @@ -268,13 +291,34 @@ func (m *monitor) loop() error { signal.Notify(sigchld, syscall.SIGCHLD) defer signal.Stop(sigchld) + escalation := time.NewTimer(time.Hour) + defer escalation.Stop() for { + escalation.Stop() + var next time.Time + for _, c := range m.children { + if !c.killAt.IsZero() && (next.IsZero() || c.killAt.Before(next)) { + next = c.killAt + } + } + var escalate <-chan time.Time + if !next.IsZero() { + escalation.Reset(time.Until(next)) + escalate = escalation.C + } select { + case <-escalate: + for _, c := range m.children { + if !c.killAt.IsZero() && !time.Now().Before(c.killAt) { + c.kill() + } + } + m.sweep(m.children, true) case <-m.hup: m.teardown() return nil case <-sigchld: - m.sweep(true) + m.sweep(m.children, true) case ev := <-events: if ev.err != nil { // EOF, an I/O error, or a protocol error means the @@ -283,7 +327,7 @@ func (m *monitor) loop() error { return nil } m.handle(ev.f, ev.fds) - if m.broken { + if m.broken || m.gracefulClose { m.teardown() return nil } @@ -308,6 +352,16 @@ func (m *monitor) handle(f rpcFrame, fds []int) { case opSignal: closeFds(fds) m.handleSignal(f) + case opTerminate: + closeFds(fds) + m.handleTerminate(f) + case opClose: + closeFds(fds) + m.gracefulClose = true + m.reply(rpcOKReply(f.ID, opClose)) + case opKillAll: + closeFds(fds) + m.handleKillAll(f) case opFdAck: closeFds(fds) if fds, ok := m.pendingFds[f.ID]; ok { @@ -512,6 +566,21 @@ func (m *monitor) handleSignal(f rpcFrame) { m.reply(rpcOKReply(f.ID, opSignal)) } +// handleTerminate schedules group termination before acknowledging the request. +func (m *monitor) handleTerminate(f rpcFrame) { + c, ok := m.children[f.Pid] + if !ok || f.ChildID == 0 || c.id != f.ChildID { + m.reply(rpcErrReply(f.ID, opTerminate, fmt.Errorf("terminate: stale child handle"))) + return + } + if f.Grace <= 0 { + m.reply(rpcErrReply(f.ID, opTerminate, fmt.Errorf("terminate: invalid grace period"))) + return + } + c.beginTermination(f.Grace) + m.reply(rpcOKReply(f.ID, opTerminate)) +} + // killGroup signals the process group pgid with kill(-pgid, sig), so // a child's descendants, such as a shell's subprocesses, die with it. func killGroup(pgid int, sig unix.Signal) error { @@ -661,22 +730,26 @@ func (m *monitor) replyFD(f rpcFrame, fds ...int) { m.pendingFds[f.ID] = fds } -// sweep reaps exited children with wait4(WNOHANG) and drops them from -// the child table. With notify set, it emits one unsolicited exit -// notification per reaped pid. -func (m *monitor) sweep(notify bool) { - for pid, c := range m.children { +// 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) { + for pid, c := range children { + if !c.killAt.IsZero() { + continue // Retain the leader until group SIGKILL. + } var ws unix.WaitStatus wpid, err := unix.Wait4(pid, &ws, unix.WNOHANG, nil) switch { case err != nil: // ECHILD means not our child or already reaped. Forget it // either way. + delete(children, pid) delete(m.children, pid) case wpid == pid: if notify && !c.oneshot { m.notifyExit(monitorProcess{PID: pid, ID: c.id}, monExitCode(ws)) } + delete(children, pid) delete(m.children, pid) } // wpid == 0: still running. @@ -726,50 +799,47 @@ func (m *monitor) notifyExit(child monitorProcess, code int) { m.reply(rpcExitNotify(child, code)) } -// teardown is the monitor's orderly exit path, reached from RPC EOF, a -// protocol error, or an external SIGHUP. It SIGHUPs every child group, -// runs a brief bounded reap sweep, then SIGKILLs every group that -// survived the HUP and reaps again. A session-level escalation timer -// in sessmonitor.go, when one was scheduled, fails its Signal against -// this closed RPC channel, so the monitor's own teardown performs the -// SIGKILL. Children that survive even the SIGKILL are abandoned in -// their own groups. +// handleKillAll requires connection-wide termination at teardown. +func (m *monitor) handleKillAll(f rpcFrame) { + m.killAll = true + m.reply(rpcOKReply(f.ID, opKillAll)) +} + +// teardown sends SIGHUP, waits for the grace period, then sends SIGKILL and reaps. +// Graceful close targets forwarding children and sessions with pending termination. +// RPC loss, external SIGHUP, and revocation target all children. +// Leaders remain unreaped until SIGKILL to prevent PID and process-group reuse. func (m *monitor) teardown() { // Close descriptors whose receipt has not been acknowledged. for id, fds := range m.pendingFds { closeFds(fds) delete(m.pendingFds, id) } - // Snapshot the pgid set at teardown entry. A group member can - // outlive its reaped leader, so the SIGKILL pass keys on this - // remembered set rather than on surviving table entries. - pgids := make(map[int]struct{}, len(m.children)) - for _, c := range m.children { - pgids[c.pgid] = struct{}{} - } - for _, c := range m.children { - // ESRCH means already gone and the like. Nothing to do. - _ = killGroup(c.pgid, unix.SIGHUP) - } - deadline := time.Now().Add(monTeardownReap) - for len(m.children) > 0 && time.Now().Before(deadline) { - // Silent sweep. The peer is gone or going, so notifications - // have nowhere to go. - m.sweep(false) - if len(m.children) > 0 { - time.Sleep(20 * time.Millisecond) + toKill := make(map[int]*monChild, len(m.children)) + killAll := !m.gracefulClose || m.broken || m.killAll + for pid, c := range m.children { + if killAll || c.id == 0 || !c.killAt.IsZero() { + toKill[pid] = c } } - if len(pgids) > 0 { - // Kill surviving group members even if their leader has exited, - // then wait for children to exit for at most monTeardownReap. - for pgid := range pgids { - _ = killGroup(pgid, unix.SIGKILL) + if len(toKill) > 0 { + deadline := time.Now().Add(monTeardownReap) + for _, c := range toKill { + c.beginTermination(monTeardownReap) + if c.killAt.Before(deadline) { + deadline = c.killAt + } + } + // Allow SIGHUP handlers to run before SIGKILL. Keep leaders + // unreaped during the grace period to reserve their process groups. + time.Sleep(time.Until(deadline)) + for _, c := range toKill { + c.kill() } deadline = time.Now().Add(monTeardownReap) - for len(m.children) > 0 && time.Now().Before(deadline) { - m.sweep(false) - if len(m.children) > 0 { + for len(toKill) > 0 && time.Now().Before(deadline) { + m.sweep(toKill, false) + if len(toKill) > 0 { time.Sleep(20 * time.Millisecond) } } diff --git a/ssh/tailssh/monitor_client.go b/ssh/tailssh/monitor_client.go index 3bae5733c..af4e773eb 100644 --- a/ssh/tailssh/monitor_client.go +++ b/ssh/tailssh/monitor_client.go @@ -90,6 +90,7 @@ type monitorClient struct { // writeMu serializes writeFrame, so the client has one logical // writer. writeMu sync.Mutex + closeMu sync.Mutex // serializes Close mu sync.Mutex // guards the fields below nextID int64 @@ -318,6 +319,28 @@ func (mc *monitorClient) Signal(ctx context.Context, child monitorProcess, sig s return err } +// Terminate sends SIGHUP to child's group and schedules SIGKILL after grace. +// Escalation continues after leader exit or graceful close. +func (mc *monitorClient) Terminate(ctx context.Context, child monitorProcess, grace time.Duration) error { + r, _, err := mc.call(ctx, rpcTerminateReq(child, grace)) + if err != nil && r.Op == "" { + // Require connection-wide termination if the request was not acknowledged. + mc.c.Close() + } + return err +} + +// KillAll requires teardown to terminate all session children. +// Call it before [monitorClient.Close] when access is revoked. +func (mc *monitorClient) KillAll(ctx context.Context) error { + _, _, err := mc.call(ctx, rpcKillAllReq(0)) + if err != nil { + // Require connection-wide termination if revocation was not acknowledged. + mc.c.Close() + } + return err +} + // Dial dials a unix socket through a relay child running with the // connection's bound identity. The returned data socket and lifetime pipe // are acknowledged to the monitor on receipt, releasing its held copies. @@ -435,19 +458,26 @@ func wrapListenerFD(fd int, name string) (net.Listener, error) { return ln, nil } -// Close tears the connection down by closing the RPC channel, which -// triggers the monitor's teardown. Close waits for the monitor to -// exit. A wedged monitor is killed after the forwarding-op deadline, -// both teardown reap sweeps, and a margin for scheduling and child reap. +// Close requests graceful teardown and waits for the monitor to exit. +// RPC loss without a graceful close request terminates all children. +// A monitor that exceeds the shutdown timeout is killed. func (mc *monitorClient) Close() error { + mc.closeMu.Lock() + defer mc.closeMu.Unlock() mc.mu.Lock() if mc.closed { mc.mu.Unlock() return nil } - mc.closed = true mc.mu.Unlock() + ctx, cancel := context.WithTimeout(context.Background(), monFwdOpDeadline) + // RPC loss without this request requires connection-wide termination. + _, _, _ = mc.call(ctx, rpcFrame{Op: opClose}) + cancel() + mc.mu.Lock() + mc.closed = true + mc.mu.Unlock() mc.c.Close() <-mc.done waitErr := make(chan error, 1) diff --git a/ssh/tailssh/monitor_lifecycle_test.go b/ssh/tailssh/monitor_lifecycle_test.go index 9f2be5cc0..f853df809 100644 --- a/ssh/tailssh/monitor_lifecycle_test.go +++ b/ssh/tailssh/monitor_lifecycle_test.go @@ -15,9 +15,11 @@ import ( "time" ) -// TestMonitorExecCancellationAfterDispatch delays the exec reply until after -// cancellation. The session must retain the child handle and terminate it. -func TestMonitorExecCancellationAfterDispatch(t *testing.T) { +// newTestMonitorClient connects a monitorClient to a fake RPC peer. +// Cleanup closes the socket and waits for the read loop. +// The client has no child process and cannot use [monitorClient.Close]. +func newTestMonitorClient(t *testing.T) (*monitorClient, *rpcConn) { + t.Helper() client, peer := rpcTestPair(t) mc := &monitorClient{ c: client.c, @@ -30,6 +32,13 @@ func TestMonitorExecCancellationAfterDispatch(t *testing.T) { client.c.Close() <-mc.done }) + return mc, peer +} + +// TestMonitorExecCancellationAfterDispatch delays the exec reply until after +// cancellation. The session must retain the child handle and terminate it. +func TestMonitorExecCancellationAfterDispatch(t *testing.T) { + mc, peer := newTestMonitorClient(t) c := &conn{srv: &server{logf: t.Logf}} c.monitor.mon = mc mc.SetExitCallback(c.monitor.exits.dispatchExit) @@ -73,16 +82,16 @@ func TestMonitorExecCancellationAfterDispatch(t *testing.T) { } hungup := make(chan bool, 1) - go func() { hungup <- ss.hangupMonitorProcess() }() + go func() { hungup <- ss.hangupMonitorProcess(true) }() frame, fds, err = peer.readFrame() closeFds(fds) if err != nil { t.Fatal(err) } - if frame.Op != opSignal || frame.Pid != child.PID || frame.ChildID != child.ID || frame.Sig != "SIGHUP" { + if frame.Op != opTerminate || frame.Pid != child.PID || frame.ChildID != child.ID || frame.Grace <= 0 { t.Fatalf("hangup frame=%+v", frame) } - if err := peer.writeFrame(rpcOKReply(frame.ID, opSignal)); err != nil { + if err := peer.writeFrame(rpcOKReply(frame.ID, opTerminate)); err != nil { t.Fatal(err) } if !<-hungup { @@ -96,8 +105,7 @@ func TestMonitorExecCancellationAfterDispatch(t *testing.T) { case <-time.After(5 * time.Second): t.Fatal("exit notification not delivered") } - // Escalation must neither consume the result nor send another signal. - ss.escalateMonitorProcess(mc) + // Each wait must return the same exit status. for range 2 { code, ok, err := ss.waitMonitorProcess() if code != 129 || !ok || err != nil { @@ -106,6 +114,46 @@ func TestMonitorExecCancellationAfterDispatch(t *testing.T) { } } +// TestMonitorPolicyCancellationWaitsForCommit checks that cancellation is +// published only after the monitor acknowledges termination. +func TestMonitorPolicyCancellationWaitsForCommit(t *testing.T) { + mc, peer := newTestMonitorClient(t) + c := &conn{} + c.monitor.mon = mc + ctx, cancel := context.WithCancelCause(context.Background()) + defer cancel(nil) + ss := &sshSession{conn: c, ctx: ctx, cancelCtx: cancel, logf: t.Logf, + osSessionState: osSessionState{monChild: monitorProcess{PID: 42, ID: 1}}, + } + finished := make(chan struct{}) + go func() { + ss.cancelWithTermination(userVisibleError{msg: "policy termination", error: context.DeadlineExceeded}) + close(finished) + }() + frame, fds, err := peer.readFrame() + closeFds(fds) + if err != nil { + t.Fatal(err) + } + if frame.Op != opTerminate || frame.Pid != 42 || frame.ChildID != 1 { + t.Fatalf("termination frame = %+v", frame) + } + if ctx.Err() != nil { + t.Fatal("cancellation published before monitor acknowledgment") + } + if err := peer.writeFrame(rpcOKReply(frame.ID, opTerminate)); err != nil { + t.Fatal(err) + } + select { + case <-finished: + case <-time.After(5 * time.Second): + t.Fatal("policy cancellation did not finish") + } + if _, ok := context.Cause(ctx).(SSHTerminationError); !ok { + t.Fatalf("cancellation cause = %v; want SSHTerminationError", context.Cause(ctx)) + } +} + // A locally rejected request must not kill other sessions on the connection. func TestMonitorValidationFailureKeepsChannel(t *testing.T) { for _, tt := range []struct { @@ -160,26 +208,15 @@ func TestMonitorWriteFailureClosesChannel(t *testing.T) { name = "partial_write" } t.Run(name, func(t *testing.T) { - client, peer := rpcTestPair(t) - mc := &monitorClient{ - c: client.c, - rpc: client, - pending: make(map[int64]chan *rpcResult), - done: make(chan struct{}), - } - go mc.readLoop() - t.Cleanup(func() { - client.c.Close() - <-mc.done - }) + mc, peer := newTestMonitorClient(t) frame := rpcPingReq(0) if partial { - if err := client.c.SetWriteBuffer(1024); err != nil { + if err := mc.c.SetWriteBuffer(1024); err != nil { t.Fatal(err) } - client.writeTimeout = 100 * time.Millisecond + mc.rpc.writeTimeout = 100 * time.Millisecond frame = rpcExecReq(0, []string{strings.Repeat("x", 100<<10)}, nil, "", false, false, 0) - } else if err := client.c.CloseWrite(); err != nil { + } else if err := mc.c.CloseWrite(); err != nil { t.Fatal(err) } if _, _, err := mc.call(mustCtx(t), frame); err == nil { @@ -206,18 +243,7 @@ func TestMonitorWriteFailureClosesChannel(t *testing.T) { } func TestMonitorReadFailureClosesChannel(t *testing.T) { - client, peer := rpcTestPair(t) - mc := &monitorClient{ - c: client.c, - rpc: client, - pending: make(map[int64]chan *rpcResult), - done: make(chan struct{}), - } - go mc.readLoop() - t.Cleanup(func() { - client.c.Close() - <-mc.done - }) + mc, peer := newTestMonitorClient(t) if _, err := peer.c.Write([]byte("invalid JSON\n")); err != nil { t.Fatal(err) } diff --git a/ssh/tailssh/monitor_linux.go b/ssh/tailssh/monitor_linux.go index 280e828a2..73eb990de 100644 --- a/ssh/tailssh/monitor_linux.go +++ b/ssh/tailssh/monitor_linux.go @@ -12,16 +12,15 @@ import ( "golang.org/x/sys/unix" ) -// monChildAttr returns the SysProcAttr for one monitor child. A ctty -// 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. +// monChildAttr returns process attributes for a session child. +// With ctty, the child starts a session with fd 0 as its controlling terminal. +// Otherwise it starts a process group. +// Pdeathsig is unset so the child can survive monitor exit. func monChildAttr(ctty bool) *syscall.SysProcAttr { return &syscall.SysProcAttr{ - Setpgid: !ctty, - Setsid: ctty, - Setctty: ctty, - Pdeathsig: unix.SIGHUP, + Setpgid: !ctty, + Setsid: ctty, + Setctty: ctty, } } @@ -37,11 +36,9 @@ func scrubFds() error { return scrubFdsByScan("/proc/self/fd") } -// fwdChildAttr returns the SysProcAttr for a one-shot forwarding child -// whose identity must be applied, that is a root monitor's child. The -// Credential carries the connection's bound identity from ma. The child -// leads its own group so the op deadline and teardown can kill the -// whole group, and Pdeathsig is set as in monChildAttr. +// fwdChildAttr returns process attributes for a forwarding child. +// The child runs with ma's credentials in its own process group. +// Pdeathsig sends SIGHUP when the creating thread exits. See golang/go#27505. func fwdChildAttr(ma monitorArgs) *syscall.SysProcAttr { return &syscall.SysProcAttr{ Credential: &syscall.Credential{ diff --git a/ssh/tailssh/monitor_rpc.go b/ssh/tailssh/monitor_rpc.go index ca1174082..84d8b399f 100644 --- a/ssh/tailssh/monitor_rpc.go +++ b/ssh/tailssh/monitor_rpc.go @@ -51,13 +51,16 @@ import ( // Monitor RPC operations. const ( - opDial = "dial" // request {net:"unix"|"tcp", addr}. reply {ok} + socket (and lifetime pipe writer for unix) - opListen = "listen" // request {net:"unix"|"tcp", addr, unlink?, agent?}. reply {ok, path} + listener fd - opExec = "exec" // request {argv, env, dir?, ctty?, envfd?, fds:0-4} + SCM_RIGHTS fds. reply {ok, pid, childID} - opSignal = "signal" // request {pid, childID, sig}. reply {ok} - opPing = "ping" // request {}. reply {ok} - opExit = "exit" // unsolicited notification {pid, childID, code}. no request ID - opFdAck = "fdack" // request {id of the reply whose descriptors were received}. no fds, no reply + opDial = "dial" // request {net:"unix"|"tcp", addr}. reply {ok} + socket (and lifetime pipe writer for unix) + opListen = "listen" // request {net:"unix"|"tcp", addr, unlink?, agent?}. reply {ok, path} + listener fd + opExec = "exec" // request {argv, env, dir?, ctty?, envfd?, fds:0-4} + SCM_RIGHTS fds. reply {ok, pid, childID} + opSignal = "signal" // request {pid, childID, sig}. reply {ok} + opTerminate = "terminate" // request {pid, childID, grace}. reply {ok}. Schedule group termination + opClose = "close" // request {}. reply {ok}. Graceful teardown + opPing = "ping" // request {}. reply {ok} + opKillAll = "killall" // request {}. reply {ok}. Terminate all session children at teardown + opExit = "exit" // unsolicited notification {pid, childID, code}. no request ID + opFdAck = "fdack" // request {id of the reply whose descriptors were received}. no fds, no reply ) const ( @@ -125,11 +128,12 @@ type rpcFrame struct { // this flag is not a privilege boundary against tailscaled. Incubator bool `json:"incubator,omitzero"` - // signal request, exit notification, and exec reply. - Pid int `json:"pid,omitzero"` - ChildID int64 `json:"childID,omitzero"` // exec request ID; required for signals - Sig string `json:"sig,omitempty"` - Code int `json:"code,omitzero"` // exit notification only + // Signal and terminate requests, exit notifications, and exec replies. + Pid int `json:"pid,omitzero"` + ChildID int64 `json:"childID,omitzero"` // exec request ID; required for signals + Sig string `json:"sig,omitempty"` + Code int `json:"code,omitzero"` // exit notification only + Grace time.Duration `json:"grace,omitzero"` // HUP-to-KILL delay for terminate // Reply fields. OK bool `json:"ok,omitzero"` @@ -141,6 +145,10 @@ func rpcPingReq(id int64) rpcFrame { return rpcFrame{ID: id, Op: opPing} } +func rpcKillAllReq(id int64) rpcFrame { + return rpcFrame{ID: id, Op: opKillAll} +} + func rpcDialReq(id int64, network, addr string) rpcFrame { return rpcFrame{ID: id, Op: opDial, Net: network, Addr: addr} } @@ -153,6 +161,10 @@ func rpcExecReq(id int64, argv, env []string, dir string, ctty, envFd bool, nfds return rpcFrame{ID: id, Op: opExec, Argv: argv, Env: env, Dir: dir, Ctty: ctty, EnvFd: envFd, Fds: nfds} } +func rpcTerminateReq(child monitorProcess, grace time.Duration) rpcFrame { + return rpcFrame{Op: opTerminate, Pid: child.PID, ChildID: child.ID, Grace: grace} +} + func rpcSignalReq(id int64, child monitorProcess, sig string) rpcFrame { return rpcFrame{ID: id, Op: opSignal, Pid: child.PID, ChildID: child.ID, Sig: sig} } diff --git a/ssh/tailssh/monitor_teardown_linux_test.go b/ssh/tailssh/monitor_teardown_linux_test.go new file mode 100644 index 000000000..7a7216086 --- /dev/null +++ b/ssh/tailssh/monitor_teardown_linux_test.go @@ -0,0 +1,85 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build linux && !android + +package tailssh + +import ( + "bufio" + "fmt" + "os" + "strconv" + "strings" + "testing" + "time" + + "golang.org/x/sys/unix" + "tailscale.com/tstest" +) + +// TestMonitorTeardownPinsLeadersUntilSIGKILL checks that RPC loss keeps +// exited leaders unreaped until group SIGKILL. +func TestMonitorTeardownPinsLeadersUntilSIGKILL(t *testing.T) { + mc := startTestMonitor(t, os.Getuid(), os.Getgid(), testGroups(t)) + null, err := os.OpenFile(os.DevNull, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + defer null.Close() + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer r.Close() + defer w.Close() + immune, err := mc.Exec(mustCtx(t), []string{"/bin/sh", "-c", "trap '' HUP; echo ready; exec sleep 300"}, nil, "/", false, nil, null, w, null) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = unix.Kill(-immune.PID, unix.SIGKILL) }) + w.Close() + r.SetReadDeadline(time.Now().Add(5 * time.Second)) + if line, err := bufio.NewReader(r).ReadString('\n'); err != nil || line != "ready\n" { + t.Fatalf("ready = %q, %v", line, err) + } + leader, err := mc.Exec(mustCtx(t), []string{"/bin/sleep", "300"}, nil, "/", false, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = unix.Kill(-leader.PID, unix.SIGKILL) }) + // Trigger teardown without a termination request. + if err := mc.c.CloseWrite(); err != nil { + t.Fatal(err) + } + checkPinned := func() error { + b, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", leader.PID)) + if err != nil { + return fmt.Errorf("leader was reaped before SIGKILL: %w", err) + } + fields := strings.Fields(string(b)[strings.LastIndexByte(string(b), ')')+1:]) + if len(fields) < 2 || fields[0] != "Z" || fields[1] != strconv.Itoa(mc.Pid()) { + return fmt.Errorf("leader is not yet a zombie pinned by the monitor: %s", b) + } + return nil + } + if err := tstest.WaitFor(monTeardownReap/4, checkPinned); err != nil { + t.Fatal(err) + } + // Check leader retention after half the grace period. + time.Sleep(monTeardownReap / 2) + if err := checkPinned(); err != nil { + t.Fatal(err) + } + if pidGone(immune.PID) { + t.Fatal("HUP-immune sibling exited before escalation") + } + if err := mc.Close(); err != nil { + t.Fatal(err) + } + for _, child := range []monitorProcess{leader, immune} { + if !pidGone(child.PID) { + t.Errorf("child %d survived teardown", child.PID) + } + } +} diff --git a/ssh/tailssh/monitor_termination_test.go b/ssh/tailssh/monitor_termination_test.go new file mode 100644 index 000000000..e091c1aad --- /dev/null +++ b/ssh/tailssh/monitor_termination_test.go @@ -0,0 +1,76 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build (linux && !android) || (darwin && !ios) + +package tailssh + +import ( + "bufio" + "context" + "fmt" + "os" + "testing" + "time" + + "golang.org/x/sys/unix" + "tailscale.com/tstest" +) + +func TestMonitorTerminationRPCFailureFailsClosed(t *testing.T) { + for _, mode := range []string{"kill-all", "terminate", "unrequested-eof"} { + t.Run(mode, func(t *testing.T) { + mc := startTestMonitor(t, os.Getuid(), os.Getgid(), testGroups(t)) + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer r.Close() + defer w.Close() + null, err := os.OpenFile(os.DevNull, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + defer null.Close() + child, err := mc.Exec(mustCtx(t), []string{"/bin/sh", "-c", "trap '' HUP; echo ready; while :; do sleep 1; done"}, nil, "/", false, nil, null, w, null) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = unix.Kill(-child.PID, unix.SIGKILL) }) + w.Close() + r.SetReadDeadline(time.Now().Add(5 * time.Second)) + if line, err := bufio.NewReader(r).ReadString('\n'); err != nil || line != "ready\n" { + t.Fatalf("ready = %q, %v", line, err) + } + if mode == "unrequested-eof" { + mc.c.Close() + } else { + // Fail the next termination request's write. + if err := mc.c.CloseWrite(); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + if mode == "kill-all" { + err = mc.KillAll(ctx) + } else { + err = mc.Terminate(ctx, child, hangupEscalation) + } + if err == nil { + t.Fatal("mandate unexpectedly succeeded on broken RPC") + } + } + if err := mc.Close(); err != nil { + t.Fatal(err) + } + if err := tstest.WaitFor(5*time.Second, func() error { + if !pidGone(child.PID) { + return fmt.Errorf("child %d survived failed mandate", child.PID) + } + return nil + }); err != nil { + t.Fatal(err) + } + }) + } +} diff --git a/ssh/tailssh/monitor_test.go b/ssh/tailssh/monitor_test.go index 8b6d092e7..fff020f3f 100644 --- a/ssh/tailssh/monitor_test.go +++ b/ssh/tailssh/monitor_test.go @@ -552,9 +552,7 @@ func TestMonitorBadExec(t *testing.T) { } } -// TestMonitorTeardown closes the client and asserts the teardown path. -// The monitor exits promptly, through EOF, group SIGHUP, reaping, -// SIGKILL of survivors, and exit 0. Its children die with it. +// TestMonitorTeardown checks that KillAll followed by Close terminates children. func TestMonitorTeardown(t *testing.T) { mc := startTestMonitor(t, os.Getuid(), os.Getgid(), testGroups(t)) exits := collectExits(mc) @@ -563,13 +561,17 @@ func TestMonitorTeardown(t *testing.T) { if err != nil { t.Fatalf("exec sleep: %v", err) } + if err := mc.KillAll(mustCtx(t)); err != nil { + t.Fatal(err) + } start := time.Now() if err := mc.Close(); err != nil { t.Fatalf("close: monitor did not exit cleanly: %v", err) } - if d := time.Since(start); d > 2*time.Second { - t.Errorf("monitor teardown took %v, want < 2s", d) + // Allow one grace period, one reap period, and scheduling slack. + if d := time.Since(start); d > 2*monTeardownReap+time.Second { + t.Errorf("monitor teardown took %v, want at most %v", d, 2*monTeardownReap+time.Second) } // The sleep child must be dead. The monitor was its parent, so it is diff --git a/ssh/tailssh/monitor_watchdog_linux_test.go b/ssh/tailssh/monitor_watchdog_linux_test.go index 001db57ed..ca1e0ec3f 100644 --- a/ssh/tailssh/monitor_watchdog_linux_test.go +++ b/ssh/tailssh/monitor_watchdog_linux_test.go @@ -76,6 +76,11 @@ func TestMonitorCloseWatchdogForwardChild(t *testing.T) { }() start := time.Now() + kctx, kcancel := context.WithTimeout(context.Background(), 16*time.Second) + if err := mc.KillAll(kctx); err != nil { + t.Errorf("arming kill-all: %v", err) + } + kcancel() err = mc.Close() t.Logf("Close duration=%v error=%v; session=%d forward=%d", time.Since(start), err, session.PID, forwardPID) if err != nil { diff --git a/ssh/tailssh/process_state_darwin_test.go b/ssh/tailssh/process_state_darwin_test.go new file mode 100644 index 000000000..7a0932b6b --- /dev/null +++ b/ssh/tailssh/process_state_darwin_test.go @@ -0,0 +1,18 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build darwin && !ios + +package tailssh + +import "golang.org/x/sys/unix" + +// pidGone reports whether pid is absent or a zombie. +func pidGone(pid int) bool { + const szomb = 5 // SZOMB in . + procs, err := unix.SysctlKinfoProcSlice("kern.proc.pid", pid) + if err != nil { + return unix.Kill(pid, 0) == unix.ESRCH + } + return len(procs) == 0 || procs[0].Proc.P_stat == szomb +} diff --git a/ssh/tailssh/process_state_linux_test.go b/ssh/tailssh/process_state_linux_test.go new file mode 100644 index 000000000..2034366ea --- /dev/null +++ b/ssh/tailssh/process_state_linux_test.go @@ -0,0 +1,28 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build linux && !android + +package tailssh + +import ( + "bytes" + "fmt" + "os" + + "golang.org/x/sys/unix" +) + +// pidGone reports whether pid is absent or a zombie. +func pidGone(pid int) bool { + b, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)) + if err != nil { + return unix.Kill(pid, 0) == unix.ESRCH + } + // The comm field may contain spaces and parentheses. + i := bytes.LastIndexByte(b, ')') + if i < 0 || i+2 >= len(b) { + return false + } + return b[i+2] == 'Z' +} diff --git a/ssh/tailssh/process_unix.go b/ssh/tailssh/process_unix.go index a7e9ecaf9..70df04bca 100644 --- a/ssh/tailssh/process_unix.go +++ b/ssh/tailssh/process_unix.go @@ -109,14 +109,19 @@ func (ss *sshSession) waitProcess() (exitCode int, err error) { return 1, err } -// hangupProcess closes the PTY or sends SIGHUP, then schedules SIGKILL -// if the session process has not exited. -func (ss *sshSession) hangupProcess() { +// hangupProcess closes the PTY. If mandated is true, it also sends SIGHUP +// and schedules SIGKILL. Otherwise it sends no explicit signals. +func (ss *sshSession) hangupProcess(mandated bool) { + // Register termination before PTY closure can send SIGHUP. + monitored := ss.hangupMonitorProcess(mandated) if ss.ptyReq != nil { // Close every PTY master descriptor so the terminal driver sends SIGHUP. closeAll(ss.wrStdin, ss.rdStdout, ss.ptyResize) + if !mandated { + return + } } - if ss.hangupMonitorProcess() { + if monitored { return } if ss.cmd == nil || ss.cmd.Process == nil { @@ -124,6 +129,9 @@ func (ss *sshSession) hangupProcess() { } p := ss.cmd.Process // The process handle synchronizes signaling with exit and reaping. + if !mandated { + return + } if ss.ptyReq == nil { p.Signal(syscall.SIGHUP) } diff --git a/ssh/tailssh/session_termination_test.go b/ssh/tailssh/session_termination_test.go new file mode 100644 index 000000000..57107c867 --- /dev/null +++ b/ssh/tailssh/session_termination_test.go @@ -0,0 +1,158 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build (linux && !android) || (darwin && !ios) + +package tailssh + +import ( + "bufio" + "fmt" + "io" + "net/http" + "net/netip" + "strconv" + "strings" + "sync" + "testing" + "time" + + gliderssh "github.com/tailscale/gliderssh" + gossh "golang.org/x/crypto/ssh" + "golang.org/x/sys/unix" + "tailscale.com/tailcfg" + "tailscale.com/tstest" +) + +// TestSessionMonitorMandatedTerminationThenDisconnect checks that duration +// and recording failures terminate the target after an immediate disconnect +// while preserving unrelated jobs. +func TestSessionMonitorMandatedTerminationThenDisconnect(t *testing.T) { + for _, mode := range []string{"duration", "recording"} { + t.Run(mode, func(t *testing.T) { + action := &tailcfg.SSHAction{Accept: true} + message := "Session timeout" + release := func() {} + if mode == "duration" { + action.SessionDuration = 2 * time.Second + } else { + message = "recording failed" + released := make(chan struct{}) + release = sync.OnceFunc(func() { close(released) }) + // Release the upload before waiting for recorder handlers during cleanup. + recorder := mockRecordingServer(t, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + w.(http.Flusher).Flush() + if _, err := bufio.NewReader(r.Body).ReadBytes('\n'); err != nil { + return + } + <-released + io.WriteString(w, "{invalid ack}\n") + w.(http.Flusher).Flush() + }) + t.Cleanup(release) + action.Recorders = []netip.AddrPort{netip.MustParseAddrPort(recorder.Listener.Addr().String())} + action.OnRecordingFailure = &tailcfg.SSHRecorderFailureAction{TerminateSessionWithMessage: message} + } + connCh := make(chan *conn, 1) + addr := newMonitorSessionServerFor(t, nil, nil, &tailcfg.SSHRule{ + SSHUsers: map[string]string{}, + Action: action, + }, false, func(c *conn, s gliderssh.Session) { + connCh <- c + c.newSSHSession(s).run() + }) + cl, err := gossh.Dial("tcp", addr, &gossh.ClientConfig{ + HostKeyCallback: gossh.InsecureIgnoreHostKey(), + Timeout: 10 * time.Second, + }) + if err != nil { + t.Fatal(err) + } + defer cl.Close() + s, err := cl.NewSession() + if err != nil { + t.Fatal(err) + } + defer s.Close() + stdout, err := s.StdoutPipe() + if err != nil { + t.Fatal(err) + } + stderr, err := s.StderrPipe() + if err != nil { + t.Fatal(err) + } + if err := s.Start("trap '' HUP; echo $$; exec sleep 300"); err != nil { + t.Fatal(err) + } + targetCh := make(chan int, 1) + go func() { + line, _ := bufio.NewReader(stdout).ReadString('\n') + pid, _ := strconv.Atoi(strings.TrimSpace(line)) + targetCh <- pid + }() + var target int + select { + case target = <-targetCh: + if target <= 1 { + t.Fatalf("invalid target PID %d", target) + } + case <-time.After(10 * time.Second): + t.Fatal("session did not start") + } + c := <-connCh + mc := c.connMonitorIfAny() + if mc == nil { + t.Fatal("session has no monitor") + } + // The unrelated job uses default SIGHUP handling. + sibling, err := mc.Exec(mustCtx(t), []string{"/bin/sleep", "300"}, nil, "/", false, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _ = unix.Kill(-sibling.PID, unix.SIGKILL) + _ = unix.Kill(-target, unix.SIGKILL) + }) + messageCh := make(chan bool, 1) + go func() { + r := bufio.NewReader(stderr) + for { + line, err := r.ReadString('\n') + if strings.Contains(line, message) { + messageCh <- true + return + } + if err != nil { + messageCh <- false + return + } + } + }() + release() + select { + case ok := <-messageCh: + if !ok { + t.Fatal("session ended without its termination message") + } + case <-time.After(10 * time.Second): + t.Fatal("termination message did not arrive") + } + cl.Close() + c.closeConnMonitor() + if err := tstest.WaitFor(5*time.Second, func() error { + if !pidGone(target) { + return fmt.Errorf("mandated target %d survived disconnect", target) + } + return nil + }); err != nil { + t.Fatal(err) + } + time.Sleep(200 * time.Millisecond) + if pidGone(sibling.PID) { + t.Fatalf("unrelated job %d killed on graceful close", sibling.PID) + } + }) + } +} diff --git a/ssh/tailssh/sessmonitor.go b/ssh/tailssh/sessmonitor.go index ac35d5628..98520d93e 100644 --- a/ssh/tailssh/sessmonitor.go +++ b/ssh/tailssh/sessmonitor.go @@ -75,6 +75,8 @@ func (s *monExitStatus) complete(code int) { // After dispatch, cancellation does not abandon the exec reply: a successful // launch always registers the child so run can terminate it and wait for exit. func (ss *sshSession) launchViaMonitor(cmd *exec.Cmd, envFile *os.File, stdio []*os.File, ctty bool) error { + ss.monitorLaunchMu.Lock() + defer ss.monitorLaunchMu.Unlock() if len(stdio) != 3 { return fmt.Errorf("internal error: monitor exec needs 3 stdio fds, got %d", len(stdio)) } @@ -118,38 +120,24 @@ func (ss *sshSession) waitMonitorProcess() (code int, ok bool, err error) { } } -// 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 { +// hangupMonitorProcess requests monitor termination if mandated is true. +// It returns false for directly launched sessions. See [sshSession.hangupProcess]. +func (ss *sshSession) hangupMonitorProcess(mandated bool) bool { if ss.monChild.PID == 0 { return false } mc := ss.conn.connMonitorIfAny() if mc == nil { - // Monitor teardown owns cleanup. Its reaped PIDs may already have - // been reused, so tailscaled must not signal them directly. + // Only the monitor may signal its child process groups. return true } - 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(knobDuration(sshHupEscalation(), hangupEscalation), func() { ss.escalateMonitorProcess(mc) }) - return true -} - -func (ss *sshSession) escalateMonitorProcess(mc *monitorClient) { - select { - case <-ss.monExit.done: - return - default: + if !mandated { + return true } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - if err := mc.Signal(ctx, ss.monChild, "SIGKILL"); err != nil { - ss.vlogf("ssh: SIGKILL session process group: %v", err) + if err := mc.Terminate(ctx, ss.monChild, knobDuration(sshHupEscalation(), hangupEscalation)); err != nil { + ss.logf("ssh: committing session termination: %v", err) } + return true } diff --git a/ssh/tailssh/sessmonitor_test.go b/ssh/tailssh/sessmonitor_test.go index af1ec15a5..9b2ba6c77 100644 --- a/ssh/tailssh/sessmonitor_test.go +++ b/ssh/tailssh/sessmonitor_test.go @@ -428,13 +428,10 @@ exit 3 } } -// TestSessionMonitorConnCloseKillsHupImmuneChild pins the teardown -// escalation on the conn-close paths, revocation, Shutdown, and plain -// teardown: the monitor's own teardown must SIGKILL the HUP-immune -// group, in both orderings of the session's own HUP escalation against -// the conn teardown (kick-then-close and close-without-kick). +// TestSessionMonitorConnCloseKillsHupImmuneChild checks that connection close +// kills mandated sessions and preserves other sessions, regardless of HUP handling. func TestSessionMonitorConnCloseKillsHupImmuneChild(t *testing.T) { - for _, mode := range []string{"kick-then-close", "close-without-kick"} { + for _, mode := range []string{"mandated", "graceful", "graceful-default-hup"} { t.Run(mode, func(t *testing.T) { lu := fwdTestIdentity(t) c := newFwdTestConn(t, lu, &tailcfg.SSHAction{Accept: true}) @@ -446,10 +443,12 @@ func TestSessionMonitorConnCloseKillsHupImmuneChild(t *testing.T) { logf: t.Logf, } - // An HUP-immune child, like TestSessionMonitorHangupEscalation: - // sh traps (ignores) SIGHUP, so only the group SIGKILL ends it. - // The marker gates on the trap being installed. - cmd := exec.Command("/bin/sh", "-c", "trap '' HUP; echo ready; while :; do sleep 1; done") + // Mandated termination must kill a HUP-immune child. + command := "trap '' HUP; echo ready; while :; do sleep 1; done" + if mode == "graceful-default-hup" { + command = "echo ready; exec sleep 300" + } + cmd := exec.Command("/bin/sh", "-c", command) cmd.Args = incubatorChildArgv(cmd.Args) stdin, stdinKeep, err := os.Pipe() if err != nil { @@ -483,22 +482,34 @@ func TestSessionMonitorConnCloseKillsHupImmuneChild(t *testing.T) { } pid := ss.monChild.PID - if mode == "kick-then-close" { - // The revocation kick (what killProcessOnContextDone does - // when the session ctx is canceled); its escalation timer - // races the conn teardown, which closes the monitor. - ss.hangupMonitorProcess() + if mode == "mandated" { + // Terminate this session without setting the connection-wide flag. + ss.hangupMonitorProcess(true) } - // The conn teardown: every conn-close path funnels here - // (HandleSSHConn's deferred closeConnMonitor). Close waits for - // the monitor to exit, so on return the teardown sweeps - // (HUP, then SIGKILL for survivors) have run. + // Wait for monitor teardown to finish. c.closeConnMonitor() - // The child must be dead and reaped by the monitor's own - // teardown: signal 0 returns ESRCH once the monitor has reaped - // it. Bound: the teardown's two sweeps (≤2s each) inside - // Close's 5s monitor-exit wait, plus slack. + if strings.HasPrefix(mode, "graceful") { + // Allow time for a parent-death signal before checking liveness. + // pidGone treats Linux zombies as dead. + time.Sleep(200 * time.Millisecond) + if pidGone(pid) { + t.Fatalf("child %d did not survive a graceful conn close", pid) + } + // Kill the survivor and wait for exit. + _ = unix.Kill(-pid, unix.SIGKILL) + _ = unix.Kill(pid, unix.SIGKILL) + deadline := time.Now().Add(10 * time.Second) + for !pidGone(pid) { + if time.Now().After(deadline) { + t.Fatalf("failed to clean up surviving child %d", pid) + } + time.Sleep(100 * time.Millisecond) + } + return + } + + // Teardown must kill and reap the child within its shutdown bound. deadline := time.Now().Add(monTeardownReap*2 + 5*time.Second) for { if err := unix.Kill(pid, 0); err != nil { @@ -513,12 +524,18 @@ func TestSessionMonitorConnCloseKillsHupImmuneChild(t *testing.T) { } } -// TestSessionMonitorTeardownKillsSamePgidStraggler pins the teardown -// SIGKILL's scope: a HUP-immune member of the session child's own -// process group whose leader dies to the teardown SIGHUP must be -// killed via the pgid set snapshot taken at teardown entry, not via -// surviving table entries. +// TestSessionMonitorTeardownKillsSamePgidStraggler checks that teardown kills +// HUP-immune group members after their leader exits. func TestSessionMonitorTeardownKillsSamePgidStraggler(t *testing.T) { + testSessionMonitorTerminatedStraggler(t, true) +} + +func TestSessionMonitorEscalationKillsSamePgidStraggler(t *testing.T) { + testSessionMonitorTerminatedStraggler(t, false) +} + +func testSessionMonitorTerminatedStraggler(t *testing.T, closeMonitor bool) { + t.Helper() lu := fwdTestIdentity(t) c := newFwdTestConn(t, lu, &tailcfg.SSHAction{Accept: true}) ctx, cancel := context.WithCancel(context.Background()) @@ -529,12 +546,7 @@ func TestSessionMonitorTeardownKillsSamePgidStraggler(t *testing.T) { logf: t.Logf, } - // The leader (sh) dies to the group SIGHUP. The nohup'd member of - // its group ignores HUP (nohup's SIG_IGN survives exec) and would - // survive the teardown under the entry-keyed SIGKILL: the first reap - // sweep reaps the leader and drops the table entry, so only the - // snapshot pgid set still names the group. The inner sh prints its - // own pid first so the test can watch it. + // The leader exits on HUP. Its background child ignores HUP and reports its PID. cmd := exec.Command("/bin/sh", "-c", "nohup sh -c 'echo $$; exec sleep 300' & echo ready; wait") cmd.Args = incubatorChildArgv(cmd.Args) @@ -589,19 +601,26 @@ func TestSessionMonitorTeardownKillsSamePgidStraggler(t *testing.T) { } } - // The conn teardown: closeConnMonitor runs the monitor's teardown, - // group SIGHUP (kills the leader, sweep reaps it, entry dropped), - // then the SIGKILL pass over the snapshot pgid set. - c.closeConnMonitor() + t.Cleanup(func() { _ = unix.Kill(-ss.monChild.PID, unix.SIGKILL) }) + ss.hangupMonitorProcess(true) + if closeMonitor { + c.closeConnMonitor() + } else { + // Check leader exit before timer escalation. + if err := tstest.WaitFor(time.Second, func() error { + if !pidGone(ss.monChild.PID) { + return errors.New("leader still alive") + } + return nil + }); err != nil { + t.Fatal(err) + } + if pidGone(straggler) { + t.Fatal("straggler did not survive HUP") + } + } - // The straggler must be dead and gone. Bound: the teardown's two - // sweeps (≤2s each) inside Close's 5s monitor-exit wait, plus slack. - // A killed straggler whose parent is gone can linger as a zombie - // adopted by a PID 1 that does not reap (the privileged CI - // container); kill(pid, 0) succeeds for zombies, so liveness is - // checked through the /proc state on linux, where a Z state counts - // as gone. Elsewhere the adopter reaps promptly and kill(pid, 0) - // suffices. + // Allow escalation and reap time. Orphaned Linux zombies count as dead. deadline = time.Now().Add(monTeardownReap*2 + 5*time.Second) for { if pidGone(straggler) { @@ -614,26 +633,34 @@ func TestSessionMonitorTeardownKillsSamePgidStraggler(t *testing.T) { } } -// pidGone reports whether pid no longer names a live process. On linux -// it reads /proc: a missing entry or a zombie (state Z) means gone. -// Elsewhere kill(pid, 0) is the check; the platforms in this file's -// build tag reap orphans promptly, so a lingering zombie is not -// expected there. -func pidGone(pid int) bool { - if runtime.GOOS == "linux" { - b, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)) - if err != nil { - return true // gone +func TestPIDGoneWithUnreapedChild(t *testing.T) { + cmd := exec.Command("/bin/sleep", "300") + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + cmd.Process.Kill() + cmd.Wait() + }) + pid := cmd.Process.Pid + if pidGone(pid) { + t.Fatal("live child reported dead") + } + if err := cmd.Process.Kill(); err != nil { + t.Fatal(err) + } + // Keep the child unreaped until after the liveness checks. + if err := tstest.WaitFor(5*time.Second, func() error { + if !pidGone(pid) { + return errors.New("unreaped child reported alive") } - // The state field follows the comm field, which may contain - // spaces and parentheses; take the field after the last ')'. - i := bytes.LastIndexByte(b, ')') - if i < 0 || i+2 >= len(b) { - return false - } - return b[i+2] == 'Z' + return nil + }); err != nil { + t.Fatal(err) + } + if err := unix.Kill(pid, 0); err != nil { + t.Fatalf("child was reaped before cleanup: %v", err) } - return unix.Kill(pid, 0) != nil } // TestWaitMonitorProcessExitNotificationWins checks priority and repeatable @@ -812,7 +839,7 @@ func TestSessionMonitorHangupEscalation(t *testing.T) { t.Fatalf("child output = %q; want ready (the HUP trap is installed)", marker) } - ss.hangupMonitorProcess() + ss.hangupMonitorProcess(true) // The child must die via the SIGKILL escalation (128+9) within the // escalation window plus slack. @@ -1011,7 +1038,7 @@ func TestHangupMonitorProcessAfterMonitorClosed(t *testing.T) { logf: t.Logf, monChild: monitorProcess{PID: cmd.Process.Pid, ID: 1}, } - if !ss.hangupMonitorProcess() { + if !ss.hangupMonitorProcess(true) { t.Fatal("monitor session took the direct hangup path") } if got := c.connMonitorIfAny(); got != nil { diff --git a/ssh/tailssh/tailssh.go b/ssh/tailssh/tailssh.go index f352fc700..a893a66ab 100644 --- a/ssh/tailssh/tailssh.go +++ b/ssh/tailssh/tailssh.go @@ -236,7 +236,7 @@ func (srv *server) HandleSSHConn(nc net.Conn) error { } // Shutdown closes active connections and waits up to sshShutdownTimeout for -// sessions to finish. Session goroutines may remain running after it returns. +// sessions to finish. Session goroutines and non-PTY processes may outlive it. func (srv *server) Shutdown() { srv.mu.Lock() srv.shutdownCalled = true @@ -340,6 +340,9 @@ type conn struct { // or partial authentication success. authCompleted atomic.Bool + // monitorKillAll requests connection-wide termination on revocation. + monitorKillAll atomic.Bool + // authRecheckDone is closed after the asynchronous auth-completion policy // check. It is initialized before the connection is published. authRecheckDone chan struct{} @@ -914,6 +917,10 @@ type sshSession struct { conn *conn agentListener net.Listener // non-nil if agent-forwarding requested+allowed + // monitorLaunchMu serializes exec registration with policy cancellation. + // The monitor must accept termination before cancellation is published. + monitorLaunchMu sync.Mutex + // initialized by launchProcess: osSessionState // the process itself; see process_*.go wrStdin io.WriteCloser @@ -928,6 +935,19 @@ type sshSession struct { childPipes []io.Closer } +// cancelWithTermination registers monitor termination before canceling ss.ctx. +// It waits for any in-flight monitor exec to register its child. +func (ss *sshSession) cancelWithTermination(err SSHTerminationError) { + ss.monitorLaunchMu.Lock() + defer ss.monitorLaunchMu.Unlock() + if ss.ctx.Err() != nil { + // Preserve the existing cancellation's termination policy. + return + } + ss.hangupMonitorProcess(true) + ss.cancelCtx(err) +} + func (ss *sshSession) vlogf(format string, args ...any) { if sshVerboseLogging() { ss.logf(format, args...) @@ -1071,6 +1091,8 @@ func (c *conn) closeConn() { func (c *conn) revokeConn(reason string) { metricPolicyChangeKick.Add(1) c.logf("session no longer valid per new SSH policy (%v); closing connection", reason) + // Request connection-wide cleanup before closing the transport. + c.monitorKillAll.Store(true) c.mu.Lock() for _, s := range c.sessions { s.cancelCtx(userVisibleError{ @@ -1353,8 +1375,9 @@ func (c *conn) fetchSSHAction(ctx context.Context, url string) (*tailcfg.SSHActi } } -// killProcessOnContextDone reports cancellation and terminates the session -// process. processDone stops it when the process exits normally. +// killProcessOnContextDone terminates processes for SSHTerminationError causes. +// Other cancellation causes close the PTY without explicitly signaling processes. +// It returns if processDone is closed and the session is not canceled. func (ss *sshSession) killProcessOnContextDone(processDone <-chan struct{}) { select { case <-ss.ctx.Done(): @@ -1364,18 +1387,24 @@ func (ss *sshSession) killProcessOnContextDone(processDone <-chan struct{}) { } } err := context.Cause(ss.ctx) - if serr, ok := err.(SSHTerminationError); ok { + serr, mandated := err.(SSHTerminationError) + select { + case <-processDone: + // Report cancellation even if the process has already exited. + default: + if mandated { + ss.logf("terminating SSH session from %v: %v", ss.conn.info.src.Addr(), err) + } else { + ss.logf("closing SSH session I/O from %v: %v; processes exit on their own", ss.conn.info.src.Addr(), err) + } + ss.hangupProcess(mandated) + } + // Register termination before writing to the client, which may block. + if mandated { 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) - ss.hangupProcess() - } } // isNotFoundOrExecutable reports whether err is a launchProcess @@ -1434,7 +1463,7 @@ func (ss *sshSession) run() { if ss.conn.finalAction.SessionDuration != 0 { t := time.AfterFunc(ss.conn.finalAction.SessionDuration, func() { - ss.cancelCtx(userVisibleError{ + ss.cancelWithTermination(userVisibleError{ fmt.Sprintf("Session timeout of %v elapsed.", ss.conn.finalAction.SessionDuration), context.DeadlineExceeded, }) @@ -1888,7 +1917,7 @@ func (ss *sshSession) startNewRecording() (_ *recording, err error) { terminate := onFailure != nil && onFailure.TerminateSessionWithMessage != "" if terminate { ss.logf("recording: error uploading recording (closing session): %v", err) - ss.cancelCtx(userVisibleError{ + ss.cancelWithTermination(userVisibleError{ error: err, msg: onFailure.TerminateSessionWithMessage, })