diff --git a/ssh/tailssh/connmonitor.go b/ssh/tailssh/connmonitor.go index a850c7d9b..a5187f135 100644 --- a/ssh/tailssh/connmonitor.go +++ b/ssh/tailssh/connmonitor.go @@ -28,6 +28,15 @@ type connMonitorState struct { // connMonitorIfAny is unaffected. closed bool + // killAll is set by armMonitorKillAll on revocation. Once set, + // connMonitor refuses to start or return a monitor, and teardown + // terminates all session children. + killAll bool + + // killAllCommitted is set after KillAll has been acknowledged by the + // monitor, avoiding a duplicate RPC during closeConnMonitor. + killAllCommitted bool + // exits routes notifications by child handle. Its callback is installed // at monitor spawn. exits monExitRegistry @@ -38,12 +47,15 @@ type connMonitorState struct { func (c *conn) connMonitor() (*monitorClient, error) { c.monitor.mu.Lock() defer c.monitor.mu.Unlock() - if c.monitor.mon != nil { - return c.monitor.mon, nil - } if c.monitor.closed { return nil, errors.New("monitor closed at connection teardown") } + if c.monitor.killAll { + return nil, errors.New("monitor closed on connection revocation") + } + if c.monitor.mon != nil { + return c.monitor.mon, nil + } uid, gid, groups, err := c.monitorCreds() if err != nil { return nil, err @@ -98,19 +110,42 @@ func (c *conn) monitorCreds() (uid, gid uint32, groups []uint32, err error) { return uint32(u64), uint32(g64), groups, nil } +// armMonitorKillAll commits connection-wide termination to the monitor +// before the transport is closed and prevents spawning a new monitor. +func (c *conn) armMonitorKillAll() { + c.monitor.mu.Lock() + c.monitor.killAll = true + mc := c.monitor.mon + committed := c.monitor.killAllCommitted + c.monitor.mu.Unlock() + if mc == nil || committed { + return + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := mc.KillAll(ctx); err != nil { + c.logf("ssh: arming monitor kill-all: %v", err) + return + } + c.monitor.mu.Lock() + c.monitor.killAllCommitted = true + c.monitor.mu.Unlock() +} + // closeConnMonitor closes the connection monitor, if any. -// If monitorKillAll is set, teardown must terminate all session children. -// Subsequent calls have no effect. +// If revocation armed kill-all without committing it, teardown ensures +// KillAll is sent before graceful close. Subsequent calls have no effect. func (c *conn) closeConnMonitor() { c.monitor.mu.Lock() mc := c.monitor.mon c.monitor.mon = nil c.monitor.closed = true + needKillAll := c.monitor.killAll && !c.monitor.killAllCommitted c.monitor.mu.Unlock() if mc == nil { return } - if c.monitorKillAll.Load() { + if needKillAll { 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) diff --git a/ssh/tailssh/connmonitor_plan9.go b/ssh/tailssh/connmonitor_plan9.go index c3ea9e7b6..6d35e6254 100644 --- a/ssh/tailssh/connmonitor_plan9.go +++ b/ssh/tailssh/connmonitor_plan9.go @@ -8,4 +8,5 @@ package tailssh // connMonitorState is empty because Plan 9 does not use a process monitor. type connMonitorState struct{} -func (c *conn) closeConnMonitor() {} +func (c *conn) armMonitorKillAll() {} +func (c *conn) closeConnMonitor() {} diff --git a/ssh/tailssh/monitor.go b/ssh/tailssh/monitor.go index a158caa29..17fcb4034 100644 --- a/ssh/tailssh/monitor.go +++ b/ssh/tailssh/monitor.go @@ -95,7 +95,9 @@ 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 records connection-wide revocation: all current children have + // begun termination, teardown terminates all children, and new launches + // are refused. killAll bool // gracefulClose records receipt of an explicit close request. @@ -432,6 +434,10 @@ func (m *monitor) handleExec(f rpcFrame, fds []int) { closeFds(fds) m.reply(rpcErrReply(f.ID, opExec, err)) } + if m.killAll { + fail(errors.New("exec: monitor is terminating")) + return + } if len(f.Argv) == 0 { fail(errors.New("exec: empty argv")) return @@ -591,6 +597,10 @@ func killGroup(pgid int, sig unix.Signal) error { // Unix dials return a private data socket and lifetime pipe for a relay child; // TCP dials return the connected socket and the child exits after handoff. func (m *monitor) handleDial(f rpcFrame) { + if m.killAll { + m.reply(rpcErrReply(f.ID, opDial, errors.New("dial: monitor is terminating"))) + return + } if err := validateFwdDial(f.Net, f.Addr); err != nil { m.reply(rpcErrReply(f.ID, opDial, err)) return @@ -604,6 +614,10 @@ func (m *monitor) handleDial(f rpcFrame) { // with the bound identity. See fwdchild.go for the socket and dir // construction. The reply carries the resulting path or address. func (m *monitor) handleListen(f rpcFrame) { + if m.killAll { + m.reply(rpcErrReply(f.ID, opListen, errors.New("listen: monitor is terminating"))) + return + } spec := fwdChildSpec{op: "listen"} switch { case f.Agent: @@ -799,9 +813,14 @@ func (m *monitor) notifyExit(child monitorProcess, code int) { m.reply(rpcExitNotify(child, code)) } -// handleKillAll requires connection-wide termination at teardown. +// handleKillAll begins connection-wide termination of all current children +// and refuses new child launches. Leaders remain pinned until SIGKILL so a +// child exiting before teardown cannot drop its process group from cleanup. func (m *monitor) handleKillAll(f rpcFrame) { m.killAll = true + for _, c := range m.children { + c.beginTermination(monTeardownReap) + } m.reply(rpcOKReply(f.ID, opKillAll)) } diff --git a/ssh/tailssh/monitor_client.go b/ssh/tailssh/monitor_client.go index af4e773eb..f504210bd 100644 --- a/ssh/tailssh/monitor_client.go +++ b/ssh/tailssh/monitor_client.go @@ -330,8 +330,9 @@ func (mc *monitorClient) Terminate(ctx context.Context, child monitorProcess, gr return err } -// KillAll requires teardown to terminate all session children. -// Call it before [monitorClient.Close] when access is revoked. +// KillAll begins termination of all current children, refuses new launches, +// and requires teardown to terminate all session children. Call it before +// closing the transport or calling [monitorClient.Close] when access is revoked. func (mc *monitorClient) KillAll(ctx context.Context) error { _, _, err := mc.call(ctx, rpcKillAllReq(0)) if err != nil { diff --git a/ssh/tailssh/monitor_lifecycle_test.go b/ssh/tailssh/monitor_lifecycle_test.go index f853df809..8089b2959 100644 --- a/ssh/tailssh/monitor_lifecycle_test.go +++ b/ssh/tailssh/monitor_lifecycle_test.go @@ -8,6 +8,7 @@ package tailssh import ( "context" "io" + "net" "os" "os/exec" "strings" @@ -154,6 +155,75 @@ func TestMonitorPolicyCancellationWaitsForCommit(t *testing.T) { } } +// TestMonitorRevokeCommitsKillAllBeforeClosingConn checks that revokeConn +// commits KillAll to the monitor before canceling sessions or closing the +// transport, and prevents any subsequent connMonitor calls. +func TestMonitorRevokeCommitsKillAllBeforeClosingConn(t *testing.T) { + mc, peer := newTestMonitorClient(t) + srvConn, cliConn := net.Pipe() + defer srvConn.Close() + defer cliConn.Close() + ctx, cancel := context.WithCancelCause(context.Background()) + defer cancel(nil) + c := &conn{ + srv: &server{logf: t.Logf}, + netConn: srvConn, + } + c.monitor.mon = mc + ss := &sshSession{conn: c, ctx: ctx, cancelCtx: cancel, logf: t.Logf} + c.sessions = []*sshSession{ss} + + cliClosed := make(chan struct{}) + go func() { + defer close(cliClosed) + var b [1]byte + _, _ = cliConn.Read(b[:]) + }() + + finished := make(chan struct{}) + go func() { + c.revokeConn("test revocation") + close(finished) + }() + + frame, fds, err := peer.readFrame() + closeFds(fds) + if err != nil { + t.Fatal(err) + } + if frame.Op != opKillAll { + t.Fatalf("frame.Op = %q; want %q", frame.Op, opKillAll) + } + if ctx.Err() != nil { + t.Fatal("session canceled before monitor acknowledged KillAll") + } + select { + case <-cliClosed: + t.Fatal("transport closed before monitor acknowledged KillAll") + default: + } + if err := peer.writeFrame(rpcOKReply(frame.ID, opKillAll)); err != nil { + t.Fatal(err) + } + + select { + case <-finished: + case <-time.After(5 * time.Second): + t.Fatal("revokeConn did not finish") + } + if _, ok := context.Cause(ctx).(SSHTerminationError); !ok { + t.Fatalf("cancellation cause = %v; want SSHTerminationError", context.Cause(ctx)) + } + select { + case <-cliClosed: + case <-time.After(5 * time.Second): + t.Fatal("transport was not closed after KillAll") + } + if _, err := c.connMonitor(); err == nil { + t.Fatal("connMonitor succeeded after revokeConn") + } +} + // A locally rejected request must not kill other sessions on the connection. func TestMonitorValidationFailureKeepsChannel(t *testing.T) { for _, tt := range []struct { diff --git a/ssh/tailssh/monitor_rpc.go b/ssh/tailssh/monitor_rpc.go index e16c1fe64..af90fe76c 100644 --- a/ssh/tailssh/monitor_rpc.go +++ b/ssh/tailssh/monitor_rpc.go @@ -59,7 +59,7 @@ const ( 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 + opKillAll = "killall" // request {}. reply {ok}. Begin connection-wide termination of all children 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 ) diff --git a/ssh/tailssh/monitor_termination_test.go b/ssh/tailssh/monitor_termination_test.go index e091c1aad..45e1c1840 100644 --- a/ssh/tailssh/monitor_termination_test.go +++ b/ssh/tailssh/monitor_termination_test.go @@ -10,6 +10,8 @@ import ( "context" "fmt" "os" + "strconv" + "strings" "testing" "time" @@ -74,3 +76,86 @@ func TestMonitorTerminationRPCFailureFailsClosed(t *testing.T) { }) } } + +// TestMonitorKillAllPinsLeaderUntilClose checks that KillAll begins +// termination immediately, pinning child leaders even if they exit on stdin +// EOF before Close so teardown still kills surviving process-group members, +// and refuses subsequent child launches. +func TestMonitorKillAllPinsLeaderUntilClose(t *testing.T) { + mc := startTestMonitor(t, os.Getuid(), os.Getgid(), testGroups(t)) + inR, inW, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer inR.Close() + defer inW.Close() + outR, outW, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer outR.Close() + defer outW.Close() + null, err := os.OpenFile(os.DevNull, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + defer null.Close() + + // Leader waits on stdin EOF while its background child ignores SIGHUP. + child, err := mc.Exec(mustCtx(t), + []string{"/bin/sh", "-c", "nohup sh -c 'echo $$; exec sleep 300'