ssh/tailssh: commit monitor KillAll before closing revoked connections

When a connection was revoked (policy change or RuleExpires), revokeConn
only set an in-memory flag and immediately closed the transport,
deferring the monitor KillAll RPC to closeConnMonitor. Closing the
transport caused non-PTY session stdin to hit EOF so the session leader
could exit 0 and be reaped and deleted from the monitor's child table
before KillAll or Terminate arrived, leaving background jobs in the
leader's process group alive after monitor teardown.

Commit KillAll to the monitor in revokeConn before canceling sessions or
closing the transport, and prevent connMonitor from returning or
spawning a monitor once revocation has begun. In the monitor, have
handleKillAll begin termination on every current child immediately so
leaders stay pinned until SIGKILL even if they exit before Close, and
refuse new exec/dial/listen launches after KillAll.

Fixes #22915

Change-Id: Ia2df1647602051f395f6e2fe107150e6a938a37a
Signed-off-by: James Tucker <james@tailscale.com>
This commit is contained in:
James Tucker committed 2026-12-04 22:18:27 +00:00
1 parent b81b993869
commit 9008f3cd8b
8 files changed
+227 -17

No files matched your search

+41 -6
View File
@@ -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)
+2 -1
View File
@@ -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() {}
+21 -2
View File
@@ -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))
}
+3 -2
View File
@@ -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 {
+70
View File
@@ -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 {
+1 -1
View File
@@ -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
)
+85
View File
@@ -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' </dev/null & read x"},
nil, "/", false, nil, inR, outW, null)
if err != nil {
t.Fatal(err)
}
inR.Close()
outW.Close()
t.Cleanup(func() { _ = unix.Kill(-child.PID, unix.SIGKILL) })
outR.SetReadDeadline(time.Now().Add(5 * time.Second))
line, err := bufio.NewReader(outR).ReadString('\n')
if err != nil {
t.Fatalf("reading straggler PID: %v", err)
}
straggler, err := strconv.Atoi(strings.TrimSpace(line))
if err != nil || straggler <= 1 {
t.Fatalf("invalid straggler PID %q: %v", line, err)
}
t.Cleanup(func() { _ = unix.Kill(straggler, unix.SIGKILL) })
if err := mc.KillAll(mustCtx(t)); err != nil {
t.Fatalf("KillAll: %v", err)
}
// New launches must be refused once KillAll has been acknowledged.
if late, err := mc.Exec(mustCtx(t), []string{"/bin/true"}, nil, "/", false, nil); err == nil {
t.Fatalf("Exec after KillAll unexpectedly spawned pid %d", late.PID)
}
// Close stdin so the leader exits immediately before Close arrives.
inW.Close()
if err := tstest.WaitFor(2*time.Second, func() error {
if !pidGone(child.PID) {
return fmt.Errorf("leader %d still running", child.PID)
}
return nil
}); err != nil {
t.Fatal(err)
}
// Give any buggy sweep a chance to reap and forget the exited leader.
time.Sleep(200 * time.Millisecond)
if pidGone(straggler) {
t.Fatalf("HUP-immune straggler %d exited before escalation", straggler)
}
if err := mc.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
if err := tstest.WaitFor(5*time.Second, func() error {
if !pidGone(straggler) {
return fmt.Errorf("straggler %d survived KillAll+Close", straggler)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
+4 -5
View File
@@ -340,9 +340,6 @@ 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{}
@@ -1091,8 +1088,10 @@ 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)
// Commit connection-wide termination to the monitor before canceling
// sessions or closing the transport so leaders stay pinned even if
// stdin EOF causes them to exit immediately.
c.armMonitorKillAll()
c.mu.Lock()
for _, s := range c.sessions {
s.cancelCtx(userVisibleError{