mirror of
https://github.com/tailscale/tailscale.git
synced 2026-12-06 07:13:49 +09:00
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 <james@tailscale.com> Change-Id: I70b4ef40035330dd542d256ba79d889a12426a74
This commit is contained in:
1 parent
e9b151bd65
commit
1334899864
19 files changed
+798
-231
No files matched your search
@@ -6,11 +6,13 @@
|
|||||||
package tailssh
|
package tailssh
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// connMonitorState owns the connection's process monitor. It is started
|
// 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
|
return uint32(u64), uint32(g64), groups, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// closeConnMonitor closes the conn's monitor, if one was spawned. It
|
// closeConnMonitor closes the connection monitor, if any.
|
||||||
// runs from HandleSSHConn's defer after the SSH connection is done.
|
// If monitorKillAll is set, teardown must terminate all session children.
|
||||||
// Closing the RPC channel triggers the monitor's teardown in monitor.go.
|
// Subsequent calls have no effect.
|
||||||
// Closing a second time is a no-op.
|
|
||||||
func (c *conn) closeConnMonitor() {
|
func (c *conn) closeConnMonitor() {
|
||||||
c.monitor.mu.Lock()
|
c.monitor.mu.Lock()
|
||||||
mc := c.monitor.mon
|
mc := c.monitor.mon
|
||||||
@@ -109,6 +110,13 @@ func (c *conn) closeConnMonitor() {
|
|||||||
if mc == nil {
|
if mc == nil {
|
||||||
return
|
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 {
|
if err := mc.Close(); err != nil {
|
||||||
c.logf("ssh: closing connection monitor: %v", err)
|
c.logf("ssh: closing connection monitor: %v", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -147,7 +147,8 @@ func fwdSpawnChild(m *monitor, spec fwdChildSpec) (*exec.Cmd, *net.UnixConn, err
|
|||||||
// which surfaces as the op's error.
|
// which surfaces as the op's error.
|
||||||
var attr *syscall.SysProcAttr
|
var attr *syscall.SysProcAttr
|
||||||
if os.Getuid() != 0 && uint64(m.args.uid) == uint64(os.Getuid()) && uint64(m.args.gid) == uint64(os.Getgid()) {
|
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 {
|
} else {
|
||||||
attr = fwdChildAttr(m.args) // born unprivileged (Credential) in its own group
|
attr = fwdChildAttr(m.args) // born unprivileged (Credential) in its own group
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -430,10 +430,9 @@ func (ss *sshSession) waitMonitorProcess() (code int, ok bool, err error) {
|
|||||||
return 0, false, nil
|
return 0, false, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// hangupMonitorProcess is the plan9 seam of the monitor session path.
|
// hangupMonitorProcess returns false on Plan 9, which launches children directly.
|
||||||
// It always reports false, so sessions hang up their directly-started
|
// See [sshSession.hangupProcess].
|
||||||
// child.
|
func (ss *sshSession) hangupMonitorProcess(mandated bool) bool {
|
||||||
func (ss *sshSession) hangupMonitorProcess() bool {
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+116
-46
@@ -19,9 +19,9 @@
|
|||||||
// localUser, is fixed in argv at spawn. Only the event loop touches
|
// localUser, is fixed in argv at spawn. Only the event loop touches
|
||||||
// the RPC channel, the child table, and file descriptors.
|
// the RPC channel, the child table, and file descriptors.
|
||||||
//
|
//
|
||||||
// RPC EOF or an external SIGHUP tears the connection down. Every child
|
// Graceful close preserves session children unless termination is required.
|
||||||
// group is SIGHUPed, then a bounded reap sweep runs, and surviving
|
// RPC loss and external SIGHUP terminate all children. Forwarding children
|
||||||
// groups are SIGKILLed before the monitor exits.
|
// always terminate.
|
||||||
|
|
||||||
package tailssh
|
package tailssh
|
||||||
|
|
||||||
@@ -53,8 +53,7 @@ const (
|
|||||||
// result. On expiry the child's group is SIGKILLed.
|
// result. On expiry the child's group is SIGKILLed.
|
||||||
monFwdOpDeadline = 10 * time.Second
|
monFwdOpDeadline = 10 * time.Second
|
||||||
|
|
||||||
// monTeardownReap bounds each reap phase in teardown. The monitor
|
// monTeardownReap bounds the teardown grace period and reap wait.
|
||||||
// stops waiting after this interval even if children remain.
|
|
||||||
monTeardownReap = 2 * time.Second
|
monTeardownReap = 2 * time.Second
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -67,6 +66,24 @@ type monChild struct {
|
|||||||
pgid int // the child's process group. Equal to its pid.
|
pgid int // the child's process group. Equal to its pid.
|
||||||
id int64 // exec request ID, or zero for a forwarding child
|
id int64 // exec request ID, or zero for a forwarding child
|
||||||
oneshot bool // dialer or listener child. Outcome carried by the op reply.
|
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
|
// monitor is the running ssh-monitor process state, owned entirely by
|
||||||
@@ -78,6 +95,12 @@ type monitor struct {
|
|||||||
hup chan os.Signal
|
hup chan os.Signal
|
||||||
broken bool // a reply or notification write failed. Leave the loop.
|
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
|
// pendingFds holds relayed dial/listen descriptors, keyed by request
|
||||||
// ID, from the reply write until tailscaled's fdack receipt. See
|
// ID, from the reply write until tailscaled's fdack receipt. See
|
||||||
// replyFD and the monitor_rpc.go header for the darwin kernel
|
// 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)
|
signal.Notify(sigchld, syscall.SIGCHLD)
|
||||||
defer signal.Stop(sigchld)
|
defer signal.Stop(sigchld)
|
||||||
|
|
||||||
|
escalation := time.NewTimer(time.Hour)
|
||||||
|
defer escalation.Stop()
|
||||||
for {
|
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 {
|
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:
|
case <-m.hup:
|
||||||
m.teardown()
|
m.teardown()
|
||||||
return nil
|
return nil
|
||||||
case <-sigchld:
|
case <-sigchld:
|
||||||
m.sweep(true)
|
m.sweep(m.children, true)
|
||||||
case ev := <-events:
|
case ev := <-events:
|
||||||
if ev.err != nil {
|
if ev.err != nil {
|
||||||
// EOF, an I/O error, or a protocol error means the
|
// EOF, an I/O error, or a protocol error means the
|
||||||
@@ -283,7 +327,7 @@ func (m *monitor) loop() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
m.handle(ev.f, ev.fds)
|
m.handle(ev.f, ev.fds)
|
||||||
if m.broken {
|
if m.broken || m.gracefulClose {
|
||||||
m.teardown()
|
m.teardown()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -308,6 +352,16 @@ func (m *monitor) handle(f rpcFrame, fds []int) {
|
|||||||
case opSignal:
|
case opSignal:
|
||||||
closeFds(fds)
|
closeFds(fds)
|
||||||
m.handleSignal(f)
|
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:
|
case opFdAck:
|
||||||
closeFds(fds)
|
closeFds(fds)
|
||||||
if fds, ok := m.pendingFds[f.ID]; ok {
|
if fds, ok := m.pendingFds[f.ID]; ok {
|
||||||
@@ -512,6 +566,21 @@ func (m *monitor) handleSignal(f rpcFrame) {
|
|||||||
m.reply(rpcOKReply(f.ID, opSignal))
|
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
|
// killGroup signals the process group pgid with kill(-pgid, sig), so
|
||||||
// a child's descendants, such as a shell's subprocesses, die with it.
|
// a child's descendants, such as a shell's subprocesses, die with it.
|
||||||
func killGroup(pgid int, sig unix.Signal) error {
|
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
|
m.pendingFds[f.ID] = fds
|
||||||
}
|
}
|
||||||
|
|
||||||
// sweep reaps exited children with wait4(WNOHANG) and drops them from
|
// sweep reaps exited children from the given set and removes them from both
|
||||||
// the child table. With notify set, it emits one unsolicited exit
|
// the set and m.children. If notify is true, it reports session exit statuses.
|
||||||
// notification per reaped pid.
|
func (m *monitor) sweep(children map[int]*monChild, notify bool) {
|
||||||
func (m *monitor) sweep(notify bool) {
|
for pid, c := range children {
|
||||||
for pid, c := range m.children {
|
if !c.killAt.IsZero() {
|
||||||
|
continue // Retain the leader until group SIGKILL.
|
||||||
|
}
|
||||||
var ws unix.WaitStatus
|
var ws unix.WaitStatus
|
||||||
wpid, err := unix.Wait4(pid, &ws, unix.WNOHANG, nil)
|
wpid, err := unix.Wait4(pid, &ws, unix.WNOHANG, nil)
|
||||||
switch {
|
switch {
|
||||||
case err != nil:
|
case err != nil:
|
||||||
// ECHILD means not our child or already reaped. Forget it
|
// ECHILD means not our child or already reaped. Forget it
|
||||||
// either way.
|
// either way.
|
||||||
|
delete(children, pid)
|
||||||
delete(m.children, pid)
|
delete(m.children, pid)
|
||||||
case wpid == pid:
|
case wpid == pid:
|
||||||
if notify && !c.oneshot {
|
if notify && !c.oneshot {
|
||||||
m.notifyExit(monitorProcess{PID: pid, ID: c.id}, monExitCode(ws))
|
m.notifyExit(monitorProcess{PID: pid, ID: c.id}, monExitCode(ws))
|
||||||
}
|
}
|
||||||
|
delete(children, pid)
|
||||||
delete(m.children, pid)
|
delete(m.children, pid)
|
||||||
}
|
}
|
||||||
// wpid == 0: still running.
|
// wpid == 0: still running.
|
||||||
@@ -726,50 +799,47 @@ func (m *monitor) notifyExit(child monitorProcess, code int) {
|
|||||||
m.reply(rpcExitNotify(child, code))
|
m.reply(rpcExitNotify(child, code))
|
||||||
}
|
}
|
||||||
|
|
||||||
// teardown is the monitor's orderly exit path, reached from RPC EOF, a
|
// handleKillAll requires connection-wide termination at teardown.
|
||||||
// protocol error, or an external SIGHUP. It SIGHUPs every child group,
|
func (m *monitor) handleKillAll(f rpcFrame) {
|
||||||
// runs a brief bounded reap sweep, then SIGKILLs every group that
|
m.killAll = true
|
||||||
// survived the HUP and reaps again. A session-level escalation timer
|
m.reply(rpcOKReply(f.ID, opKillAll))
|
||||||
// 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
|
// teardown sends SIGHUP, waits for the grace period, then sends SIGKILL and reaps.
|
||||||
// their own groups.
|
// 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() {
|
func (m *monitor) teardown() {
|
||||||
// Close descriptors whose receipt has not been acknowledged.
|
// Close descriptors whose receipt has not been acknowledged.
|
||||||
for id, fds := range m.pendingFds {
|
for id, fds := range m.pendingFds {
|
||||||
closeFds(fds)
|
closeFds(fds)
|
||||||
delete(m.pendingFds, id)
|
delete(m.pendingFds, id)
|
||||||
}
|
}
|
||||||
// Snapshot the pgid set at teardown entry. A group member can
|
toKill := make(map[int]*monChild, len(m.children))
|
||||||
// outlive its reaped leader, so the SIGKILL pass keys on this
|
killAll := !m.gracefulClose || m.broken || m.killAll
|
||||||
// remembered set rather than on surviving table entries.
|
for pid, c := range m.children {
|
||||||
pgids := make(map[int]struct{}, len(m.children))
|
if killAll || c.id == 0 || !c.killAt.IsZero() {
|
||||||
for _, c := range m.children {
|
toKill[pid] = c
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(pgids) > 0 {
|
if len(toKill) > 0 {
|
||||||
// Kill surviving group members even if their leader has exited,
|
deadline := time.Now().Add(monTeardownReap)
|
||||||
// then wait for children to exit for at most monTeardownReap.
|
for _, c := range toKill {
|
||||||
for pgid := range pgids {
|
c.beginTermination(monTeardownReap)
|
||||||
_ = killGroup(pgid, unix.SIGKILL)
|
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)
|
deadline = time.Now().Add(monTeardownReap)
|
||||||
for len(m.children) > 0 && time.Now().Before(deadline) {
|
for len(toKill) > 0 && time.Now().Before(deadline) {
|
||||||
m.sweep(false)
|
m.sweep(toKill, false)
|
||||||
if len(m.children) > 0 {
|
if len(toKill) > 0 {
|
||||||
time.Sleep(20 * time.Millisecond)
|
time.Sleep(20 * time.Millisecond)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -90,6 +90,7 @@ type monitorClient struct {
|
|||||||
// writeMu serializes writeFrame, so the client has one logical
|
// writeMu serializes writeFrame, so the client has one logical
|
||||||
// writer.
|
// writer.
|
||||||
writeMu sync.Mutex
|
writeMu sync.Mutex
|
||||||
|
closeMu sync.Mutex // serializes Close
|
||||||
|
|
||||||
mu sync.Mutex // guards the fields below
|
mu sync.Mutex // guards the fields below
|
||||||
nextID int64
|
nextID int64
|
||||||
@@ -318,6 +319,28 @@ func (mc *monitorClient) Signal(ctx context.Context, child monitorProcess, sig s
|
|||||||
return err
|
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
|
// Dial dials a unix socket through a relay child running with the
|
||||||
// connection's bound identity. The returned data socket and lifetime pipe
|
// connection's bound identity. The returned data socket and lifetime pipe
|
||||||
// are acknowledged to the monitor on receipt, releasing its held copies.
|
// 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
|
return ln, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close tears the connection down by closing the RPC channel, which
|
// Close requests graceful teardown and waits for the monitor to exit.
|
||||||
// triggers the monitor's teardown. Close waits for the monitor to
|
// RPC loss without a graceful close request terminates all children.
|
||||||
// exit. A wedged monitor is killed after the forwarding-op deadline,
|
// A monitor that exceeds the shutdown timeout is killed.
|
||||||
// both teardown reap sweeps, and a margin for scheduling and child reap.
|
|
||||||
func (mc *monitorClient) Close() error {
|
func (mc *monitorClient) Close() error {
|
||||||
|
mc.closeMu.Lock()
|
||||||
|
defer mc.closeMu.Unlock()
|
||||||
mc.mu.Lock()
|
mc.mu.Lock()
|
||||||
if mc.closed {
|
if mc.closed {
|
||||||
mc.mu.Unlock()
|
mc.mu.Unlock()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
mc.closed = true
|
|
||||||
mc.mu.Unlock()
|
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.c.Close()
|
||||||
<-mc.done
|
<-mc.done
|
||||||
waitErr := make(chan error, 1)
|
waitErr := make(chan error, 1)
|
||||||
|
|||||||
@@ -15,9 +15,11 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestMonitorExecCancellationAfterDispatch delays the exec reply until after
|
// newTestMonitorClient connects a monitorClient to a fake RPC peer.
|
||||||
// cancellation. The session must retain the child handle and terminate it.
|
// Cleanup closes the socket and waits for the read loop.
|
||||||
func TestMonitorExecCancellationAfterDispatch(t *testing.T) {
|
// The client has no child process and cannot use [monitorClient.Close].
|
||||||
|
func newTestMonitorClient(t *testing.T) (*monitorClient, *rpcConn) {
|
||||||
|
t.Helper()
|
||||||
client, peer := rpcTestPair(t)
|
client, peer := rpcTestPair(t)
|
||||||
mc := &monitorClient{
|
mc := &monitorClient{
|
||||||
c: client.c,
|
c: client.c,
|
||||||
@@ -30,6 +32,13 @@ func TestMonitorExecCancellationAfterDispatch(t *testing.T) {
|
|||||||
client.c.Close()
|
client.c.Close()
|
||||||
<-mc.done
|
<-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 := &conn{srv: &server{logf: t.Logf}}
|
||||||
c.monitor.mon = mc
|
c.monitor.mon = mc
|
||||||
mc.SetExitCallback(c.monitor.exits.dispatchExit)
|
mc.SetExitCallback(c.monitor.exits.dispatchExit)
|
||||||
@@ -73,16 +82,16 @@ func TestMonitorExecCancellationAfterDispatch(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
hungup := make(chan bool, 1)
|
hungup := make(chan bool, 1)
|
||||||
go func() { hungup <- ss.hangupMonitorProcess() }()
|
go func() { hungup <- ss.hangupMonitorProcess(true) }()
|
||||||
frame, fds, err = peer.readFrame()
|
frame, fds, err = peer.readFrame()
|
||||||
closeFds(fds)
|
closeFds(fds)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
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)
|
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)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if !<-hungup {
|
if !<-hungup {
|
||||||
@@ -96,8 +105,7 @@ func TestMonitorExecCancellationAfterDispatch(t *testing.T) {
|
|||||||
case <-time.After(5 * time.Second):
|
case <-time.After(5 * time.Second):
|
||||||
t.Fatal("exit notification not delivered")
|
t.Fatal("exit notification not delivered")
|
||||||
}
|
}
|
||||||
// Escalation must neither consume the result nor send another signal.
|
// Each wait must return the same exit status.
|
||||||
ss.escalateMonitorProcess(mc)
|
|
||||||
for range 2 {
|
for range 2 {
|
||||||
code, ok, err := ss.waitMonitorProcess()
|
code, ok, err := ss.waitMonitorProcess()
|
||||||
if code != 129 || !ok || err != nil {
|
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.
|
// A locally rejected request must not kill other sessions on the connection.
|
||||||
func TestMonitorValidationFailureKeepsChannel(t *testing.T) {
|
func TestMonitorValidationFailureKeepsChannel(t *testing.T) {
|
||||||
for _, tt := range []struct {
|
for _, tt := range []struct {
|
||||||
@@ -160,26 +208,15 @@ func TestMonitorWriteFailureClosesChannel(t *testing.T) {
|
|||||||
name = "partial_write"
|
name = "partial_write"
|
||||||
}
|
}
|
||||||
t.Run(name, func(t *testing.T) {
|
t.Run(name, func(t *testing.T) {
|
||||||
client, peer := rpcTestPair(t)
|
mc, peer := newTestMonitorClient(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
|
|
||||||
})
|
|
||||||
frame := rpcPingReq(0)
|
frame := rpcPingReq(0)
|
||||||
if partial {
|
if partial {
|
||||||
if err := client.c.SetWriteBuffer(1024); err != nil {
|
if err := mc.c.SetWriteBuffer(1024); err != nil {
|
||||||
t.Fatal(err)
|
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)
|
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)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if _, _, err := mc.call(mustCtx(t), frame); err == nil {
|
if _, _, err := mc.call(mustCtx(t), frame); err == nil {
|
||||||
@@ -206,18 +243,7 @@ func TestMonitorWriteFailureClosesChannel(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestMonitorReadFailureClosesChannel(t *testing.T) {
|
func TestMonitorReadFailureClosesChannel(t *testing.T) {
|
||||||
client, peer := rpcTestPair(t)
|
mc, peer := newTestMonitorClient(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
|
|
||||||
})
|
|
||||||
if _, err := peer.c.Write([]byte("invalid JSON\n")); err != nil {
|
if _, err := peer.c.Write([]byte("invalid JSON\n")); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,16 +12,15 @@ import (
|
|||||||
"golang.org/x/sys/unix"
|
"golang.org/x/sys/unix"
|
||||||
)
|
)
|
||||||
|
|
||||||
// monChildAttr returns the SysProcAttr for one monitor child. A ctty
|
// monChildAttr returns process attributes for a session child.
|
||||||
// child gets Setsid+Setctty with the PTY child endpoint as fd 0; Setpgid is
|
// With ctty, the child starts a session with fd 0 as its controlling terminal.
|
||||||
// set only for non-ctty children. Pdeathsig is advisory: it fires on
|
// Otherwise it starts a process group.
|
||||||
// the exit of the creating thread, not the process, per golang/go#27505.
|
// Pdeathsig is unset so the child can survive monitor exit.
|
||||||
func monChildAttr(ctty bool) *syscall.SysProcAttr {
|
func monChildAttr(ctty bool) *syscall.SysProcAttr {
|
||||||
return &syscall.SysProcAttr{
|
return &syscall.SysProcAttr{
|
||||||
Setpgid: !ctty,
|
Setpgid: !ctty,
|
||||||
Setsid: ctty,
|
Setsid: ctty,
|
||||||
Setctty: ctty,
|
Setctty: ctty,
|
||||||
Pdeathsig: unix.SIGHUP,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,11 +36,9 @@ func scrubFds() error {
|
|||||||
return scrubFdsByScan("/proc/self/fd")
|
return scrubFdsByScan("/proc/self/fd")
|
||||||
}
|
}
|
||||||
|
|
||||||
// fwdChildAttr returns the SysProcAttr for a one-shot forwarding child
|
// fwdChildAttr returns process attributes for a forwarding child.
|
||||||
// whose identity must be applied, that is a root monitor's child. The
|
// The child runs with ma's credentials in its own process group.
|
||||||
// Credential carries the connection's bound identity from ma. The child
|
// Pdeathsig sends SIGHUP when the creating thread exits. See golang/go#27505.
|
||||||
// leads its own group so the op deadline and teardown can kill the
|
|
||||||
// whole group, and Pdeathsig is set as in monChildAttr.
|
|
||||||
func fwdChildAttr(ma monitorArgs) *syscall.SysProcAttr {
|
func fwdChildAttr(ma monitorArgs) *syscall.SysProcAttr {
|
||||||
return &syscall.SysProcAttr{
|
return &syscall.SysProcAttr{
|
||||||
Credential: &syscall.Credential{
|
Credential: &syscall.Credential{
|
||||||
|
|||||||
+24
-12
@@ -51,13 +51,16 @@ import (
|
|||||||
|
|
||||||
// Monitor RPC operations.
|
// Monitor RPC operations.
|
||||||
const (
|
const (
|
||||||
opDial = "dial" // request {net:"unix"|"tcp", addr}. reply {ok} + socket (and lifetime pipe writer for unix)
|
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
|
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}
|
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}
|
opSignal = "signal" // request {pid, childID, sig}. reply {ok}
|
||||||
opPing = "ping" // request {}. reply {ok}
|
opTerminate = "terminate" // request {pid, childID, grace}. reply {ok}. Schedule group termination
|
||||||
opExit = "exit" // unsolicited notification {pid, childID, code}. no request ID
|
opClose = "close" // request {}. reply {ok}. Graceful teardown
|
||||||
opFdAck = "fdack" // request {id of the reply whose descriptors were received}. no fds, no reply
|
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 (
|
const (
|
||||||
@@ -125,11 +128,12 @@ type rpcFrame struct {
|
|||||||
// this flag is not a privilege boundary against tailscaled.
|
// this flag is not a privilege boundary against tailscaled.
|
||||||
Incubator bool `json:"incubator,omitzero"`
|
Incubator bool `json:"incubator,omitzero"`
|
||||||
|
|
||||||
// signal request, exit notification, and exec reply.
|
// Signal and terminate requests, exit notifications, and exec replies.
|
||||||
Pid int `json:"pid,omitzero"`
|
Pid int `json:"pid,omitzero"`
|
||||||
ChildID int64 `json:"childID,omitzero"` // exec request ID; required for signals
|
ChildID int64 `json:"childID,omitzero"` // exec request ID; required for signals
|
||||||
Sig string `json:"sig,omitempty"`
|
Sig string `json:"sig,omitempty"`
|
||||||
Code int `json:"code,omitzero"` // exit notification only
|
Code int `json:"code,omitzero"` // exit notification only
|
||||||
|
Grace time.Duration `json:"grace,omitzero"` // HUP-to-KILL delay for terminate
|
||||||
|
|
||||||
// Reply fields.
|
// Reply fields.
|
||||||
OK bool `json:"ok,omitzero"`
|
OK bool `json:"ok,omitzero"`
|
||||||
@@ -141,6 +145,10 @@ func rpcPingReq(id int64) rpcFrame {
|
|||||||
return rpcFrame{ID: id, Op: opPing}
|
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 {
|
func rpcDialReq(id int64, network, addr string) rpcFrame {
|
||||||
return rpcFrame{ID: id, Op: opDial, Net: network, Addr: addr}
|
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}
|
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 {
|
func rpcSignalReq(id int64, child monitorProcess, sig string) rpcFrame {
|
||||||
return rpcFrame{ID: id, Op: opSignal, Pid: child.PID, ChildID: child.ID, Sig: sig}
|
return rpcFrame{ID: id, Op: opSignal, Pid: child.PID, ChildID: child.ID, Sig: sig}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -552,9 +552,7 @@ func TestMonitorBadExec(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestMonitorTeardown closes the client and asserts the teardown path.
|
// TestMonitorTeardown checks that KillAll followed by Close terminates children.
|
||||||
// The monitor exits promptly, through EOF, group SIGHUP, reaping,
|
|
||||||
// SIGKILL of survivors, and exit 0. Its children die with it.
|
|
||||||
func TestMonitorTeardown(t *testing.T) {
|
func TestMonitorTeardown(t *testing.T) {
|
||||||
mc := startTestMonitor(t, os.Getuid(), os.Getgid(), testGroups(t))
|
mc := startTestMonitor(t, os.Getuid(), os.Getgid(), testGroups(t))
|
||||||
exits := collectExits(mc)
|
exits := collectExits(mc)
|
||||||
@@ -563,13 +561,17 @@ func TestMonitorTeardown(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("exec sleep: %v", err)
|
t.Fatalf("exec sleep: %v", err)
|
||||||
}
|
}
|
||||||
|
if err := mc.KillAll(mustCtx(t)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
if err := mc.Close(); err != nil {
|
if err := mc.Close(); err != nil {
|
||||||
t.Fatalf("close: monitor did not exit cleanly: %v", err)
|
t.Fatalf("close: monitor did not exit cleanly: %v", err)
|
||||||
}
|
}
|
||||||
if d := time.Since(start); d > 2*time.Second {
|
// Allow one grace period, one reap period, and scheduling slack.
|
||||||
t.Errorf("monitor teardown took %v, want < 2s", d)
|
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
|
// The sleep child must be dead. The monitor was its parent, so it is
|
||||||
|
|||||||
@@ -76,6 +76,11 @@ func TestMonitorCloseWatchdogForwardChild(t *testing.T) {
|
|||||||
}()
|
}()
|
||||||
|
|
||||||
start := time.Now()
|
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()
|
err = mc.Close()
|
||||||
t.Logf("Close duration=%v error=%v; session=%d forward=%d", time.Since(start), err, session.PID, forwardPID)
|
t.Logf("Close duration=%v error=%v; session=%d forward=%d", time.Since(start), err, session.PID, forwardPID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -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 <sys/proc.h>.
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -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'
|
||||||
|
}
|
||||||
@@ -109,14 +109,19 @@ func (ss *sshSession) waitProcess() (exitCode int, err error) {
|
|||||||
return 1, err
|
return 1, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// hangupProcess closes the PTY or sends SIGHUP, then schedules SIGKILL
|
// hangupProcess closes the PTY. If mandated is true, it also sends SIGHUP
|
||||||
// if the session process has not exited.
|
// and schedules SIGKILL. Otherwise it sends no explicit signals.
|
||||||
func (ss *sshSession) hangupProcess() {
|
func (ss *sshSession) hangupProcess(mandated bool) {
|
||||||
|
// Register termination before PTY closure can send SIGHUP.
|
||||||
|
monitored := ss.hangupMonitorProcess(mandated)
|
||||||
if ss.ptyReq != nil {
|
if ss.ptyReq != nil {
|
||||||
// Close every PTY master descriptor so the terminal driver sends SIGHUP.
|
// Close every PTY master descriptor so the terminal driver sends SIGHUP.
|
||||||
closeAll(ss.wrStdin, ss.rdStdout, ss.ptyResize)
|
closeAll(ss.wrStdin, ss.rdStdout, ss.ptyResize)
|
||||||
|
if !mandated {
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if ss.hangupMonitorProcess() {
|
if monitored {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if ss.cmd == nil || ss.cmd.Process == nil {
|
if ss.cmd == nil || ss.cmd.Process == nil {
|
||||||
@@ -124,6 +129,9 @@ func (ss *sshSession) hangupProcess() {
|
|||||||
}
|
}
|
||||||
p := ss.cmd.Process
|
p := ss.cmd.Process
|
||||||
// The process handle synchronizes signaling with exit and reaping.
|
// The process handle synchronizes signaling with exit and reaping.
|
||||||
|
if !mandated {
|
||||||
|
return
|
||||||
|
}
|
||||||
if ss.ptyReq == nil {
|
if ss.ptyReq == nil {
|
||||||
p.Signal(syscall.SIGHUP)
|
p.Signal(syscall.SIGHUP)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
+11
-23
@@ -75,6 +75,8 @@ func (s *monExitStatus) complete(code int) {
|
|||||||
// After dispatch, cancellation does not abandon the exec reply: a successful
|
// 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.
|
// 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 {
|
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 {
|
if len(stdio) != 3 {
|
||||||
return fmt.Errorf("internal error: monitor exec needs 3 stdio fds, got %d", len(stdio))
|
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
|
// hangupMonitorProcess requests monitor termination if mandated is true.
|
||||||
// if the child has not exited. It returns false for directly launched sessions.
|
// It returns false for directly launched sessions. See [sshSession.hangupProcess].
|
||||||
func (ss *sshSession) hangupMonitorProcess() bool {
|
func (ss *sshSession) hangupMonitorProcess(mandated bool) bool {
|
||||||
if ss.monChild.PID == 0 {
|
if ss.monChild.PID == 0 {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
mc := ss.conn.connMonitorIfAny()
|
mc := ss.conn.connMonitorIfAny()
|
||||||
if mc == nil {
|
if mc == nil {
|
||||||
// Monitor teardown owns cleanup. Its reaped PIDs may already have
|
// Only the monitor may signal its child process groups.
|
||||||
// been reused, so tailscaled must not signal them directly.
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
if ss.ptyReq == nil {
|
if !mandated {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
return true
|
||||||
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:
|
|
||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
if err := mc.Signal(ctx, ss.monChild, "SIGKILL"); err != nil {
|
if err := mc.Terminate(ctx, ss.monChild, knobDuration(sshHupEscalation(), hangupEscalation)); err != nil {
|
||||||
ss.vlogf("ssh: SIGKILL session process group: %v", err)
|
ss.logf("ssh: committing session termination: %v", err)
|
||||||
}
|
}
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
@@ -428,13 +428,10 @@ exit 3
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSessionMonitorConnCloseKillsHupImmuneChild pins the teardown
|
// TestSessionMonitorConnCloseKillsHupImmuneChild checks that connection close
|
||||||
// escalation on the conn-close paths, revocation, Shutdown, and plain
|
// kills mandated sessions and preserves other sessions, regardless of HUP handling.
|
||||||
// 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).
|
|
||||||
func TestSessionMonitorConnCloseKillsHupImmuneChild(t *testing.T) {
|
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) {
|
t.Run(mode, func(t *testing.T) {
|
||||||
lu := fwdTestIdentity(t)
|
lu := fwdTestIdentity(t)
|
||||||
c := newFwdTestConn(t, lu, &tailcfg.SSHAction{Accept: true})
|
c := newFwdTestConn(t, lu, &tailcfg.SSHAction{Accept: true})
|
||||||
@@ -446,10 +443,12 @@ func TestSessionMonitorConnCloseKillsHupImmuneChild(t *testing.T) {
|
|||||||
logf: t.Logf,
|
logf: t.Logf,
|
||||||
}
|
}
|
||||||
|
|
||||||
// An HUP-immune child, like TestSessionMonitorHangupEscalation:
|
// Mandated termination must kill a HUP-immune child.
|
||||||
// sh traps (ignores) SIGHUP, so only the group SIGKILL ends it.
|
command := "trap '' HUP; echo ready; while :; do sleep 1; done"
|
||||||
// The marker gates on the trap being installed.
|
if mode == "graceful-default-hup" {
|
||||||
cmd := exec.Command("/bin/sh", "-c", "trap '' HUP; echo ready; while :; do sleep 1; done")
|
command = "echo ready; exec sleep 300"
|
||||||
|
}
|
||||||
|
cmd := exec.Command("/bin/sh", "-c", command)
|
||||||
cmd.Args = incubatorChildArgv(cmd.Args)
|
cmd.Args = incubatorChildArgv(cmd.Args)
|
||||||
stdin, stdinKeep, err := os.Pipe()
|
stdin, stdinKeep, err := os.Pipe()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -483,22 +482,34 @@ func TestSessionMonitorConnCloseKillsHupImmuneChild(t *testing.T) {
|
|||||||
}
|
}
|
||||||
pid := ss.monChild.PID
|
pid := ss.monChild.PID
|
||||||
|
|
||||||
if mode == "kick-then-close" {
|
if mode == "mandated" {
|
||||||
// The revocation kick (what killProcessOnContextDone does
|
// Terminate this session without setting the connection-wide flag.
|
||||||
// when the session ctx is canceled); its escalation timer
|
ss.hangupMonitorProcess(true)
|
||||||
// races the conn teardown, which closes the monitor.
|
|
||||||
ss.hangupMonitorProcess()
|
|
||||||
}
|
}
|
||||||
// The conn teardown: every conn-close path funnels here
|
// Wait for monitor teardown to finish.
|
||||||
// (HandleSSHConn's deferred closeConnMonitor). Close waits for
|
|
||||||
// the monitor to exit, so on return the teardown sweeps
|
|
||||||
// (HUP, then SIGKILL for survivors) have run.
|
|
||||||
c.closeConnMonitor()
|
c.closeConnMonitor()
|
||||||
|
|
||||||
// The child must be dead and reaped by the monitor's own
|
if strings.HasPrefix(mode, "graceful") {
|
||||||
// teardown: signal 0 returns ESRCH once the monitor has reaped
|
// Allow time for a parent-death signal before checking liveness.
|
||||||
// it. Bound: the teardown's two sweeps (≤2s each) inside
|
// pidGone treats Linux zombies as dead.
|
||||||
// Close's 5s monitor-exit wait, plus slack.
|
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)
|
deadline := time.Now().Add(monTeardownReap*2 + 5*time.Second)
|
||||||
for {
|
for {
|
||||||
if err := unix.Kill(pid, 0); err != nil {
|
if err := unix.Kill(pid, 0); err != nil {
|
||||||
@@ -513,12 +524,18 @@ func TestSessionMonitorConnCloseKillsHupImmuneChild(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSessionMonitorTeardownKillsSamePgidStraggler pins the teardown
|
// TestSessionMonitorTeardownKillsSamePgidStraggler checks that teardown kills
|
||||||
// SIGKILL's scope: a HUP-immune member of the session child's own
|
// HUP-immune group members after their leader exits.
|
||||||
// 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.
|
|
||||||
func TestSessionMonitorTeardownKillsSamePgidStraggler(t *testing.T) {
|
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)
|
lu := fwdTestIdentity(t)
|
||||||
c := newFwdTestConn(t, lu, &tailcfg.SSHAction{Accept: true})
|
c := newFwdTestConn(t, lu, &tailcfg.SSHAction{Accept: true})
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
@@ -529,12 +546,7 @@ func TestSessionMonitorTeardownKillsSamePgidStraggler(t *testing.T) {
|
|||||||
logf: t.Logf,
|
logf: t.Logf,
|
||||||
}
|
}
|
||||||
|
|
||||||
// The leader (sh) dies to the group SIGHUP. The nohup'd member of
|
// The leader exits on HUP. Its background child ignores HUP and reports its PID.
|
||||||
// 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.
|
|
||||||
cmd := exec.Command("/bin/sh", "-c",
|
cmd := exec.Command("/bin/sh", "-c",
|
||||||
"nohup sh -c 'echo $$; exec sleep 300' & echo ready; wait")
|
"nohup sh -c 'echo $$; exec sleep 300' & echo ready; wait")
|
||||||
cmd.Args = incubatorChildArgv(cmd.Args)
|
cmd.Args = incubatorChildArgv(cmd.Args)
|
||||||
@@ -589,19 +601,26 @@ func TestSessionMonitorTeardownKillsSamePgidStraggler(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The conn teardown: closeConnMonitor runs the monitor's teardown,
|
t.Cleanup(func() { _ = unix.Kill(-ss.monChild.PID, unix.SIGKILL) })
|
||||||
// group SIGHUP (kills the leader, sweep reaps it, entry dropped),
|
ss.hangupMonitorProcess(true)
|
||||||
// then the SIGKILL pass over the snapshot pgid set.
|
if closeMonitor {
|
||||||
c.closeConnMonitor()
|
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
|
// Allow escalation and reap time. Orphaned Linux zombies count as dead.
|
||||||
// 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.
|
|
||||||
deadline = time.Now().Add(monTeardownReap*2 + 5*time.Second)
|
deadline = time.Now().Add(monTeardownReap*2 + 5*time.Second)
|
||||||
for {
|
for {
|
||||||
if pidGone(straggler) {
|
if pidGone(straggler) {
|
||||||
@@ -614,26 +633,34 @@ func TestSessionMonitorTeardownKillsSamePgidStraggler(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// pidGone reports whether pid no longer names a live process. On linux
|
func TestPIDGoneWithUnreapedChild(t *testing.T) {
|
||||||
// it reads /proc: a missing entry or a zombie (state Z) means gone.
|
cmd := exec.Command("/bin/sleep", "300")
|
||||||
// Elsewhere kill(pid, 0) is the check; the platforms in this file's
|
if err := cmd.Start(); err != nil {
|
||||||
// build tag reap orphans promptly, so a lingering zombie is not
|
t.Fatal(err)
|
||||||
// expected there.
|
}
|
||||||
func pidGone(pid int) bool {
|
t.Cleanup(func() {
|
||||||
if runtime.GOOS == "linux" {
|
cmd.Process.Kill()
|
||||||
b, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
|
cmd.Wait()
|
||||||
if err != nil {
|
})
|
||||||
return true // gone
|
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
|
return nil
|
||||||
// spaces and parentheses; take the field after the last ')'.
|
}); err != nil {
|
||||||
i := bytes.LastIndexByte(b, ')')
|
t.Fatal(err)
|
||||||
if i < 0 || i+2 >= len(b) {
|
}
|
||||||
return false
|
if err := unix.Kill(pid, 0); err != nil {
|
||||||
}
|
t.Fatalf("child was reaped before cleanup: %v", err)
|
||||||
return b[i+2] == 'Z'
|
|
||||||
}
|
}
|
||||||
return unix.Kill(pid, 0) != nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestWaitMonitorProcessExitNotificationWins checks priority and repeatable
|
// 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)
|
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
|
// The child must die via the SIGKILL escalation (128+9) within the
|
||||||
// escalation window plus slack.
|
// escalation window plus slack.
|
||||||
@@ -1011,7 +1038,7 @@ func TestHangupMonitorProcessAfterMonitorClosed(t *testing.T) {
|
|||||||
logf: t.Logf,
|
logf: t.Logf,
|
||||||
monChild: monitorProcess{PID: cmd.Process.Pid, ID: 1},
|
monChild: monitorProcess{PID: cmd.Process.Pid, ID: 1},
|
||||||
}
|
}
|
||||||
if !ss.hangupMonitorProcess() {
|
if !ss.hangupMonitorProcess(true) {
|
||||||
t.Fatal("monitor session took the direct hangup path")
|
t.Fatal("monitor session took the direct hangup path")
|
||||||
}
|
}
|
||||||
if got := c.connMonitorIfAny(); got != nil {
|
if got := c.connMonitorIfAny(); got != nil {
|
||||||
|
|||||||
+42
-13
@@ -236,7 +236,7 @@ func (srv *server) HandleSSHConn(nc net.Conn) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Shutdown closes active connections and waits up to sshShutdownTimeout for
|
// 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() {
|
func (srv *server) Shutdown() {
|
||||||
srv.mu.Lock()
|
srv.mu.Lock()
|
||||||
srv.shutdownCalled = true
|
srv.shutdownCalled = true
|
||||||
@@ -340,6 +340,9 @@ type conn struct {
|
|||||||
// or partial authentication success.
|
// or partial authentication success.
|
||||||
authCompleted atomic.Bool
|
authCompleted atomic.Bool
|
||||||
|
|
||||||
|
// monitorKillAll requests connection-wide termination on revocation.
|
||||||
|
monitorKillAll atomic.Bool
|
||||||
|
|
||||||
// authRecheckDone is closed after the asynchronous auth-completion policy
|
// authRecheckDone is closed after the asynchronous auth-completion policy
|
||||||
// check. It is initialized before the connection is published.
|
// check. It is initialized before the connection is published.
|
||||||
authRecheckDone chan struct{}
|
authRecheckDone chan struct{}
|
||||||
@@ -914,6 +917,10 @@ type sshSession struct {
|
|||||||
conn *conn
|
conn *conn
|
||||||
agentListener net.Listener // non-nil if agent-forwarding requested+allowed
|
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:
|
// initialized by launchProcess:
|
||||||
osSessionState // the process itself; see process_*.go
|
osSessionState // the process itself; see process_*.go
|
||||||
wrStdin io.WriteCloser
|
wrStdin io.WriteCloser
|
||||||
@@ -928,6 +935,19 @@ type sshSession struct {
|
|||||||
childPipes []io.Closer
|
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) {
|
func (ss *sshSession) vlogf(format string, args ...any) {
|
||||||
if sshVerboseLogging() {
|
if sshVerboseLogging() {
|
||||||
ss.logf(format, args...)
|
ss.logf(format, args...)
|
||||||
@@ -1071,6 +1091,8 @@ func (c *conn) closeConn() {
|
|||||||
func (c *conn) revokeConn(reason string) {
|
func (c *conn) revokeConn(reason string) {
|
||||||
metricPolicyChangeKick.Add(1)
|
metricPolicyChangeKick.Add(1)
|
||||||
c.logf("session no longer valid per new SSH policy (%v); closing connection", reason)
|
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()
|
c.mu.Lock()
|
||||||
for _, s := range c.sessions {
|
for _, s := range c.sessions {
|
||||||
s.cancelCtx(userVisibleError{
|
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
|
// killProcessOnContextDone terminates processes for SSHTerminationError causes.
|
||||||
// process. processDone stops it when the process exits normally.
|
// 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{}) {
|
func (ss *sshSession) killProcessOnContextDone(processDone <-chan struct{}) {
|
||||||
select {
|
select {
|
||||||
case <-ss.ctx.Done():
|
case <-ss.ctx.Done():
|
||||||
@@ -1364,18 +1387,24 @@ func (ss *sshSession) killProcessOnContextDone(processDone <-chan struct{}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
err := context.Cause(ss.ctx)
|
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 != "" {
|
if msg := serr.SSHTerminationMessage(); msg != "" {
|
||||||
io.WriteString(ss.Stderr(), "\r\n\r\n"+msg+"\r\n\r\n")
|
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
|
// isNotFoundOrExecutable reports whether err is a launchProcess
|
||||||
@@ -1434,7 +1463,7 @@ func (ss *sshSession) run() {
|
|||||||
|
|
||||||
if ss.conn.finalAction.SessionDuration != 0 {
|
if ss.conn.finalAction.SessionDuration != 0 {
|
||||||
t := time.AfterFunc(ss.conn.finalAction.SessionDuration, func() {
|
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),
|
fmt.Sprintf("Session timeout of %v elapsed.", ss.conn.finalAction.SessionDuration),
|
||||||
context.DeadlineExceeded,
|
context.DeadlineExceeded,
|
||||||
})
|
})
|
||||||
@@ -1888,7 +1917,7 @@ func (ss *sshSession) startNewRecording() (_ *recording, err error) {
|
|||||||
terminate := onFailure != nil && onFailure.TerminateSessionWithMessage != ""
|
terminate := onFailure != nil && onFailure.TerminateSessionWithMessage != ""
|
||||||
if terminate {
|
if terminate {
|
||||||
ss.logf("recording: error uploading recording (closing session): %v", err)
|
ss.logf("recording: error uploading recording (closing session): %v", err)
|
||||||
ss.cancelCtx(userVisibleError{
|
ss.cancelWithTermination(userVisibleError{
|
||||||
error: err,
|
error: err,
|
||||||
msg: onFailure.TerminateSessionWithMessage,
|
msg: onFailure.TerminateSessionWithMessage,
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in new issue
Block a user