diff --git a/ssh/tailssh/fdleak_test.go b/ssh/tailssh/fdleak_test.go new file mode 100644 index 000000000..91ef006de --- /dev/null +++ b/ssh/tailssh/fdleak_test.go @@ -0,0 +1,779 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build (linux && !android) || (darwin && !ios) + +// Regression tests for the PTY-master descriptor leak into later +// sessions: a pty-master dup made without FD_CLOEXEC shows up in a +// later session child's fdinfo as a tty-index matching the earlier +// session's pty. Both session-path dups are atomic F_DUPFD_CLOEXEC, +// and on the monitor route the session children are exec'd by the +// per-conn monitor process from a clean fd table. +// +// Two properties are pinned: +// +// - Two concurrent sessions through one conn's monitor, the first +// with a pty, the second dumping its fd table and /proc/self/fdinfo: +// the second child holds no tty-index matching the first session's +// pty and nothing beyond the declared set. +// - The declared-fds-only rule for every child class: the monitor +// session child with the --env-fd pipe as fd 3, the one-shot fwd +// child dialed through the same conn's monitor while a pty session +// is live, and the direct path with tailscaledPath set to "" (the +// session child is exec'd by this process from its inherited fd +// table). +// +// Root runs bind the monitor-route conns to the non-root sshfwda test +// user, so the later children run as another uid than the test process +// holding the pty master. Non-root runs assert the same fd isolation +// between same-uid sessions. +// +// All fd-listing assertions take the listing from an external process +// such as ls, or, for the helper-children dumps in dumpChildFdsTo, by +// an explicitly numbered dirfd whose transient number is excluded (the +// /proc/self/fd false-leak lesson from TestMonitorExecChildInheritsNoFds). + +package tailssh + +import ( + "fmt" + "net" + "net/netip" + "os" + "os/user" + "path/filepath" + "reflect" + "runtime" + "strconv" + "strings" + "testing" + "time" + + gliderssh "github.com/tailscale/gliderssh" + gossh "golang.org/x/crypto/ssh" + "tailscale.com/tailcfg" + "tailscale.com/tailcfg/nodecap" + "tailscale.com/tstest" +) + +// sessionFdsDumpCmd is the fd-table dump run by the session child's +// shell. The fd listing is taken by ls, an external process, so the +// transient opendir descriptor belongs to ls, not to the listed +// process; the fdinfo phase globs the shell's fdinfo files in-process +// and cats each with an external cat. An inherited pty master shows up +// twice, as an fd beyond the declared set and as a tty-index line +// matching the earlier session's /dev/pts/N. +const sessionFdsDumpCmd = ` +echo FDLIST-BEGIN +ls -1 /proc/$$/fd +echo FDLIST-END +for f in /proc/$$/fd/*; do + echo ==FDTARGET ${f##*/} + readlink "$f" +done +echo FDTARGET-END +for f in /proc/$$/fdinfo/*; do + echo ==FDINFO $f + cat $f +done +echo FDINFO-END` + +// ptyMasterLeakFatalf fails the test when the isolation assertion trips. +// The cause is a leaked descriptor or another fd-hygiene bug of the same +// class, not a broken test. +func ptyMasterLeakFatalf(t *testing.T, format string, args ...any) { + t.Helper() + t.Fatalf("pty-master fd leak into later sessions: "+format, args...) +} + +// waitSessionPtsIndex polls a pty session's output until the child's tty +// line appears and returns the pty's pts index. A leaked master fd +// would report this index in the fdinfo dump of a later session's child. +func waitSessionPtsIndex(t *testing.T, out *sessTestBuffer, timeout time.Duration) int { + t.Helper() + deadline := time.Now().Add(timeout) + for time.Now().Before(deadline) { + for _, line := range strings.Fields(out.String()) { + if pts, ok := strings.CutPrefix(line, "/dev/pts/"); ok { + n, err := strconv.Atoi(pts) + if err == nil { + return n + } + } + } + time.Sleep(50 * time.Millisecond) + } + t.Fatalf("pty session never reported its tty (got %q)", out.String()) + return -1 +} + +// sessionFdsDump holds the parsed output of sessionFdsDumpCmd. Fds is +// the set of fds the session child's shell holds, taken only from the +// external ls listing. TtyIdx holds every tty-index value the fdinfo +// exposed; kernels without the tty-index fdinfo line expose none, and +// the fd-count assertion is then the effective one. +type sessionFdsDump struct { + fds map[int]bool + ttyIdx map[int]bool // tty-index values seen on any fd + targets map[int]string // per-fd readlink targets, when dumped + sawFdinfo bool +} + +// parseSessionFdsDump parses sessionFdsDumpCmd's output, the fd listing +// between the FDLIST markers and the fdinfo sections' tty-index lines. +// fdinfo lines are tab-separated, so this parses line-wise rather than +// by whitespace fields. An fdinfo section whose cat produced nothing is +// ignored: its ENOENT is the fdinfo glob's own transient fd, closed by +// cat time. +func parseSessionFdsDump(t *testing.T, out string) sessionFdsDump { + t.Helper() + d := sessionFdsDump{fds: map[int]bool{}, ttyIdx: map[int]bool{}, targets: map[int]string{}} + inList, inInfo, inTarget := false, false, false + lastTargetFD := -1 + for _, raw := range strings.Split(out, "\n") { + line := strings.TrimSpace(raw) + switch { + case line == "FDLIST-BEGIN": + inList, inInfo, inTarget = true, false, false + continue + case line == "FDLIST-END": + inList, inInfo = false, false + continue + case strings.HasPrefix(line, "==FDTARGET"): + inList, inInfo, inTarget = false, false, true + if v, ok := strings.CutPrefix(line, "==FDTARGET "); ok { + lastTargetFD, _ = strconv.Atoi(strings.TrimSpace(v)) + } + continue + case line == "FDTARGET-END": + inList, inInfo, inTarget = false, false, false + continue + case strings.HasPrefix(line, "==FDINFO"): + // A new section begins. Sections whose content lines never + // arrive below were transient, closed before cat could read. + inList, inInfo, inTarget = false, true, false + continue + case line == "FDINFO-END": + inList, inInfo = false, false + continue + } + if inList { + if line == "" { + continue + } + if fd, err := strconv.Atoi(line); err == nil { + d.fds[fd] = true + } else { + t.Fatalf("fd listing line %q: not a number", line) + } + } + if inTarget && line != "" && lastTargetFD >= 0 { + d.targets[lastTargetFD] = line + } + if inInfo && line != "" { + d.sawFdinfo = true + if v, ok := strings.CutPrefix(line, "tty-index:"); ok { + n, err := strconv.Atoi(strings.TrimSpace(v)) + if err == nil { + d.ttyIdx[n] = true + } + } + } + } + return d +} + +// runFdsDumpSession opens the session that runs sessionFdsDumpCmd (with +// any extraArg appended) and returns its raw output. gossh Run returns +// at the exit-status frame, which this server may send before the final +// output frames, so the caller-readable buffer is polled until the +// dump's FDINFO-END terminator arrives before the output is parsed. +func runFdsDumpSession(t *testing.T, cl *gossh.Client, extraArg string, configure func(*gossh.Session)) string { + t.Helper() + s, err := cl.NewSession() + if err != nil { + t.Fatalf("new dump session: %v", err) + } + if configure != nil { + configure(s) + } + var out sessTestBuffer + s.Stdout = &out + s.Stderr = &out + if err := s.Run(sessionFdsDumpCmd + extraArg); err != nil { + t.Fatalf("fd dump session: %v (output %q)", err, out.String()) + } + deadline := time.Now().Add(10 * time.Second) + for { + if strings.Contains(out.String(), "FDINFO-END") { + return out.String() + } + if time.Now().After(deadline) { + t.Fatalf("fd dump output never completed (got %q)", out.String()) + } + time.Sleep(20 * time.Millisecond) + } +} + +// TestParseSessionFdsDumpDetectsTtyIndex proves the fdinfo parse half +// of the isolation assertions detects the leak's mechanism: a synthetic +// dump in the byte-for-byte shape the shell emits yields the fd set +// and the tty-index. +func TestParseSessionFdsDumpDetectsTtyIndex(t *testing.T) { + out := "FDLIST-BEGIN\n4\n0\n1\n2\nFDLIST-END\n" + + "==FDINFO /proc/999/fdinfo/4\npos:\t0\nflags:\t02100002\nmnt_id:\t19\nino:\t89\ntty-index:\t17\n" + + "==FDINFO /proc/999/fdinfo/0\npos:\t0\nflags:\t02\n\n" + + "FDINFO-END\n" + d := parseSessionFdsDump(t, out) + want := map[int]bool{0: true, 1: true, 2: true, 4: true} + if !reflect.DeepEqual(d.fds, want) { + t.Fatalf("parsed fd set = %v, want %v", d.fds, want) + } + if !d.sawFdinfo { + t.Fatal("fdinfo sections not seen") + } + if wantIdx := map[int]bool{17: true}; !reflect.DeepEqual(d.ttyIdx, wantIdx) { + t.Fatalf("parsed tty-index set = %v, want %v (the leaked-master line)", d.ttyIdx, wantIdx) + } +} + +// ambientFds snapshots the test process's fd table before the test +// creates anything. A CI runner's process chain can hold inherited +// non-close-on-exec pipes; every descendant inherits them, so they +// show up in every session child's fd dump without being session +// leaks. Snapshot fd numbers persist for the process lifetime, since +// an open descriptor keeps its number, so a dump-time fd present here +// is ambient inheritance rather than something this test's sessions +// acquired. +func ambientFds(t *testing.T) map[int]bool { + t.Helper() + ents, err := os.ReadDir("/proc/self/fd") + if err != nil { + t.Logf("ambient fd snapshot unavailable (%v); beyond-set detection runs unfiltered", err) + return nil + } + m := make(map[int]bool, len(ents)) + for _, ent := range ents { + if n, err := strconv.Atoi(ent.Name()); err == nil { + m[n] = true + } + } + return m +} + +// assertSessionFdsIsolated asserts the fd isolation properties for +// one session child's fd dump against a live pty session at pts index +// ptsIdx: the dump holds exactly the declared fds 0, 1 and 2 (the +// env-fd 3 is not passed to the shell), with no tty-index collision +// with the live pty's master. A beyond-set fd that was already open in +// the test process when the test started is runner-inherited ambient +// state and is reported, not failed; a beyond-set fd acquired since, +// or any fd targeting the live pty's master or slave, fails. +func assertSessionFdsIsolated( + t *testing.T, + dump sessionFdsDump, + ptsIdx int, + crossUserNote string, + ambient map[int]bool, +) { + t.Helper() + for fd := range dump.fds { + if fd >= 0 && fd <= 3 { + continue + } + if ambient[fd] { + t.Logf("session child inherited ambient fd %d -> %q", fd, dump.targets[fd]) + continue + } + ptyMasterLeakFatalf(t, + "unexpected fd %d -> %q: fds=%v tty-indexes=%v targets=%v live-pty=pts/%d (%s)", + fd, dump.targets[fd], dump.fds, dump.ttyIdx, dump.targets, ptsIdx, crossUserNote) + } + for fd, target := range dump.targets { + if target == "/dev/ptmx" || target == fmt.Sprintf("/dev/pts/%d", ptsIdx) { + ptyMasterLeakFatalf(t, + "session child inherited PTY fd %d -> %s: live-pty=pts/%d ambient=%v", + fd, target, ptsIdx, ambient) + } + } + if dump.ttyIdx[ptsIdx] { + ptyMasterLeakFatalf(t, + "session child inherited live PTY master pts/%d: fds=%v (%s)", + ptsIdx, dump.fds, crossUserNote) + } + t.Logf("session child fds=%v tty-indexes=%v live-pty=pts/%d (%s)", + dump.fds, dump.ttyIdx, ptsIdx, crossUserNote) +} + +// ptyLeakCrossUserNote describes the uid relationship the test proves. +// Under root, the session children run as the bound non-root user while +// the test process holds the pty master as root. Otherwise both run +// under the same uid. +func ptyLeakCrossUserNote() string { + if uid := os.Getuid(); uid != 0 { + return fmt.Sprintf("same-uid pin: tailscaled-proxy uid %d is also the bound user", uid) + } + return "test process runs as root; session children run as the bound non-root user" +} + +// startPtyLeakSession opens the long-lived pty session, session 1 of +// the isolation tests. Its child reports its tty, then sleeps. The +// master stays open in the test process until the client closes it, +// for the whole duration of the second session's dump. +func startPtyLeakSession(t *testing.T, cl *gossh.Client) (*gossh.Session, *sessTestBuffer, int) { + t.Helper() + s, err := cl.NewSession() + if err != nil { + t.Fatalf("new pty session: %v", err) + } + if err := s.RequestPty("xterm", 10, 40, gossh.TerminalModes{}); err != nil { + t.Fatalf("request pty: %v", err) + } + var out sessTestBuffer + s.Stdout = &out + s.Stderr = &out + if err := s.Start("tty; sleep 25"); err != nil { + t.Fatalf("start pty session child: %v", err) + } + return s, &out, waitSessionPtsIndex(t, &out, 15*time.Second) +} + +// TestSessionPTYMasterNotInheritedByLaterSessions is the targeted +// pty-leak regression of two concurrent sessions through one conn's +// monitor. Session 1 holds a live pty whose master lives in the +// tailscaled-proxy process, which is this test process; session 2 +// dumps its fd table and fdinfo. The second child must hold only its +// declared fds 0, 1 and 2 and no fd whose tty-index matches the first +// session's pty. +// +// The SSHBehaviorV1 cap pins the incubator to the in-process children +// branch, as in TestSessionMonitorExitStatusOrder. +func TestSessionPTYMasterNotInheritedByLaterSessions(t *testing.T) { + if runtime.GOOS != "linux" { + t.Skip("fd-table / fdinfo assertions read /proc; linux-only") + } + lu := fwdTestIdentity(t) // root runs: the non-root sshfwda user + addr := newMonitorSessionServerFor(t, lu, nil, nil, false, func(c *conn, s gliderssh.Session) { + c.newSSHSession(s).run() + }) + + cl, err := gossh.Dial("tcp", addr, &gossh.ClientConfig{ + HostKeyCallback: gossh.InsecureIgnoreHostKey(), + Timeout: 15 * time.Second, + }) + if err != nil { + t.Fatal(err) + } + defer cl.Close() + + ambient := ambientFds(t) + s1, _, ptsIdx := startPtyLeakSession(t, cl) + defer s1.Close() + + raw := runFdsDumpSession(t, cl, "", nil) + dump := parseSessionFdsDump(t, raw) + note := ptyLeakCrossUserNote() + assertSessionFdsIsolated(t, dump, ptsIdx, note, ambient) + declared := map[int]bool{0: true, 1: true, 2: true} + live := map[int]bool{} + for fd := range dump.fds { + if fd <= 3 || !ambient[fd] { + // The child's declared stdio is its own; only beyond-set + // fds are candidates for ambient inheritance. + live[fd] = true + } + } + if !reflect.DeepEqual(live, declared) { + t.Errorf("session child fds=%v ambient=%v; want declared fds=%v", + dump.fds, ambient, declared) + } + if !dump.sawFdinfo { + t.Fatalf("fdinfo sections produced no content (raw %q)", raw) + } +} + +// TestSessionChildDeclaredFdsIncludeOnlyEnvFD pins the +// declared-fds rule for the monitor's session child +// with the --env-fd present. A session whose client-forwarded env pair +// is accepted travels to the incubator as a fourth descriptor, fd 3. +// The incubator child, exec'd by the conn's monitor, must hold exactly +// {0,1,2,3}, fd 3 being the env pipe. The incubator dump runs in the +// helper-test entry before the incubator drops privileges. +func TestSessionChildDeclaredFdsIncludeOnlyEnvFD(t *testing.T) { + if runtime.GOOS != "linux" { + t.Skip("fd-table / fdinfo assertions read /proc; linux-only") + } + lu := fwdTestIdentity(t) + dumpPath := filepath.Join(t.TempDir(), "incub-fds.dump") + ambient := ambientFds(t) + + rule := &tailcfg.SSHRule{ + SSHUsers: map[string]string{"test": lu.Username}, + Action: &tailcfg.SSHAction{Accept: true}, + AcceptEnv: []string{"TERM"}, + Principals: []*tailcfg.SSHPrincipal{ + {Any: true}, + }, + } + caps := []nodecap.Cap{ + nodecap.SSHBehaviorV1, + nodecap.SSHEnvironmentVariables, + } + addr := newMonitorSessionServerFor(t, lu, caps, rule, false, func(c *conn, s gliderssh.Session) { + c.newSSHSession(s).run() + }) + + cl, err := gossh.Dial("tcp", addr, &gossh.ClientConfig{ + HostKeyCallback: gossh.InsecureIgnoreHostKey(), + Timeout: 15 * time.Second, + }) + if err != nil { + t.Fatal(err) + } + defer cl.Close() + + s1, _, ptsIdx := startPtyLeakSession(t, cl) + defer s1.Close() + + // The trailing marker carries the dump path in the incubator's + // argv. Setenv must run on the same session the dump does; + // runFdsDumpSession's configure callback applies it before the + // command starts. + raw := runFdsDumpSession(t, cl, " ; echo "+incubFdsDumpMarker+"="+dumpPath, func(s *gossh.Session) { + if err := s.Setenv("TERM", "leakcheck"); err != nil { + t.Fatalf("Setenv: %v", err) + } + }) + + // The shell holds the declared std only, after the privilege drop + // and after the env pipe is closed. + dump := parseSessionFdsDump(t, raw) + assertSessionFdsIsolated(t, dump, ptsIdx, ptyLeakCrossUserNote(), ambient) + + // The incubator's fd table at exec time, straight from the + // monitor's handoff, holds fd 3 plus stdio. + blocks := parseFDumpBlocks(t, dumpPath) + if len(blocks) != 1 { + t.Fatalf("incubator fd dump has %d blocks, want 1: %v", len(blocks), blocks) + } + assertHelperChildDeclaredFds(t, blocks[0], ptsIdx, "pipe:", "monitor session child (incubator)", ambient) + t.Logf("incubator child fds at exec: %v", blocks[0]) +} + +// TestFwdChildHoldsOnlyDeclaredFds pins the declared-fds rule for +// the one-shot forwarding child. While a pty session is live +// on the same conn, its master held by the tailscaled-proxy test +// process, a unix -L dial through the same conn's monitor spawns the +// fwd child. The helper dumps the child's exec-inherited fd table at +// entry: exactly {0,1,2,3}, stdio from the monitor plus the +// result-channel socketpair end. +func TestFwdChildHoldsOnlyDeclaredFds(t *testing.T) { + if runtime.GOOS != "linux" { + t.Skip("the helper fd dump reads /proc; linux-only") + } + lu := fwdTestIdentity(t) + dumpPath := filepath.Join(fwdTmpDir(t), "fwd-fds.dump") + t.Setenv("TS_TEST_SSH_FWD_FDINFO", dumpPath) + ambient := ambientFds(t) + + rule := &tailcfg.SSHRule{ + SSHUsers: map[string]string{"test": lu.Username}, + Action: &tailcfg.SSHAction{ + Accept: true, + AllowLocalPortForwarding: true, + }, + Principals: []*tailcfg.SSHPrincipal{ + {Any: true}, + }, + } + connCh := make(chan *conn, 1) + addr := newMonitorSessionServerFor(t, lu, nil, rule, true, func(c *conn, s gliderssh.Session) { + select { + case connCh <- c: + default: + } + c.newSSHSession(s).run() + }) + + cl, err := gossh.Dial("tcp", addr, &gossh.ClientConfig{ + HostKeyCallback: gossh.InsecureIgnoreHostKey(), + Timeout: 15 * time.Second, + }) + if err != nil { + t.Fatal(err) + } + defer cl.Close() + + s1, _, ptsIdx := startPtyLeakSession(t, cl) + defer s1.Close() + + // The dial target is a socket the bound user can open, in the + // allowlist. + svcDir := fwdTmpDir(t) + svcPath := filepath.Join(svcDir, "svc.sock") + ln, err := net.Listen("unix", svcPath) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + if err := os.Chmod(svcPath, 0o666); err != nil { + t.Fatal(err) + } + go func() { + for { + sc, err := ln.Accept() + if err != nil { + return + } + go sc.Close() + } + }() + + // Dial through the same conn's monitor while the pty session is live. + sc := <-connCh + gctx, cancel := fwdTestCtxTimeout(30 * time.Second) + defer cancel() + uc, err := sc.mayForwardLocalUnixTo(gctx, svcPath) + if err != nil { + t.Fatalf("unix -L dial through the session conn's monitor: %v", err) + } + uc.Close() + + blocks := parseFDumpBlocks(t, dumpPath) + if len(blocks) < 1 { + t.Fatalf("no fwd child dumped its fd table (dial went through, so a fwd child ran)") + } + for _, b := range blocks { + assertHelperChildDeclaredFds(t, b, ptsIdx, "socket:", "fwd child", ambient) + } + t.Logf("forwarding child fd tables: count=%d newest=%v live-pty=pts/%d (%s)", + len(blocks), blocks[len(blocks)-1], ptsIdx, ptyLeakCrossUserNote()) +} + +// newDirectSessionServer is newMonitorSessionServerFor's shape with +// tailscaledPath set to "", the direct-exec fallback used when no +// tailscaled binary exists, as in tsnet. The session child is exec'd +// by this process with its inherited fd table, so a regression to a +// non-CLOEXEC dup of the pty master is caught by a later session's +// child seeing the master. +// +// Under root the conn binds to root itself: the direct path has no +// privilege-dropping incubator, and directExecAllowed refuses a root +// process running another user's session. Under non-root it binds to the +// current user, and the fd-isolation assertions are same-uid. +func newDirectSessionServer(t *testing.T, handler func(c *conn, s gliderssh.Session)) string { + t.Helper() + username := "root" + if os.Getuid() != 0 { + u, err := user.Current() + if err != nil { + t.Fatal(err) + } + username = u.Username + } + um, err := userLookup(username) + if err != nil { + t.Fatal(err) + } + um.loginShellCached = "/bin/sh" + + logf := tstest.WhileTestRunningLogger(t) + srv := &server{ + lb: &localState{ + sshEnabled: true, + varRoot: t.TempDir(), + }, + logf: logf, + } + sc, err := srv.newConn() + if err != nil { + t.Fatal(err) + } + t.Cleanup(sc.closeFwdMonitor) + sc.insecureSkipTailscaleAuth = true + sc.localUser = um + for _, g := range testGroups(t) { + sc.userGroupIDs = append(sc.userGroupIDs, strconv.Itoa(g)) + } + sc.info = &sshConnInfo{ + sshUser: "test", + src: netip.MustParseAddrPort("1.2.3.4:32342"), + dst: netip.MustParseAddrPort("1.2.3.5:22"), + node: (&tailcfg.Node{}).View(), + uprof: tailcfg.UserProfile{}, + } + sc.action0 = &tailcfg.SSHAction{Accept: true} + sc.finalAction = sc.action0 + sc.authCompleted.Store(true) + sc.Handler = func(s gliderssh.Session) { + handler(sc, s) + } + + ln, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + go sc.HandleConn(c) + } + }() + return ln.Addr().String() +} + +// TestDirectPathSessionInheritsNoPtyMaster pins the declared-fds +// rule for the direct path, where the session child is exec'd from +// the fd-holding process itself. With a pty session live, whose master +// and both CLOEXEC dups are held by this test process, a later +// non-pty session's child must hold exactly {0,1,2} and no tty-index +// collision with the live pty. +func TestDirectPathSessionInheritsNoPtyMaster(t *testing.T) { + if runtime.GOOS != "linux" { + t.Skip("fd-table / fdinfo assertions read /proc; linux-only") + } + if os.Geteuid() == 0 && os.Getuid() != 0 { + t.Skip("elevated-but-not-root execution is not a supported direct-path configuration") + } + ambient := ambientFds(t) + addr := newDirectSessionServer(t, func(c *conn, s gliderssh.Session) { + c.newSSHSession(s).run() + }) + + cl, err := gossh.Dial("tcp", addr, &gossh.ClientConfig{ + HostKeyCallback: gossh.InsecureIgnoreHostKey(), + Timeout: 15 * time.Second, + }) + if err != nil { + t.Fatal(err) + } + defer cl.Close() + + s1, _, ptsIdx := startPtyLeakSession(t, cl) + defer s1.Close() + + raw := runFdsDumpSession(t, cl, "", nil) + dump := parseSessionFdsDump(t, raw) + note := "direct path: the session child is exec'd from the fd-holding process itself" + if os.Getuid() == 0 { + note += "; root run, sessions as root (the direct path cannot drop privileges)" + } + assertSessionFdsIsolated(t, dump, ptsIdx, note, ambient) + live := map[int]bool{} + for fd := range dump.fds { + if fd <= 3 || !ambient[fd] { + // The child's declared stdio is its own; only beyond-set + // fds are candidates for ambient inheritance. + live[fd] = true + } + } + want := map[int]bool{0: true, 1: true, 2: true} + if !reflect.DeepEqual(live, want) { + t.Errorf("direct session child fds=%v ambient=%v; want declared fds=%v", + dump.fds, ambient, want) + } + if !dump.sawFdinfo { + t.Fatalf("fdinfo sections produced no content (raw %q)", raw) + } +} + +// fdDumpEntry is one dumped descriptor: its readlink target and the +// FD_CLOEXEC state parsed from its fdinfo flags field. +type fdDumpEntry struct { + target string + cloexec bool +} + +// parseFDumpBlocks parses the BEGIN/END-delimited blocks of +// "fd flags -> " lines in a dumpChildFdsTo file. +func parseFDumpBlocks(t *testing.T, path string) []map[int]fdDumpEntry { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read fd dump: %v", err) + } + var blocks []map[int]fdDumpEntry + var cur map[int]fdDumpEntry + for _, line := range strings.Split(string(b), "\n") { + switch { + case strings.HasPrefix(line, "BEGIN "): + cur = map[int]fdDumpEntry{} + case strings.HasPrefix(line, "END "): + if cur != nil { + blocks = append(blocks, cur) + cur = nil + } + case strings.HasPrefix(line, "fd "): + if cur == nil { + t.Fatalf("fd dump line %q outside a BEGIN/END block", line) + } + rest := strings.TrimPrefix(line, "fd ") + fdS, rest2, ok := strings.Cut(rest, " ") + if !ok { + t.Fatalf("fd dump line %q: not an fd entry", line) + } + fd, err := strconv.Atoi(fdS) + if err != nil { + t.Fatalf("fd dump line %q: %v", line, err) + } + flags := "" + if before, after, ok := strings.Cut(rest2, " -> "); ok { + rest2 = after + if v, ok := strings.CutPrefix(before, "flags "); ok { + flags = strings.TrimSpace(v) + } + } + cloexec := false + if fv, err := strconv.ParseUint(flags, 8, 32); err == nil { + cloexec = fv&0o2000000 != 0 // O_CLOEXEC is visible in fdinfo's flags + } + cur[fd] = fdDumpEntry{target: rest2, cloexec: cloexec} + } + } + return blocks +} + +// assertHelperChildDeclaredFds asserts the declared-fds rule for a +// re-exec'd helper child's dumped fd table, the fwd child or the +// incubator with its --env-fd pipe: fds 0 to 2 and fd 3, the declared +// pipe or socket end, must be present, every fd beyond the declared +// set must be FD_CLOEXEC, and no descriptor may resolve to a pty end +// while another session's pty is live. The observee's own runtime +// bookkeeping, its epoll and eventfd pair, is created after exec and +// always carries the flag, unlike an exec-inherited stray from a +// non-CLOEXEC dup. +func assertHelperChildDeclaredFds( + t *testing.T, + block map[int]fdDumpEntry, + ptsIdx int, + fd3WantPrefix, classDesc string, + ambient map[int]bool, +) { + t.Helper() + for fd := 0; fd <= 3; fd++ { + if _, ok := block[fd]; !ok { + t.Fatalf("%s: declared fd %d missing from fd table %v", classDesc, fd, block) + } + } + if !strings.HasPrefix(block[3].target, fd3WantPrefix) { + t.Errorf("%s: fd 3 = %q, want a %s descriptor", classDesc, block[3].target, fd3WantPrefix) + } + for fd, e := range block { + if strings.Contains(e.target, "/dev/ptmx") || strings.HasPrefix(e.target, "/dev/pts/") { + ptyMasterLeakFatalf(t, "%s inherited PTY fd %d -> %s: live-pty=pts/%d", + classDesc, fd, e.target, ptsIdx) + } + if fd > 3 && !e.cloexec { + if ambient[fd] { + t.Logf("%s inherited ambient fd %d -> %q", classDesc, fd, e.target) + continue + } + ptyMasterLeakFatalf(t, "%s has unexpected fd %d -> %s without CLOEXEC: live-pty=pts/%d", + classDesc, fd, e.target, ptsIdx) + } + } +} diff --git a/ssh/tailssh/fwdchild_linux_test.go b/ssh/tailssh/fwdchild_linux_test.go index 603470aa3..ad18d01c2 100644 --- a/ssh/tailssh/fwdchild_linux_test.go +++ b/ssh/tailssh/fwdchild_linux_test.go @@ -7,7 +7,15 @@ package tailssh import ( "errors" + "fmt" + "io" + "io/fs" "net" + "os" + "path/filepath" + "slices" + "strconv" + "strings" "golang.org/x/sys/unix" ) @@ -30,3 +38,76 @@ func peerCredUID(c net.Conn) (int, error) { } return int(u.Uid), nil } + +// dumpChildFdsTo appends this process's fd table to the file at path, +// one "fd flags -> " line per descriptor, wrapped +// in a BEGIN/END block tagged with tag. It runs at re-exec'd helper-child +// entry (the TS_TEST_SSH_FWD_FDINFO knob for the one-shot fwd child, +// the INCUB-FDS-DUMP= argv marker for the session child's +// incubator), before the child performs its op. +// +// Readlink targets show any leaked pty end. The fdinfo flags field +// separates inherited descriptors from the observee's own runtime +// bookkeeping, which always carries FD_CLOEXEC. +// +// The enumeration runs on an explicitly opened dirfd whose number is +// skipped, along with the dump file's own descriptor; descriptors that +// vanish between the listing and the read are skipped as transient. +func dumpChildFdsTo(path, tag string) { + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o666) + if err != nil { + return + } + defer f.Close() + const fdDir = "/proc/self/fd" + dirfd, err := unix.Open(fdDir, unix.O_RDONLY|unix.O_DIRECTORY, 0) + if err != nil { + return + } + defer unix.Close(dirfd) + + // First pass: snapshot the fd numbers via getdents on the known dirfd. + var fdnums []int + buf := make([]byte, 16384) + for { + n, err := unix.Getdents(dirfd, buf) + if n <= 0 { + break + } + _, _, names := unix.ParseDirent(buf[:n], -1, nil) + for _, name := range names { + if fd, err := strconv.Atoi(name); err == nil && fd != dirfd && fd != int(f.Fd()) { + fdnums = append(fdnums, fd) + } + } + if err != nil && err != io.EOF { + break + } + } + slices.Sort(fdnums) + + // Second pass: readlink and fdinfo flags for each listed number. + var sb strings.Builder + fmt.Fprintf(&sb, "BEGIN %s pid %d\n", tag, os.Getpid()) + for _, fd := range fdnums { + target, lerr := os.Readlink(filepath.Join(fdDir, strconv.Itoa(fd))) + if lerr != nil { + if errors.Is(lerr, fs.ErrNotExist) { + continue // transient: closed between the listing and this read + } + target = lerr.Error() + } + flags := "" + if info, ierr := os.ReadFile(filepath.Join("/proc/self/fdinfo", strconv.Itoa(fd))); ierr == nil { + for _, line := range strings.Split(string(info), "\n") { + if v, ok := strings.CutPrefix(line, "flags:"); ok { + flags = strings.TrimSpace(v) + break + } + } + } + fmt.Fprintf(&sb, "fd %d flags %s -> %s\n", fd, flags, target) + } + fmt.Fprintf(&sb, "END %s\n", tag) + _, _ = f.WriteString(sb.String()) +} diff --git a/ssh/tailssh/fwdchild_other_test.go b/ssh/tailssh/fwdchild_other_test.go index e65156c9d..041aac4ee 100644 --- a/ssh/tailssh/fwdchild_other_test.go +++ b/ssh/tailssh/fwdchild_other_test.go @@ -15,3 +15,8 @@ import ( func peerCredUID(c net.Conn) (int, error) { return 0, errors.New("peer cred not implemented on this platform") } + +// dumpChildFdsTo is a no-op off linux. The exec-inheritance fd dump +// reads /proc, and every test gating on it skips on these platforms +// anyway. +func dumpChildFdsTo(path, tag string) {} diff --git a/ssh/tailssh/fwdchild_test.go b/ssh/tailssh/fwdchild_test.go index 4c8450c56..3ec81670d 100644 --- a/ssh/tailssh/fwdchild_test.go +++ b/ssh/tailssh/fwdchild_test.go @@ -45,7 +45,21 @@ var testFwdPrefix = []string{"-test.run=^TestSSHFwdHelperProcess$", "-test.timeo func TestSSHFwdHelperProcess(t *testing.T) { for i, a := range os.Args { if a == "--" && i+1 < len(os.Args) && os.Args[i+1] == "ssh-fwd" { - if err := beFwdChild(os.Args[i+2:]); err != nil { + // Declared-fds pin for the fwd child. When the test asks + // for it, the child dumps its exec-inherited fd table + // before performing the op. The dump path arrives by + // argv, from the monitor's spawn of this child: the child + // itself runs with no environment. The test-only flag is + // stripped before the op parser sees it. + var childArgs []string + for _, a := range os.Args[i+2:] { + if p, ok := strings.CutPrefix(a, "--test-fdinfo="); ok { + dumpChildFdsTo(p, "ssh-fwd") + continue + } + childArgs = append(childArgs, a) + } + if err := beFwdChild(childArgs); err != nil { // The op's outcome was already reported on the result // channel; the exit code mirrors it. fmt.Fprintln(os.Stderr, "ssh-fwd child:", err) diff --git a/ssh/tailssh/fwdmonitor.go b/ssh/tailssh/fwdmonitor.go index da22dba6d..67202752f 100644 --- a/ssh/tailssh/fwdmonitor.go +++ b/ssh/tailssh/fwdmonitor.go @@ -45,9 +45,11 @@ import ( gossh "golang.org/x/crypto/ssh" ) -// fwdState is the conn's forwarding state. It holds the per-connection -// monitor, spawned lazily on the first forwarding or agent need and -// closed when the conn is torn down. The monitor's identity is bound at +// fwdState is the conn's monitor state. It holds the per-connection +// ssh-monitor, spawned lazily on the first forwarding, agent, or +// session need and closed when the conn is torn down. exits +// dispatches the monitor's async child-exit notifications to the +// conn's sessions in sessmonitor.go. The monitor's identity is bound at // spawn to the conn's localUser, with the uid, gid, and groups from // clientAuth. type fwdState struct { @@ -56,8 +58,52 @@ type fwdState struct { // closed is set by closeFwdMonitor, before the lock is dropped. Once // the conn's teardown has run, fwdMonitor refuses to spawn. - // fwdMonitorIfAny is unaffected and read-only. + // fwdMonitorIfAny is unaffected. closed bool + + // exits routes notifications by child handle. Its callback is installed + // at monitor spawn. + exits monExitRegistry +} + +// monExitRegistry matches exit notifications to child handles, including +// notifications received before the session registers its waiter. +type monExitRegistry struct { + mu sync.Mutex + waiters map[monitorProcess]*monExitStatus + pending map[monitorProcess]int // exits received before registration +} + +// dispatchExit is the monitorClient exit callback, called from the +// client's read-loop goroutine. +func (s *monExitRegistry) dispatchExit(pid monitorProcess, code int) { + s.mu.Lock() + defer s.mu.Unlock() + if ch, ok := s.waiters[pid]; ok { + delete(s.waiters, pid) + ch.complete(code) + return + } + if s.pending == nil { + s.pending = make(map[monitorProcess]int) + } + s.pending[pid] = code +} + +// registerSessionExit delivers and removes a pending exit, or registers +// a waiter for a future notification. +func (s *monExitRegistry) registerSessionExit(pid monitorProcess, ch *monExitStatus) { + s.mu.Lock() + defer s.mu.Unlock() + if code, ok := s.pending[pid]; ok { + delete(s.pending, pid) + ch.complete(code) + return + } + if s.waiters == nil { + s.waiters = make(map[monitorProcess]*monExitStatus) + } + s.waiters[pid] = ch } // fwdMonitor returns the conn's monitor, spawning it on first use with @@ -87,16 +133,18 @@ func (c *conn) fwdMonitor() (*monitorClient, error) { } mc, err := spawnMonitor(exe, uid, gid, groups, c.localUser.Username) if err != nil { - return nil, fmt.Errorf("spawning ssh-monitor for forwarding as %q: %w", c.localUser.Username, err) + return nil, fmt.Errorf("spawning ssh-monitor for %q: %w", c.localUser.Username, err) } + // Route the monitor's async exit notifications to the conn's + // sessions in sessmonitor.go. + mc.SetExitCallback(c.fwd.exits.dispatchExit) c.fwd.mon = mc return mc, nil } // fwdMonitorIfAny returns the conn's monitor without spawning one. // Callers that can race the conn's teardown must use it instead of the -// lazy fwdMonitor. See fwdState.closed. Nil means the monitor is already -// gone. +// lazy fwdMonitor. See fwdState.closed. func (c *conn) fwdMonitorIfAny() *monitorClient { c.fwd.mu.Lock() defer c.fwd.mu.Unlock() diff --git a/ssh/tailssh/fwdmonitor_test.go b/ssh/tailssh/fwdmonitor_test.go index 97138cdac..2f597351b 100644 --- a/ssh/tailssh/fwdmonitor_test.go +++ b/ssh/tailssh/fwdmonitor_test.go @@ -1130,6 +1130,32 @@ func TestFwdConnLocalUnixDirSwapRaceNeverServesProtectedSocket(t *testing.T) { attempts.Load(), dials.Load(), eacces.Load(), enoent.Load(), swaps.Load()) } +// TestMonExitRegistryPIDReuse checks both exit-before-registration and +// registration-before-exit when two child generations share a PID. +func TestMonExitRegistryPIDReuse(t *testing.T) { + var r monExitRegistry + old := monitorProcess{PID: 42, ID: 1} + fresh := monitorProcess{PID: 42, ID: 2} + ch, ch2 := newMonExitStatus(), newMonExitStatus() + r.dispatchExit(old, 7) + r.registerSessionExit(fresh, ch2) + r.registerSessionExit(old, ch) + <-ch.done + if ch.code != 7 { + t.Fatalf("old exit = %d; want 7", ch.code) + } + select { + case <-ch2.done: + t.Fatal("old notification completed the new child") + default: + } + r.dispatchExit(fresh, 9) + <-ch2.done + if ch2.code != 9 || ch.code != 7 { + t.Fatalf("exit codes = %d, %d; want 7, 9", ch.code, ch2.code) + } +} + // TestFwdAllowedSocketPathCaps pins the allowlist's two lexical caps: // a home directory that cleans to "/" must not collapse the allowlist // to "every absolute path", and over-long paths beyond the sun_path diff --git a/ssh/tailssh/incubator.go b/ssh/tailssh/incubator.go index f3308246a..2a6d4f2f2 100644 --- a/ssh/tailssh/incubator.go +++ b/ssh/tailssh/incubator.go @@ -212,9 +212,12 @@ func (ss *sshSession) newIncubatorCommand(logf logger.Logf) (cmd *exec.Cmd, forw remoteUser = strings.Join(ci.node.Tags().AsSlice(), ",") } + // incubatorArgs is the argv after the executable path and the + // incubatorSpawnPrefix. It holds the identity flags, the session + // flags, and the command. Tests that run a real session through the + // monitor override incubatorSpawnPrefix to route to beIncubator + // directly. incubatorArgs := []string{ - "be-child", - "ssh", "--login-shell=" + lu.LoginShell(), "--uid=" + lu.Uid, "--gid=" + lu.Gid, @@ -274,7 +277,8 @@ func (ss *sshSession) newIncubatorCommand(logf logger.Logf) (cmd *exec.Cmd, forw } } - cmd = exec.CommandContext(ss.ctx, ss.conn.srv.tailscaledPath, incubatorArgs...) + argv := append(slices.Clone(incubatorSpawnPrefix), incubatorArgs...) + cmd = exec.CommandContext(ss.ctx, ss.conn.srv.tailscaledPath, argv...) // The incubator will chdir into the home directory after it drops privileges. cmd.Dir = "/" return cmd, forwardedEnv, nil @@ -285,6 +289,14 @@ var ( debugTest atomic.Bool ) +// incubatorSpawnPrefix is the argv prefix, after the executable path, +// used to launch the incubator. In tailscaled it is "be-child ssh", +// dispatched by cmd/tailscaled's beChild through childproc. Tests that +// drive a real session through the monitor override this seam to +// re-exec the test binary and dispatch to beIncubator via the helper +// test. +var incubatorSpawnPrefix = []string{"be-child", "ssh"} + type incubatorArgs struct { loginShell string uid int @@ -387,23 +399,42 @@ func (ia *incubatorArgs) loadForwardedEnv() error { return nil } -// forwardedEnviron returns the environment to hand to the user's process. This includes the -// current environment plus the client-forwarded pairs. It also returns allowedExtraKeys for -// the "su -w" allowlist, the forwarded key names, plus SSH_AUTH_SOCK. -func (ia *incubatorArgs) forwardedEnviron() (env, allowedExtraKeys []string) { - // SSH_AUTH_SOCK is allowlisted here rather than forwarded because old - // parents set it without forwarding any keys. It can only be present if - // the parent enabled agent forwarding: the child's environment is built - // by incubatorEnv, never from the parent's os.Environ. - allowedExtraKeys = []string{"SSH_AUTH_SOCK"} +// forwardedEnviron appends accepted client values to the filtered base environment. +func (ia *incubatorArgs) forwardedEnviron() []string { + return append(ia.rootExecEnviron(), ia.forwardedEnv...) +} - env = append(os.Environ(), ia.forwardedEnv...) +// rootExecEnviron copies the incubator environment without TERM or locale +// variables. login and su receive forwardedEnv in addition to this base; +// the capability probe receives only the base. +func (ia *incubatorArgs) rootExecEnviron() []string { + env := make([]string, 0, len(os.Environ())) + for _, kv := range os.Environ() { + if k, _, ok := strings.Cut(kv, "="); ok && clientDerivedEnvKey(k) { + continue + } + env = append(env, kv) + } + return env +} + +// clientDerivedEnvKey identifies the default client environment variables +// accepted by incubatorEnv, including TERM from a PTY request. +func clientDerivedEnvKey(k string) bool { + return k == "TERM" || k == "LANG" || strings.HasPrefix(k, "LC_") +} + +// suAllowEnvKeys returns the "su -w" allowlist for the given args: +// SSH_AUTH_SOCK plus the names of the policy-forwarded pairs. +func (ia *incubatorArgs) suAllowEnvKeys() []string { + keys := make([]string, 0, 1+len(ia.forwardedEnv)) + keys = append(keys, "SSH_AUTH_SOCK") for _, kv := range ia.forwardedEnv { if k, _, ok := strings.Cut(kv, "="); ok { - allowedExtraKeys = append(allowedExtraKeys, k) + keys = append(keys, k) } } - return env, allowedExtraKeys + return keys } // beIncubator is the entrypoint to the `tailscaled be-child ssh` subcommand. @@ -572,7 +603,7 @@ func tryExecLogin(dlogf logger.Logf, ia incubatorArgs) error { loginArgs := ia.loginArgs(loginCmdPath) dlogf("logging in with %+v", loginArgs) - environ, _ := ia.forwardedEnviron() + environ := append(ia.rootExecEnviron(), ia.forwardedEnv...) // If Exec works, the Go code will not proceed past this: err = unix.Exec(loginCmdPath, loginArgs, environ) @@ -608,7 +639,10 @@ func trySU(dlogf logger.Logf, ia incubatorArgs) (handled bool, err error) { defer sessionCloser() } - environ, allowListEnvKeys := ia.forwardedEnviron() + // Pass forwarded pairs in su's environment and allow -w to copy + // them into the login shell's environment. + environ := append(ia.rootExecEnviron(), ia.forwardedEnv...) + allowListEnvKeys := ia.suAllowEnvKeys() loginArgs := []string{ su, @@ -653,18 +687,9 @@ func findSU(dlogf logger.Logf, ia incubatorArgs) string { return "" } - _, allowListEnvKeys := ia.forwardedEnviron() - // First try to execute su -w -l -c true // to make sure su supports the necessary arguments. - err = exec.Command( - su, - "-w", strings.Join(allowListEnvKeys, ","), - "-l", - ia.localUser, - "-c", "true", - ).Run() - if err != nil { + if err := suProbeCmd(ia, su).Run(); err != nil { dlogf("su check failed: %s", err) return "" } @@ -672,6 +697,20 @@ func findSU(dlogf logger.Logf, ia incubatorArgs) string { return su } +// suProbeCmd builds findSU's capability probe command. The probe runs +// su with rootExecEnviron. +func suProbeCmd(ia incubatorArgs, su string) *exec.Cmd { + cmd := exec.Command( + su, + "-w", strings.Join(ia.suAllowEnvKeys(), ","), + "-l", + ia.localUser, + "-c", "true", + ) + cmd.Env = ia.rootExecEnviron() + return cmd +} + // handleSSHInProcess is a last resort if we couldn't use login or su. It // registers a new session with the OS, sets its UID, GID and groups to the // specified values, and then launches the requested `--cmd` in the user's @@ -686,7 +725,8 @@ func handleSSHInProcess(dlogf logger.Logf, ia incubatorArgs) error { return err } - environ, _ := ia.forwardedEnviron() + // Build the shell environment after dropping privileges. + environ := ia.forwardedEnviron() args := shellArgs(ia.isShell, ia.cmd) dlogf("running %s %q", ia.loginShell, args) @@ -865,6 +905,13 @@ func (ss *sshSession) incubatorEnv() []string { env = append(env, kv) } } + // The pty request's TERM passes the same acceptEnvPair value rule as + // the environ-sourced TERM. It is assembled here, with the rest of + // the client-derived environment, so the client-derived pairs can be + // forwarded to the incubator through one channel; see launchProcess. + if ptyReq, _, isPty := ss.Pty(); isPty && ptyReq.Term != "" && acceptEnvPair("TERM="+ptyReq.Term) { + env = append(env, "TERM="+ptyReq.Term) + } ci := ss.conn.info env = append(env, @@ -879,9 +926,32 @@ func (ss *sshSession) incubatorEnv() []string { return env } +// mergeForwardedEnv adds default TERM and locale values not already present +// in forwarded. Defaults use last-value-wins, as exec.Cmd.Env does. +func mergeForwardedEnv(env, forwarded []string) []string { + seen := make(map[string]bool) + for _, kv := range forwarded { + k, _, _ := strings.Cut(kv, "=") + seen[k] = true + } + for _, kv := range slices.Backward(env) { + if k, _, ok := strings.Cut(kv, "="); ok && clientDerivedEnvKey(k) && !seen[k] { + forwarded = append(forwarded, kv) + seen[k] = true + } + } + return forwarded +} + // launchProcess launches an incubator process for the provided session. // It is responsible for configuring the process execution environment. -// The caller can wait for the process to exit by calling cmd.Wait(). +// The caller can wait for the process to exit by calling cmd.Wait() or, +// on the monitor path, by waiting on waitProcess's exit-notification +// wait. +// +// On unix with a tailscaled binary the child is exec'd by the conn's +// ssh-monitor via launchViaMonitor; the direct-exec fallback, with no +// tailscaled binary, and plan9 keep the direct start. // // It sets ss.cmd, stdin, stdout, and stderr. func (ss *sshSession) launchProcess() error { @@ -895,11 +965,21 @@ func (ss *sshSession) launchProcess() error { cmd := ss.cmd cmd.Env = ss.incubatorEnv() - if len(forwardedEnv) > 0 { - // The accepted environment may contain secrets, so it is passed to the child via an - // inherited file, never the argv or the environment. Closing after Start is safe: the - // child has its own copy by then. - envFile, err := forwardedEnvFile(forwardedEnv) + // Pass default TERM and locale variables through the environment pipe. + // Policy-forwarded values take precedence over these defaults. + if ss.conn.srv.tailscaledPath != "" { + forwardedEnv = mergeForwardedEnv(cmd.Env, forwardedEnv) + } + // Add --env-fd if the merged environment is non-empty. + if len(forwardedEnv) > 0 && !slices.Contains(cmd.Args, fmt.Sprintf("--env-fd=%d", forwardedEnvChildFD)) { + cmd.Args = append(cmd.Args, fmt.Sprintf("--env-fd=%d", forwardedEnvChildFD)) + } + + // Create the environment pipe for incubator sessions. Close the + // parent copy after launch; the child then owns its copy. + var envFile *os.File + if len(forwardedEnv) > 0 && ss.conn.srv.tailscaledPath != "" { + envFile, err = forwardedEnvFile(forwardedEnv) if err != nil { return err } @@ -910,7 +990,7 @@ func (ss *sshSession) launchProcess() error { ptyReq, winCh, isPty := ss.Pty() if !isPty { ss.logf("starting non-pty command: %+v", cmd.Args) - return ss.startWithStdPipes() + return ss.startWithStdPipes(envFile) } if sshDisablePTY() { @@ -919,37 +999,67 @@ func (ss *sshSession) launchProcess() error { } ss.ptyReq = &ptyReq - pty, tty, err := ss.startWithPTY() + pty, tty, err := ss.startWithPTY(envFile) if err != nil { return err } - // We need to be able to close stdin and stdout separately later so make a - // dup. - ptyDup, err := syscall.Dup(int(pty.Fd())) + // We need to be able to close stdin and stdout separately later so make + // dups. Use F_DUPFD_CLOEXEC rather than dup(2): a plain dup does not set + // FD_CLOEXEC, so the pty master would be inherited by every other SSH + // session's child process started while this session is alive. A leaked + // master keeps the pty open after this session ends, so its slave never + // hangs up and processes writing to it (e.g. a tmux server) block forever. + // + // The resize goroutine owns the second dup, so a window-change + // request acts on a descriptor held open for its goroutine's + // lifetime. + outDup, err := unix.FcntlInt(pty.Fd(), unix.F_DUPFD_CLOEXEC, 0) if err != nil { pty.Close() tty.Close() return err } - go resizeWindow(ptyDup /* arbitrary fd */, winCh) + resizeDup, err := unix.FcntlInt(pty.Fd(), unix.F_DUPFD_CLOEXEC, 0) + if err != nil { + unix.Close(outDup) + pty.Close() + tty.Close() + return err + } + go resizeWindow(os.NewFile(uintptr(resizeDup), pty.Name()), winCh) ss.wrStdin = pty - ss.rdStdout = os.NewFile(uintptr(ptyDup), pty.Name()) + ss.rdStdout = os.NewFile(uintptr(outDup), pty.Name()) ss.rdStderr = nil // not available for pty ss.childPipes = []io.Closer{tty} return nil } -func resizeWindow(fd int, winCh <-chan gliderssh.Window) { +// sessionViaMonitor reports whether this session's child is exec'd by +// the conn's ssh-monitor instead of being started directly by +// tailscaled. The monitor route requires a tailscaled binary; plan9 +// has no monitor. +func (ss *sshSession) sessionViaMonitor() bool { + return ss.conn.srv.tailscaledPath != "" +} + +// resizeWindow applies window-change requests to the session's pty +// master. It stops when the SSH channel closes its window channel or +// when the ioctl on the master fails. f is this goroutine's own +// descriptor of the master, held open for the goroutine's lifetime. +func resizeWindow(f *os.File, winCh <-chan gliderssh.Window) { + defer f.Close() for win := range winCh { - unix.IoctlSetWinsize(fd, syscall.TIOCSWINSZ, &unix.Winsize{ + if err := unix.IoctlSetWinsize(int(f.Fd()), syscall.TIOCSWINSZ, &unix.Winsize{ Row: uint16(win.Height), Col: uint16(win.Width), Xpixel: uint16(win.WidthPixels), Ypixel: uint16(win.HeightPixels), - }) + }); err != nil { + return + } } } @@ -1015,8 +1125,9 @@ var opcodeShortName = map[uint8]string{ ssh.TTY_OP_OSPEED: "tty_op_ospeed", } -// startWithPTY starts cmd with a pseudo-terminal attached to Stdin, Stdout and Stderr. -func (ss *sshSession) startWithPTY() (ptyFile, tty *os.File, err error) { +// startWithPTY starts the session with a pseudo-terminal as its stdio. +// On the monitor path, the slave descriptors are passed via SCM_RIGHTS. +func (ss *sshSession) startWithPTY(envFile *os.File) (ptyFile, tty *os.File, err error) { ptyReq := ss.ptyReq cmd := ss.cmd if cmd == nil { @@ -1091,10 +1202,6 @@ func (ss *sshSession) startWithPTY() (ptyFile, tty *os.File, err error) { if ctlErr != nil { return nil, nil, fmt.Errorf("ptyRawConn.Control func: %w", ctlErr) } - cmd.SysProcAttr = &syscall.SysProcAttr{ - Setctty: true, - Setsid: true, - } updateStringInSlice(cmd.Args, "--has-tty=false", "--has-tty=true") if ptyName, err := ptyName(ptyFile); err == nil { updateStringInSlice(cmd.Args, "--tty-name=", "--tty-name="+ptyName) @@ -1102,8 +1209,21 @@ func (ss *sshSession) startWithPTY() (ptyFile, tty *os.File, err error) { cmd.Env = append(cmd.Env, fmt.Sprintf("SSH_TTY=%s", fullPath)) } - if ptyReq.Term != "" { - cmd.Env = append(cmd.Env, fmt.Sprintf("TERM=%s", ptyReq.Term)) + // The pty request's TERM is assembled in incubatorEnv with the rest + // of the client-derived pairs, so it reaches the incubator through + // the accepted-pairs channel; see launchProcess. + + if ss.sessionViaMonitor() { + ss.logf("starting pty command via session monitor: %+v", cmd.Args) + if err := ss.launchViaMonitor(cmd, envFile, []*os.File{tty, tty, tty}, true); err != nil { + return nil, nil, err + } + return ptyFile, tty, nil + } + + cmd.SysProcAttr = &syscall.SysProcAttr{ + Setctty: true, + Setsid: true, } cmd.Stdin = tty cmd.Stdout = tty @@ -1117,8 +1237,11 @@ func (ss *sshSession) startWithPTY() (ptyFile, tty *os.File, err error) { } // startWithStdPipes starts cmd with os.Pipe for Stdin, Stdout and Stderr. -func (ss *sshSession) startWithStdPipes() (err error) { - var rdStdin, wrStdout, wrStderr io.ReadWriteCloser +// On the monitor path the child is exec'd by the conn's ssh-monitor via +// launchViaMonitor, which also carries the env-fd pipe; tailscaled +// keeps its own pipe ends in childPipes. +func (ss *sshSession) startWithStdPipes(envFile *os.File) (err error) { + var rdStdin, wrStdout, wrStderr *os.File defer func() { if err != nil { closeAll(rdStdin, ss.wrStdin, ss.rdStdout, wrStdout, ss.rdStderr, wrStderr) @@ -1136,10 +1259,13 @@ func (ss *sshSession) startWithStdPipes() (err error) { if ss.rdStderr, wrStderr, err = os.Pipe(); err != nil { return err } + ss.childPipes = []io.Closer{rdStdin, wrStdout, wrStderr} + if ss.sessionViaMonitor() { + return ss.launchViaMonitor(ss.cmd, envFile, []*os.File{rdStdin, wrStdout, wrStderr}, false) + } ss.cmd.Stdin = rdStdin ss.cmd.Stdout = wrStdout ss.cmd.Stderr = wrStderr - ss.childPipes = []io.Closer{rdStdin, wrStdout, wrStderr} return ss.cmd.Start() } diff --git a/ssh/tailssh/incubator_plan9.go b/ssh/tailssh/incubator_plan9.go index b9fcf41a4..6e4d02a61 100644 --- a/ssh/tailssh/incubator_plan9.go +++ b/ssh/tailssh/incubator_plan9.go @@ -424,6 +424,19 @@ func (ss *sshSession) startWithStdPipes() (err error) { return ss.cmd.Start() } +// waitMonitorProcess is the plan9 seam of the monitor session path. +// plan9 has no monitor, so it always reports the direct path. +func (ss *sshSession) waitMonitorProcess() (code int, ok bool, err error) { + return 0, false, nil +} + +// hangupMonitorProcess is the plan9 seam of the monitor session path. +// It always reports false, so sessions hang up their directly-started +// child. +func (ss *sshSession) hangupMonitorProcess() bool { + return false +} + func envForUser(u *userMeta) []string { return []string{ fmt.Sprintf("user=%s", u.Username), diff --git a/ssh/tailssh/incubator_test.go b/ssh/tailssh/incubator_test.go index 69f9e92a3..d72c049b1 100644 --- a/ssh/tailssh/incubator_test.go +++ b/ssh/tailssh/incubator_test.go @@ -19,9 +19,37 @@ import ( gliderssh "github.com/tailscale/gliderssh" "golang.org/x/sys/unix" "tailscale.com/tailcfg" + "tailscale.com/tailcfg/nodecap" "tailscale.com/types/logger" ) +func TestMergeForwardedEnv(t *testing.T) { + defaults := []string{ + "TERM=dumb", + "LANG=C", + "LC_TIME=C", + "TERM=xterm-256color", + "LANG=en_US.UTF-8", + "LC_TIME=en_US.UTF-8", + "HOME=/ignored", + } + for _, policyTerm := range []string{"", "policy-term"} { + var forwarded []string + wantTerm := "xterm-256color" + if policyTerm != "" { + forwarded = []string{"TERM=" + policyTerm} + wantTerm = policyTerm + } + got := mergeForwardedEnv(defaults, forwarded) + want := []string{"TERM=" + wantTerm, "LANG=en_US.UTF-8", "LC_TIME=en_US.UTF-8"} + slices.Sort(got) + slices.Sort(want) + if !slices.Equal(got, want) { + t.Errorf("mergeForwardedEnv = %q; want %q", got, want) + } + } +} + // fakeSession is a minimal gliderssh.Session for exercising the incubator // command/env construction. Only the methods used by newIncubatorCommand and // incubatorEnv are implemented; the embedded interface is nil, so any other @@ -49,7 +77,7 @@ func newTestSession(t *testing.T, acceptEnv []string, clientEnviron []string) *s logf: logger.Discard, lb: &localState{ sshEnabled: true, - caps: []tailcfg.NodeCapability{tailcfg.NodeAttrSSHEnvironmentVariables}, + caps: []nodecap.Cap{nodecap.SSHEnvironmentVariables}, }, // tailscaledPath must be non-empty to take the incubator (be-child) // path rather than the direct-exec fallback. @@ -193,19 +221,27 @@ func TestForwardedEnvFileRoundTrip(t *testing.T) { t.Errorf("forwardedEnv = %q, want %q", ia.forwardedEnv, pairs) } - // forwardedEnviron applies the pairs to the user's environment and names - // them in the "su -w" allowlist, alongside SSH_AUTH_SOCK. - env, keys := ia.forwardedEnviron() + // forwardedEnviron applies the pairs to the user's environment (the + // in-process, post-drop path only). + env := ia.forwardedEnviron() for _, p := range pairs { if !slices.Contains(env, p) { t.Errorf("pair %q missing from forwardedEnviron env", p) } } - for _, k := range []string{"SSH_AUTH_SOCK", "GITLAB_API_TOKEN", "PATH"} { - if !slices.Contains(keys, k) { - t.Errorf("allowlist missing %q: %q", k, keys) + // The su -w allowlist is SSH_AUTH_SOCK plus the forwarded keys. The + // pairs ride su's own environment. See + // TestRootExecEnvExcludesClientEnv for the TERM/LANG/LC_* exclusion + // from that environment. + want := []string{"SSH_AUTH_SOCK"} + for _, p := range pairs { + if k, _, ok := strings.Cut(p, "="); ok { + want = append(want, k) } } + if !slices.Equal(ia.suAllowEnvKeys(), want) { + t.Errorf("suAllowEnvKeys() = %q; want %q", ia.suAllowEnvKeys(), want) + } } // TestParseIncubatorArgsEnvFD verifies that --env-fd values naming @@ -244,16 +280,17 @@ func TestLoadForwardedEnvLegacyEncodedEnv(t *testing.T) { t.Errorf("forwardedEnv = %q, want %q", ia.forwardedEnv, pairs) } - env, keys := ia.forwardedEnviron() + env := ia.forwardedEnviron() for _, p := range pairs { if !slices.Contains(env, p) { t.Errorf("legacy pair %q missing from env", p) } } - for _, k := range []string{"SSH_AUTH_SOCK", "GITLAB_API_TOKEN", "OTHER"} { - if !slices.Contains(keys, k) { - t.Errorf("allowlist missing %q: %q", k, keys) - } + // The su -w allowlist names only the pairs that were forwarded plus + // the server-derived SSH_AUTH_SOCK. + empty := incubatorArgs{} + if keys := empty.suAllowEnvKeys(); !slices.Equal(keys, []string{"SSH_AUTH_SOCK"}) { + t.Errorf("suAllowEnvKeys() with no forwarded pairs = %q; want [SSH_AUTH_SOCK]", keys) } // Malformed values are rejected. @@ -284,9 +321,85 @@ func TestLoadForwardedEnvSanitizesPairs(t *testing.T) { if !slices.Equal(ia.forwardedEnv, []string{"GOOD=1"}) { t.Errorf("forwardedEnv = %q, want [GOOD=1]", ia.forwardedEnv) } - _, keys := ia.forwardedEnviron() - if !slices.Equal(keys, []string{"SSH_AUTH_SOCK", "GOOD"}) { - t.Errorf("allowlist = %q, want [SSH_AUTH_SOCK GOOD]", keys) +} + +// TestRootExecEnvExcludesClientEnv is the structural env regression +// test: the environment handed to root-exec'd login/su contains no +// client-derived pair, neither the acceptEnvPair set, the only +// client-controllable keys in the incubator's environment, nor +// anything from the forwarded env, while the post-drop environment +// from forwardedEnviron carries everything for the user's own session. +func TestRootExecEnvExcludesClientEnv(t *testing.T) { + ia := incubatorArgs{forwardedEnv: []string{ + "GITLAB_API_TOKEN=s3cr3t", + "LANG=xx_YY.UTF-8", + "LC_ALL=xx_YY.UTF-8", + }} + // The incubator's own environment is built by tailscaled (incubatorEnv: + // SHELL/USER/HOME/PATH/SSH_*, the server-set agent socket, and the + // client's acceptEnvPair'd pairs), so the test process's ambient + // TERM/LANG (if any) stands in for the client-derived ones. A daemon + // or root environment must never supply them to the user's process: + // they flow only through the forwarded pairs. + t.Setenv("TERM", "rootenv-xterm-256color") + root := ia.rootExecEnviron() + if len(root) == 0 && len(os.Environ()) > 0 { + t.Fatal("rootExecEnviron() = empty; want the server-derived environment") + } + for _, kv := range root { + k, _, _ := strings.Cut(kv, "=") + if clientDerivedEnvKey(k) { + t.Errorf("client-derived pair %q present in root-exec'd environment", kv) + } + } + // Every forwarded pair (secret or not) is absent from the root env but + // present in the post-drop env. + for _, pair := range ia.forwardedEnv { + if slices.Contains(root, pair) { + t.Errorf("forwarded pair %q present in root-exec'd environment", pair) + } + } + user := ia.forwardedEnviron() + for _, pair := range ia.forwardedEnv { + if !slices.Contains(user, pair) { + t.Errorf("forwarded pair %q missing from post-drop environment", pair) + } + } + // The post-drop environment takes TERM/LANG/LC_* only from the + // forwarded pairs: the ambient daemon-side TERM must not leak, and a + // client-derived key the client did not send stays absent. + got := map[string]string{} + for _, kv := range user { + k, v, _ := strings.Cut(kv, "=") + got[k] = v + } + if v, ok := got["TERM"]; ok { + t.Errorf("post-drop environment has TERM=%q; client sent none", v) + } + if got["LANG"] != "xx_YY.UTF-8" || got["LC_ALL"] != "xx_YY.UTF-8" { + t.Errorf("post-drop locale = LANG=%q LC_ALL=%q; want forwarded values", + got["LANG"], got["LC_ALL"]) + } + for _, k := range []string{"TERM", "LANG", "LC_ALL"} { + if !clientDerivedEnvKey(k) { + t.Errorf("clientDerivedEnvKey(%q) = false; want true", k) + } + } + for _, k := range []string{"HOME", "PATH", "SSH_CONNECTION", "SSH_AUTH_SOCK", "USER"} { + if clientDerivedEnvKey(k) { + t.Errorf("clientDerivedEnvKey(%q) = true; want false (server-derived)", k) + } + } + // findSU's capability probe runs su as root too, and its + // environment must obey the same contract. + probe := suProbeCmd(ia, "/bin/su") + if len(probe.Env) == 0 && len(os.Environ()) > 0 { + t.Fatal("suProbeCmd env = empty; want the filtered root-exec environment") + } + for _, kv := range probe.Env { + if k, _, _ := strings.Cut(kv, "="); clientDerivedEnvKey(k) { + t.Errorf("client-derived pair %q present in findSU probe environment", kv) + } } } diff --git a/ssh/tailssh/localstate_test.go b/ssh/tailssh/localstate_test.go index c64afc87e..1f27e6fa6 100644 --- a/ssh/tailssh/localstate_test.go +++ b/ssh/tailssh/localstate_test.go @@ -14,6 +14,7 @@ import ( "tailscale.com/net/tsdial" "tailscale.com/tailcfg" + "tailscale.com/tailcfg/nodecap" "tailscale.com/types/key" "tailscale.com/types/netmap" "tailscale.com/util/set" @@ -26,8 +27,8 @@ type localState struct { varRoot string // if empty, TailscaleVarRoot returns "" // caps, if non-empty, are advertised via NetMap().AllCaps. Used to gate - // features like NodeAttrSSHEnvironmentVariables in tests. - caps []tailcfg.NodeCapability + // features like nodecap.SSHEnvironmentVariables in tests. + caps []nodecap.Cap // serverActions is a map of the action name to the action. // It is served for paths like https://unused/ssh-action/. diff --git a/ssh/tailssh/monitor.go b/ssh/tailssh/monitor.go index ba7a15b13..e83427f8d 100644 --- a/ssh/tailssh/monitor.go +++ b/ssh/tailssh/monitor.go @@ -8,6 +8,13 @@ // authorized, and speaks the protocol of monitor_rpc.go over the // socketpair fd it inherits at spawn. // +// The monitor owns every child process the connection spawns. Session +// children are the incubator in incubator.go, spawned with the +// monitor's credentials because the incubator needs root to exec +// login and su and to register the login session. Forwarding children +// in fwdchild.go are one-shot dial and bind workers, spawned with the +// connection user's credentials. +// // The connection's identity, the uid, gid, and groups of its // localUser, is fixed in argv at spawn. Only the event loop touches // the RPC channel, the child table, and file descriptors. @@ -27,6 +34,7 @@ import ( "os/exec" "os/signal" "path/filepath" + "slices" "strconv" "strings" "syscall" @@ -55,8 +63,9 @@ const ( // child, a dialer or listener, reports its outcome in its op's reply, // and its exit is reaped silently by the sweep after its SIGCHLD. type monChild struct { - pgid int // the child's process group. Equal to its pid. - oneshot bool // dialer or listener child. Outcome carried by the op reply. + pgid int // the child's process group. Equal to its pid. + id int64 // exec request ID, or zero for a forwarding child + oneshot bool // dialer or listener child. Outcome carried by the op reply. } // monitor is the running ssh-monitor process state, owned entirely by @@ -315,6 +324,49 @@ func (m *monitor) handle(f rpcFrame, fds []int) { } } +// incubatorArgv requires and normalizes identity flags to the connection's +// bound identity. It accepts only the canonical --name=value spelling for +// these flags, rejecting aliases that could override a normalized value. +// The caller is trusted to supply the executable and remaining arguments. +func (m *monitor) incubatorArgv(argv []string) ([]string, error) { + values := map[string]string{ + "--uid=": formatID(m.args.uid), + "--gid=": formatID(m.args.gid), + "--groups=": joinGids(m.args.gids), + "--local-user=": m.args.localUser, + } + out := slices.Clone(argv) + seen := make(map[string]bool, len(values)) + for i, a := range argv[1:] { + name, _, _ := strings.Cut(strings.TrimLeft(a, "-"), "=") + if _, identity := values["--"+name+"="]; identity && !strings.HasPrefix(a, "--"+name+"=") { + return nil, fmt.Errorf("incubator exec: non-canonical identity flag %q", a) + } + for flag, val := range values { + if strings.HasPrefix(a, flag) { + out[i+1] = flag + val + seen[flag] = true + } + } + } + for flag := range values { + if !seen[flag] { + return nil, fmt.Errorf("incubator exec: argv has no %s flag", strings.TrimSuffix(flag, "=")) + } + } + return out, nil +} + +// joinGids renders a supplementary group list as the comma-separated +// form the incubator's --groups flag takes. +func joinGids(gids []uint32) string { + parts := make([]string, len(gids)) + for i, g := range gids { + parts[i] = formatID(g) + } + return strings.Join(parts, ",") +} + // handleExec spawns one child, mapping the request's file descriptors // to the child's stdio. monExecOpDeadline bounds the op from dispatch // to the return of cmd.Start; it does not bound the child's lifetime. @@ -328,11 +380,29 @@ func (m *monitor) handleExec(f rpcFrame, fds []int) { fail(errors.New("exec: empty argv")) return } + // An envfd exec must carry exactly four descriptors, stdio plus + // the --env-fd pipe. This re-check catches the fourth fd without + // the flag, which the codec's count check cannot see. + if f.EnvFd != (len(fds) == 4) { + fail(fmt.Errorf("exec: %d fds with envfd=%v; want 4 fds with envfd, or up to 3 without", len(fds), f.EnvFd)) + return + } // argv[0] must be an absolute path. if !filepath.IsAbs(f.Argv[0]) { fail(fmt.Errorf("exec: argv[0] must be an absolute path, got %q", f.Argv[0])) return } + // The incubator starts with monitor credentials so it can run login + // or su and register the login session before dropping privileges. + // Normalize its identity flags to the connection's bound identity. + if f.Incubator { + argv, err := m.incubatorArgv(f.Argv) + if err != nil { + fail(err) + return + } + f.Argv = argv + } cmd := exec.Command(f.Argv[0], f.Argv[1:]...) // Env is used exactly as given. An exec request with no env gives // the child an empty environment: the monitor's own environment @@ -343,22 +413,34 @@ func (m *monitor) handleExec(f rpcFrame, fds []int) { cmd.Env = []string{} // nil would inherit the monitor's environment } cmd.Dir = monChildDir(f.Dir) - // monStdio wraps the stdio descriptors. A failure before ownership - // moves to files closes every descriptor exactly once, in - // monStdio's error path. - files, err := monStdio(fds) + // monStdio wraps the stdio descriptors, fds[:3], with /dev/null + // for any missing stream, and takes ownership of them. The env-fd + // descriptor, fds[3], present exactly when EnvFd is set, is + // wrapped separately below. A failure before ownership moves + // closes every descriptor exactly once. + files, err := monStdio(fds[:min(3, len(fds))]) if err != nil { - // monStdio's error path already closed every descriptor. Nil - // the slice so fail's closeFds is a no-op rather than a double - // close. + // monStdio's error path already closed every descriptor it was + // given. The env-fd descriptor beyond the sub-slice is still + // ours. Nil the slice so fail's closeFds is a no-op rather than + // a double close. + closeFds(fds[min(3, len(fds)):]) fds = nil fail(err) return } - // From here the raw ints in fds are owned by files, each wrapped in - // an *os.File that closes it exactly once. Clearing the slice makes - // every later fail() a no-op for them instead of a double close. + // From here the raw stdio ints are owned by files, each wrapped in + // an *os.File that closes it exactly once. + var envFile *os.File + if len(fds) == 4 { + envFile = os.NewFile(uintptr(fds[3]), "ssh-monitor-child-envfd") + defer envFile.Close() + } + // The files now own these descriptors; fail must not close them again. fds = nil + if envFile != nil { + cmd.ExtraFiles = []*os.File{envFile} + } cmd.Stdin, cmd.Stdout, cmd.Stderr = files[0], files[1], files[2] cmd.SysProcAttr = monChildAttr(f.Ctty) // Re-scrub before the fork: anything opened or received since entry @@ -388,7 +470,7 @@ func (m *monitor) handleExec(f rpcFrame, fds []int) { return } // Its pgid is its pid. See monChildAttr. - m.children[cmd.Process.Pid] = &monChild{pgid: cmd.Process.Pid} + m.children[cmd.Process.Pid] = &monChild{pgid: cmd.Process.Pid, id: f.ID} m.reply(rpcExecReply(f.ID, cmd.Process.Pid)) } @@ -408,13 +490,12 @@ func killGroupAndReap(pid int) (reaped bool) { return false } -// handleSignal signals a child process *group* whose pid is validated -// against the monitor's child table. +// handleSignal validates both PID and generation before signaling a child group. func (m *monitor) handleSignal(f rpcFrame) { replyErr := func(err error) { m.reply(rpcErrReply(f.ID, opSignal, err)) } c, ok := m.children[f.Pid] - if !ok { - replyErr(fmt.Errorf("signal: pid %d is not a monitor child", f.Pid)) + if !ok || f.ChildID == 0 || c.id != f.ChildID { + replyErr(fmt.Errorf("signal: pid %d with child ID %d is not a monitor child", f.Pid, f.ChildID)) return } sig := unix.SignalNum(f.Sig) @@ -597,7 +678,7 @@ func (m *monitor) sweep(notify bool) { delete(m.children, pid) case wpid == pid: if notify && !c.oneshot { - m.notifyExit(pid, monExitCode(ws)) + m.notifyExit(monitorProcess{PID: pid, ID: c.id}, monExitCode(ws)) } delete(m.children, pid) } @@ -644,15 +725,18 @@ func (m *monitor) reply(f rpcFrame) { } } -func (m *monitor) notifyExit(pid, code int) { - m.reply(rpcExitNotify(pid, code)) +func (m *monitor) notifyExit(child monitorProcess, code int) { + m.reply(rpcExitNotify(child, code)) } // teardown is the monitor's orderly exit path, reached from RPC EOF, a // protocol error, or an external SIGHUP. It SIGHUPs every child group, // runs a brief bounded reap sweep, then SIGKILLs every group that -// survived the HUP and reaps again. Children that survive even the -// SIGKILL are abandoned in their own groups. +// survived the HUP and reaps again. A session-level escalation timer +// in sessmonitor.go, when one was scheduled, fails its Signal against +// this closed RPC channel, so the monitor's own teardown performs the +// SIGKILL. Children that survive even the SIGKILL are abandoned in +// their own groups. func (m *monitor) teardown() { // Release every descriptor parked for an fdack: the peer is going // away or gone, so no acknowledgment will arrive. diff --git a/ssh/tailssh/monitor_client.go b/ssh/tailssh/monitor_client.go index 10400b95c..927ed8f61 100644 --- a/ssh/tailssh/monitor_client.go +++ b/ssh/tailssh/monitor_client.go @@ -8,8 +8,8 @@ // current binary. It multiplexes request IDs, dispatches unsolicited // exit notifications, and serializes writes. // -// Dial, Listen, and ListenAgent implement the conn's forwarding socket -// ops. +// Dial, Listen, and ListenAgent serve the conn's forwarding paths, +// and Exec serves the session path. package tailssh @@ -87,7 +87,7 @@ type monitorClient struct { mu sync.Mutex // guards the fields below nextID int64 pending map[int64]chan *rpcResult - onExit func(pid, code int) + onExit func(monitorProcess, int) closed bool // done is closed when the read loop exits, on RPC EOF or a read @@ -102,6 +102,8 @@ func (mc *monitorClient) Pid() int { func (mc *monitorClient) readLoop() { defer close(mc.done) + // A protocol/read failure must also trigger monitor teardown. + defer mc.c.Close() for { f, fds, err := mc.rpc.readFrame() if err != nil { @@ -134,7 +136,7 @@ func (mc *monitorClient) dispatch(f rpcFrame, fds []int) { h := mc.onExit mc.mu.Unlock() if h != nil { - h(f.Pid, f.Code) + h(monitorProcess{PID: f.Pid, ID: f.ChildID}, f.Code) } } // Other unsolicited frames are ignored. @@ -153,12 +155,14 @@ func (mc *monitorClient) dispatch(f rpcFrame, fds []int) { mc.mu.Unlock() } -// call sends one request and waits for its reply (with any descriptors it -// carries), the context, or the RPC channel's death. On every path that -// does not hand the descriptors to the caller they are closed exactly -// once. See dispatch for the race-free handoff. +// call sends a request and waits for its reply, cancellation, or channel death. +// Dispatched exec requests ignore cancellation so their child handles cannot be +// lost. Descriptors not handed to the caller are closed here or by dispatch. func (mc *monitorClient) call(ctx context.Context, f rpcFrame, fds ...int) (rpcFrame, []int, error) { var zero rpcFrame + if err := ctx.Err(); err != nil { + return zero, nil, err + } mc.mu.Lock() if mc.closed { mc.mu.Unlock() @@ -172,7 +176,10 @@ func (mc *monitorClient) call(ctx context.Context, f rpcFrame, fds ...int) (rpcF mc.mu.Unlock() mc.writeMu.Lock() - err := mc.rpc.writeFrame(f, fds...) + err := ctx.Err() + if err == nil { + err = mc.rpc.writeFrame(f, fds...) + } mc.writeMu.Unlock() if err != nil { mc.mu.Lock() @@ -181,6 +188,13 @@ func (mc *monitorClient) call(ctx context.Context, f rpcFrame, fds ...int) (rpcF return zero, nil, fmt.Errorf("ssh-monitor: write %q: %w", f.Op, err) } + done := ctx.Done() + if f.Op == opExec { + // Once dispatched, exec must return its child handle even if the + // session is canceled. The caller then owns termination and waiting. + // Monitor death also ends this wait and tears down its children. + done = nil + } select { case r := <-ch: if !r.f.OK { @@ -188,7 +202,7 @@ func (mc *monitorClient) call(ctx context.Context, f rpcFrame, fds ...int) (rpcF return r.f, nil, errors.New("ssh-monitor: " + r.f.Err) } return r.f, r.fds, nil - case <-ctx.Done(): + case <-done: // Delete the entry under the lock: after this, dispatch finds no // waiter and closes a late reply's descriptors itself. A reply // already sitting in the channel is drained here and closed. @@ -214,40 +228,86 @@ func (mc *monitorClient) call(ctx context.Context, f rpcFrame, fds ...int) (rpcF } } -// SetExitCallback registers h for unsolicited exit notifications from the -// monitor, one call per reaped child with the child's pid and exit code. -// It may be replaced at any time. nil disables delivery. -func (mc *monitorClient) SetExitCallback(h func(pid, code int)) { +// SetExitCallback registers h for unsolicited child exit notifications. +// nil disables delivery. +func (mc *monitorClient) SetExitCallback(h func(monitorProcess, int)) { mc.mu.Lock() mc.onExit = h mc.mu.Unlock() } +// Gone returns a channel closed when the RPC read loop exits. +func (mc *monitorClient) Gone() <-chan struct{} { + return mc.done +} + // Ping round-trips a ping request. func (mc *monitorClient) Ping(ctx context.Context) error { _, _, err := mc.call(ctx, rpcPingReq(0)) return err } -// Exec spawns a child on the monitor with the given stdio descriptors, -// stdin, stdout, and stderr in order. It returns the child's pid. The -// child's exit arrives later via the exit callback. -func (mc *monitorClient) Exec(ctx context.Context, argv, env []string, dir string, ctty bool, stdio ...*os.File) (int, error) { - fds := make([]int, len(stdio)) - for i, f := range stdio { - fds[i] = int(f.Fd()) +// execRequest builds an exec frame and descriptor list. envFile, when +// present, follows stdio and becomes the child's fd 3. +func execRequest(argv, env []string, dir string, ctty bool, envFile *os.File, stdio []*os.File) (rpcFrame, []int) { + fds := make([]int, 0, len(stdio)+1) + for _, f := range stdio { + fds = append(fds, int(f.Fd())) } - f := rpcExecReq(0, argv, env, dir, ctty, len(fds)) + if envFile != nil { + fds = append(fds, int(envFile.Fd())) + } + f := rpcExecReq(0, argv, env, dir, ctty, envFile != nil, len(fds)) + return f, fds +} + +// execOnMonitor sends an exec frame and returns the child handle. +func (mc *monitorClient) execOnMonitor(ctx context.Context, f rpcFrame, fds []int) (monitorProcess, error) { r, _, err := mc.call(ctx, f, fds...) if err != nil { - return 0, err + return monitorProcess{}, err } - return r.Pid, nil + if r.Pid <= 0 || r.ChildID == 0 || r.ChildID != r.ID { + mc.c.Close() + return monitorProcess{}, errors.New("ssh-monitor: invalid exec child handle") + } + return monitorProcess{PID: r.Pid, ID: r.ChildID}, nil +} + +// Exec launches trusted argv with the given environment and directory. +// Once dispatched, it waits for the child handle or monitor death even if +// ctx is canceled; the caller owns termination of a successfully launched child. +func (mc *monitorClient) Exec( + ctx context.Context, + argv, env []string, + dir string, + ctty bool, + envFile *os.File, + stdio ...*os.File, +) (monitorProcess, error) { + f, fds := execRequest(argv, env, dir, ctty, envFile, stdio) + return mc.execOnMonitor(ctx, f, fds) +} + +// ExecIncubator launches a trusted incubator invocation with its identity +// flags normalized to the monitor's bound identity. Like Exec, it returns +// the child handle even if ctx is canceled after dispatch. +func (mc *monitorClient) ExecIncubator( + ctx context.Context, + argv, env []string, + dir string, + ctty bool, + envFile *os.File, + stdio ...*os.File, +) (monitorProcess, error) { + f, fds := execRequest(argv, env, dir, ctty, envFile, stdio) + f.Incubator = true + return mc.execOnMonitor(ctx, f, fds) } // Signal asks the monitor to signal a child process group. -func (mc *monitorClient) Signal(ctx context.Context, pid int, sig string) error { - _, _, err := mc.call(ctx, rpcSignalReq(0, pid, sig)) +func (mc *monitorClient) Signal(ctx context.Context, child monitorProcess, sig string) error { + _, _, err := mc.call(ctx, rpcSignalReq(0, child, sig)) return err } @@ -324,7 +384,8 @@ func wrapListenerFD(fd int, name string) (net.Listener, error) { // Close tears the connection down by closing the RPC channel, which // triggers the monitor's teardown. Close waits for the monitor to -// exit. A wedged monitor is killed after 5 seconds. +// exit. A wedged monitor is killed after the forwarding-op deadline, +// both teardown reap sweeps, and a margin for scheduling and child reap. func (mc *monitorClient) Close() error { mc.mu.Lock() if mc.closed { @@ -341,7 +402,7 @@ func (mc *monitorClient) Close() error { select { case err := <-waitErr: return err - case <-time.After(5 * time.Second): + case <-time.After(monFwdOpDeadline + 2*monTeardownReap + 5*time.Second): mc.cmd.Process.Kill() return <-waitErr } diff --git a/ssh/tailssh/monitor_lifecycle_test.go b/ssh/tailssh/monitor_lifecycle_test.go new file mode 100644 index 000000000..bac9a5d93 --- /dev/null +++ b/ssh/tailssh/monitor_lifecycle_test.go @@ -0,0 +1,289 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build (linux && !android) || (darwin && !ios) || freebsd || openbsd + +package tailssh + +import ( + "context" + "io" + "os" + "os/exec" + "strings" + "testing" + "time" +) + +// TestMonitorExecCancellationAfterDispatch delays the exec reply until after +// cancellation. The session must retain the child handle and terminate it. +func TestMonitorExecCancellationAfterDispatch(t *testing.T) { + client, peer := rpcTestPair(t) + mc := &monitorClient{ + c: client.c, + rpc: client, + pending: make(map[int64]chan *rpcResult), + done: make(chan struct{}), + } + go mc.readLoop() + t.Cleanup(func() { + client.c.Close() + <-mc.done + }) + c := &conn{srv: &server{logf: t.Logf}} + c.fwd.mon = mc + mc.SetExitCallback(c.fwd.exits.dispatchExit) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + ss := &sshSession{conn: c, ctx: ctx, logf: t.Logf} + f, err := os.OpenFile(os.DevNull, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + defer f.Close() + launched := make(chan error, 1) + cmd := exec.Command("/unused/incubator") + stdio := []*os.File{f, f, f} + go func() { + launched <- ss.launchViaMonitor(cmd, nil, stdio, false) + }() + frame, fds, err := peer.readFrame() + closeFds(fds) + if err != nil { + t.Fatal(err) + } + if frame.Op != opExec { + t.Fatalf("op=%s; want exec", frame.Op) + } + cancel() + child := monitorProcess{PID: 42, ID: frame.ID} + if err := peer.writeFrame(rpcExecReply(frame.ID, child.PID)); err != nil { + t.Fatal(err) + } + select { + case err := <-launched: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("exec did not return its reply") + } + if ss.monChild != child { + t.Fatalf("child=%v; want %v", ss.monChild, child) + } + + hungup := make(chan bool, 1) + go func() { hungup <- ss.hangupMonitorProcess() }() + frame, fds, err = peer.readFrame() + closeFds(fds) + if err != nil { + t.Fatal(err) + } + if frame.Op != opSignal || frame.Pid != child.PID || frame.ChildID != child.ID || frame.Sig != "SIGHUP" { + t.Fatalf("hangup frame=%+v", frame) + } + if err := peer.writeFrame(rpcOKReply(frame.ID, opSignal)); err != nil { + t.Fatal(err) + } + if !<-hungup { + t.Fatal("canceled session lost its monitor child") + } + if err := peer.writeFrame(rpcExitNotify(child, 129)); err != nil { + t.Fatal(err) + } + select { + case <-ss.monExit.done: + case <-time.After(5 * time.Second): + t.Fatal("exit notification not delivered") + } + // Escalation must neither consume the result nor send another signal. + ss.escalateMonitorProcess(mc) + for range 2 { + code, ok, err := ss.waitMonitorProcess() + if code != 129 || !ok || err != nil { + t.Fatalf("wait=(%d,%v,%v)", code, ok, err) + } + } +} + +// A locally rejected request must not kill other sessions on the connection. +func TestMonitorValidationFailureKeepsChannel(t *testing.T) { + for _, tt := range []struct { + name string + frame rpcFrame + nfds int + wantErr string + }{ + {"line_cap", rpcExecReq(0, []string{strings.Repeat("x", rpcMaxLine)}, nil, "", false, false, 1), 1, "line cap"}, + {"fd_count", rpcExecReq(0, []string{"/bin/true"}, nil, "", false, false, rpcMaxFds+1), rpcMaxFds + 1, "cannot carry"}, + {"op_fd_count", rpcPingReq(0), 1, "cannot carry"}, + } { + t.Run(tt.name, func(t *testing.T) { + mc := startTestMonitor(t, os.Getuid(), os.Getgid(), testGroups(t)) + exits := collectExits(mc) + child, err := mc.Exec(mustCtx(t), []string{"/bin/sleep", "30"}, nil, "/", false, nil) + if err != nil { + t.Fatal(err) + } + fds := make([]int, tt.nfds) + for i := range fds { + fds[i] = devNullFd(t) + } + _, _, err = mc.call(mustCtx(t), tt.frame, fds...) + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("call error = %v; want %q", err, tt.wantErr) + } + mc.mu.Lock() + npending := len(mc.pending) + mc.mu.Unlock() + if npending != 0 { + t.Fatalf("pending requests = %d; want 0", npending) + } + if err := mc.Ping(mustCtx(t)); err != nil { + t.Fatalf("ping after validation failure: %v", err) + } + if err := mc.Signal(mustCtx(t), child, "SIGTERM"); err != nil { + t.Fatal(err) + } + note := waitExitNote(t, exits, 5*time.Second) + if note.pid != child || note.code != 143 { + t.Fatalf("exit=%+v; want child=%+v code=143", note, child) + } + }) + } +} + +func TestMonitorWriteFailureClosesChannel(t *testing.T) { + for _, partial := range []bool{false, true} { + name := "closed_write" + if partial { + name = "partial_write" + } + t.Run(name, func(t *testing.T) { + client, peer := rpcTestPair(t) + mc := &monitorClient{ + c: client.c, + rpc: client, + pending: make(map[int64]chan *rpcResult), + done: make(chan struct{}), + } + go mc.readLoop() + t.Cleanup(func() { + client.c.Close() + <-mc.done + }) + frame := rpcPingReq(0) + if partial { + if err := client.c.SetWriteBuffer(1024); err != nil { + t.Fatal(err) + } + client.writeTimeout = 100 * time.Millisecond + frame = rpcExecReq(0, []string{strings.Repeat("x", 100<<10)}, nil, "", false, false, 0) + } else if err := client.c.CloseWrite(); err != nil { + t.Fatal(err) + } + if _, _, err := mc.call(mustCtx(t), frame); err == nil { + t.Fatal("write succeeded unexpectedly") + } + select { + case <-mc.done: + case <-time.After(5 * time.Second): + t.Fatal("write failure did not close the channel") + } + if err := peer.c.SetReadDeadline(time.Now().Add(time.Second)); err != nil { + t.Fatal(err) + } + // Drain any partial frame and verify EOF triggers peer teardown. + n, err := io.Copy(io.Discard, peer.c) + if err != nil { + t.Fatalf("drain peer: %v; want EOF", err) + } + if partial && (n == 0 || n >= 100<<10) { + t.Fatalf("wrote %d bytes; want a partial frame", n) + } + }) + } +} + +func TestMonitorReadFailureClosesChannel(t *testing.T) { + client, peer := rpcTestPair(t) + mc := &monitorClient{ + c: client.c, + rpc: client, + pending: make(map[int64]chan *rpcResult), + done: make(chan struct{}), + } + go mc.readLoop() + t.Cleanup(func() { + client.c.Close() + <-mc.done + }) + if _, err := peer.c.Write([]byte("invalid JSON\n")); err != nil { + t.Fatal(err) + } + select { + case <-mc.done: + case <-time.After(5 * time.Second): + t.Fatal("read loop did not reject the invalid frame") + } + if err := peer.c.SetReadDeadline(time.Now().Add(time.Second)); err != nil { + t.Fatal(err) + } + var b [1]byte + if _, err := peer.c.Read(b[:]); err != io.EOF { + t.Fatalf("peer read = %v; want EOF to trigger monitor teardown", err) + } +} + +func TestMonitorRejectsStaleChildHandle(t *testing.T) { + mc := startTestMonitor(t, os.Getuid(), os.Getgid(), testGroups(t)) + exits := collectExits(mc) + child, err := mc.Exec(mustCtx(t), []string{"/bin/sleep", "30"}, nil, "/", false, nil) + if err != nil { + t.Fatal(err) + } + stale := child + stale.ID++ + if err := mc.Signal(mustCtx(t), stale, "SIGKILL"); err == nil { + t.Fatal("signal accepted a mismatched child generation") + } + if err := mc.Signal(mustCtx(t), child, "SIGTERM"); err != nil { + t.Fatal(err) + } + note := waitExitNote(t, exits, 5*time.Second) + if note.pid != child || note.code != 143 { + t.Fatalf("exit=%+v; want child=%+v code=143", note, child) + } +} + +func TestIncubatorRejectsIdentityAliases(t *testing.T) { + m := &monitor{ + args: monitorArgs{ + uid: 1000, + gid: 1000, + gids: []uint32{1000}, + localUser: "ubuntu", + }, + } + for _, alias := range [][]string{ + {"-uid=0"}, + {"--uid", "0"}, + {"-gid=0"}, + {"--gid", "0"}, + {"-groups=0"}, + {"--groups", "0"}, + {"-local-user=root"}, + {"--local-user", "root"}, + } { + argv := append([]string{ + "/tailscaled", "be-child", "ssh", + "--uid=1", + "--gid=1", + "--groups=1", + "--local-user=alice", + }, alias...) + if _, err := m.incubatorArgv(argv); err == nil { + t.Errorf("accepted identity alias %q", alias) + } + } +} diff --git a/ssh/tailssh/monitor_rpc.go b/ssh/tailssh/monitor_rpc.go index a848ebbc9..df11662f8 100644 --- a/ssh/tailssh/monitor_rpc.go +++ b/ssh/tailssh/monitor_rpc.go @@ -12,7 +12,7 @@ // // {"id":N,"op":"dial","net":"unix","addr":"/run/user/1000/x.sock"} request // {"id":N,"op":"dial","ok":true} reply carrying at most one fd -// {"op":"exit","pid":123,"code":0} unsolicited notification +// {"op":"exit","pid":123,"childID":1,"code":0} unsolicited notification // // The caller assigns request IDs and replies echo them. The codec // decodes and encodes frames and descriptors. ID bookkeeping, read @@ -54,10 +54,10 @@ import ( const ( opDial = "dial" // request {net:"unix", addr}. reply {ok} + connected fd opListen = "listen" // request {net:"unix"|"tcp", addr, unlink?, agent?}. reply {ok, path} + listener fd - opExec = "exec" // request {argv, env, dir?, ctty?, fds:0-3} + up to 3 SCM_RIGHTS stdio fds. reply {ok, pid} - opSignal = "signal" // request {pid, sig}. reply {ok} + opExec = "exec" // request {argv, env, dir?, ctty?, envfd?, fds:0-4} + SCM_RIGHTS fds. reply {ok, pid, childID} + opSignal = "signal" // request {pid, childID, sig}. reply {ok} opPing = "ping" // request {}. reply {ok} - opExit = "exit" // unsolicited notification {pid, code}. no ID + 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 ) @@ -68,8 +68,9 @@ const ( rpcMaxLine = 256 << 10 // rpcMaxFds is the maximum number of SCM_RIGHTS descriptors any one - // frame may carry: exec passes child stdin, stdout and stderr. - rpcMaxFds = 3 + // frame may carry. Exec passes child stdin, stdout and stderr plus + // the env-fd pipe declared by rpcFrame.EnvFd. + rpcMaxFds = 4 // rpcFdHerald is the one-byte payload of the message that carries a // frame's descriptors. It is a NUL byte, which never appears inside @@ -115,11 +116,21 @@ type rpcFrame struct { Dir string `json:"dir,omitempty"` Ctty bool `json:"ctty,omitzero"` Fds int `json:"fds,omitzero"` + // EnvFd, when set on an exec request, declares a fourth descriptor + // after stdin, stdout, and stderr: the --env-fd payload pipe for + // the forwarded client env pairs. + EnvFd bool `json:"envfd,omitzero"` + + // Incubator requests identity-flag normalization for an incubator argv. + // The RPC caller is trusted to supply the executable and other arguments; + // this flag is not a privilege boundary against tailscaled. + Incubator bool `json:"incubator,omitzero"` // signal request, exit notification, and exec reply. - Pid int `json:"pid,omitzero"` - Sig string `json:"sig,omitempty"` - Code int `json:"code,omitzero"` // exit notification only + Pid int `json:"pid,omitzero"` + ChildID int64 `json:"childID,omitzero"` // exec request ID; required for signals + Sig string `json:"sig,omitempty"` + Code int `json:"code,omitzero"` // exit notification only // Reply fields. OK bool `json:"ok,omitzero"` @@ -139,19 +150,18 @@ func rpcListenReq(id int64, network, addr string, unlink, agent bool) rpcFrame { return rpcFrame{ID: id, Op: opListen, Net: network, Addr: addr, Unlink: unlink, Agent: agent} } -func rpcExecReq(id int64, argv, env []string, dir string, ctty bool, nfds int) rpcFrame { - return rpcFrame{ID: id, Op: opExec, Argv: argv, Env: env, Dir: dir, Ctty: ctty, Fds: nfds} +func rpcExecReq(id int64, argv, env []string, dir string, ctty, envFd bool, nfds int) rpcFrame { + return rpcFrame{ID: id, Op: opExec, Argv: argv, Env: env, Dir: dir, Ctty: ctty, EnvFd: envFd, Fds: nfds} } -func rpcSignalReq(id int64, pid int, sig string) rpcFrame { - return rpcFrame{ID: id, Op: opSignal, Pid: pid, Sig: sig} +func rpcSignalReq(id int64, child monitorProcess, sig string) rpcFrame { + return rpcFrame{ID: id, Op: opSignal, Pid: child.PID, ChildID: child.ID, Sig: sig} } -// rpcExecReply is the reply to an exec request, OK plus the spawned -// child's pid. The child's exit arrives later as an unsolicited exit -// notification. The notification carries this pid. +// rpcExecReply returns the PID and generation of the spawned child. +// Signals and exit notifications carry the same pair. func rpcExecReply(id int64, pid int) rpcFrame { - return rpcFrame{ID: id, Op: opExec, OK: true, Pid: pid} + return rpcFrame{ID: id, Op: opExec, OK: true, Pid: pid, ChildID: id} } func rpcOKReply(id int64, op string) rpcFrame { @@ -163,8 +173,8 @@ func rpcErrReply(id int64, op string, err error) rpcFrame { } // rpcExitNotify is the unsolicited child-exit notification frame. -func rpcExitNotify(pid, code int) rpcFrame { - return rpcFrame{Op: opExit, Pid: pid, Code: code} +func rpcExitNotify(child monitorProcess, code int) rpcFrame { + return rpcFrame{Op: opExit, Pid: child.PID, ChildID: child.ID, Code: code} } // rpcFdAckReq acknowledges receipt of the descriptors a reply with the @@ -197,6 +207,9 @@ func (f rpcFrame) checkFds(n int) error { if f.Op == opExec && f.Fds > 0 && f.Fds != n { return fmt.Errorf("monitor rpc: exec declared %d fds but %d arrived", f.Fds, n) } + if f.Op == opExec && f.EnvFd && n != 4 { + return fmt.Errorf("monitor rpc: envfd exec carried %d fds, want exactly 4 (stdio + env fd)", n) + } return nil } @@ -248,40 +261,50 @@ func heraldFrames(rbuf []byte, sets [][]int, queued func(k int) bool) ([]int, er // returned, and marks every received descriptor close-on-exec before // returning. The caller owns the returned descriptors. func recvFdSets(oob []byte, flags int) ([][]int, error) { - if flags&unix.MSG_CTRUNC != 0 { - // The OOB buffer was too small for the incoming cmsgs; the - // kernel has already closed the descriptors that did not fit. - return nil, errors.New("monitor rpc: ancillary data truncated (more fds than the protocol allows)") - } - if len(oob) == 0 { - return nil, nil - } - cmsgs, err := unix.ParseSocketControlMessage(oob) - if err != nil { - return nil, err - } var sets [][]int var all []int - for _, cm := range cmsgs { - if cm.Header.Level != unix.SOL_SOCKET || cm.Header.Type != unix.SCM_RIGHTS { - return nil, fmt.Errorf("monitor rpc: unexpected control message (level %d, type %d)", cm.Header.Level, cm.Header.Type) - } - got, err := unix.ParseUnixRights(&cm) + fail := func(err error) ([][]int, error) { + closeFds(all) + return nil, err + } + var unexpected error + // Parse one cmsg at a time so rights already parsed are still owned + // (and can be closed) if a later control message is rejected. + for len(oob) >= unix.CmsgLen(0) { + hdr, data, rest, err := unix.ParseOneSocketControlMessage(oob) if err != nil { - closeFds(all) - return nil, err + return fail(err) } - for _, fd := range got { - if _, err := unix.FcntlInt(uintptr(fd), unix.F_SETFD, unix.FD_CLOEXEC); err != nil { - closeFds(append(all, got...)) - return nil, err + oob = rest + if hdr.Level != unix.SOL_SOCKET || hdr.Type != unix.SCM_RIGHTS { + if unexpected == nil { + unexpected = fmt.Errorf("monitor rpc: unexpected control message (level %d, type %d)", hdr.Level, hdr.Type) } + continue // Later cmsgs may still contain received rights. + } + got, err := unix.ParseUnixRights(&unix.SocketControlMessage{Header: hdr, Data: data}) + if err != nil { + return fail(err) } sets = append(sets, got) all = append(all, got...) + } + if flags&unix.MSG_CTRUNC != 0 { + // The kernel closed the descriptors that did not fit; close the + // subset it installed in our process before rejecting the read. + return fail(errors.New("monitor rpc: ancillary data truncated (more fds than the protocol allows)")) + } + if unexpected != nil { + return fail(unexpected) + } + for _, got := range sets { + for _, fd := range got { + if _, err := unix.FcntlInt(uintptr(fd), unix.F_SETFD, unix.FD_CLOEXEC); err != nil { + return fail(err) + } + } if len(got) > rpcMaxFds { - closeFds(all) - return nil, fmt.Errorf("monitor rpc: frame carried %d fds; protocol allows at most %d", len(got), rpcMaxFds) + return fail(fmt.Errorf("monitor rpc: frame carried %d fds; protocol allows at most %d", len(got), rpcMaxFds)) } } return sets, nil @@ -492,7 +515,9 @@ func (m *rpcConn) readFrame() (f rpcFrame, fds []int, err error) { } // writeFrame encodes f as one JSON line and writes it. See sendFds for -// descriptor attachment and ownership. +// descriptor attachment and ownership. Validation errors leave the channel +// usable. Transport errors close it: a partial write leaves the request outcome +// unknown, so the peer must tear down any children it started. func (m *rpcConn) writeFrame(f rpcFrame, fds ...int) error { if len(fds) > maxFdsForOp(f.Op) { return fmt.Errorf("monitor rpc: op %q cannot carry %d fds", f.Op, len(fds)) @@ -506,10 +531,15 @@ func (m *rpcConn) writeFrame(f rpcFrame, fds ...int) error { return fmt.Errorf("monitor rpc: frame of %d bytes exceeds %d-byte line cap", len(b), rpcMaxLine) } if err := m.c.SetWriteDeadline(time.Now().Add(m.writeTimeout)); err != nil { + m.c.Close() return err } defer m.c.SetWriteDeadline(time.Time{}) - return writeLine(unixSender{m.c}, b, fds) + if err := writeLine(unixSender{m.c}, b, fds); err != nil { + m.c.Close() + return err + } + return nil } // wrapUnixConn wraps a raw file descriptor in a *net.UnixConn for read, diff --git a/ssh/tailssh/monitor_rpc_linux_test.go b/ssh/tailssh/monitor_rpc_linux_test.go new file mode 100644 index 000000000..abf19a9b2 --- /dev/null +++ b/ssh/tailssh/monitor_rpc_linux_test.go @@ -0,0 +1,123 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build linux && !android + +package tailssh + +import ( + "testing" + + "golang.org/x/sys/unix" +) + +// Regression assertion for rejected SCM_RIGHTS ancillary data: any subset +// installed by the kernel must be closed, even when MSG_CTRUNC is set. +func TestMonitorRPCAncillaryTruncationDoesNotLeak(t *testing.T) { + pair, err := unix.Socketpair(unix.AF_UNIX, unix.SOCK_STREAM, 0) + if err != nil { + t.Fatal(err) + } + defer unix.Close(pair[0]) + defer unix.Close(pair[1]) + var original []int + defer func() { closeFds(original) }() + for range 4 { + fd, e := unix.Open("/dev/null", unix.O_RDONLY|unix.O_CLOEXEC, 0) + if e != nil { + t.Fatal(e) + } + original = append(original, fd) + } + if err := unix.Sendmsg(pair[0], []byte("x"), unix.UnixRights(original...), nil, 0); err != nil { + t.Fatal(err) + } + b, oob := make([]byte, 8), make([]byte, unix.CmsgSpace(4)) + _, on, flags, _, err := unix.Recvmsg(pair[1], b, oob, unix.MSG_CMSG_CLOEXEC) + if err != nil { + t.Fatal(err) + } + if flags&unix.MSG_CTRUNC == 0 { + t.Fatalf("expected MSG_CTRUNC, flags=%x", flags) + } + _, recvErr := recvFdSets(oob[:on], flags) + if recvErr == nil { + t.Fatal("recvFdSets accepted truncated rights") + } + cmsgs, err := unix.ParseSocketControlMessage(oob[:on]) + if err != nil { + t.Fatal(err) + } + var delivered []int + for _, cm := range cmsgs { + fds, e := unix.ParseUnixRights(&cm) + if e != nil { + t.Fatal(e) + } + delivered = append(delivered, fds...) + } + if len(delivered) == 0 { + t.Fatal("kernel delivered no rights, test cannot assert fd cleanup") + } + for _, fd := range delivered { + if _, e := unix.FcntlInt(uintptr(fd), unix.F_GETFD, 0); e == nil { + unix.Close(fd) // Clean up only if recvFdSets failed to close it. + t.Errorf("recvFdSets leaked delivered fd %d after MSG_CTRUNC", fd) + } else if e != unix.EBADF { + t.Fatalf("fd %d status=%v", fd, e) + } + } + t.Logf("MSG_CTRUNC delivered %d rights; recvFdSets error=%v", len(delivered), recvErr) +} + +func TestMonitorRPCUnexpectedControlMessageClosesRights(t *testing.T) { + for _, tc := range []struct { + name string + unexpectedFirst bool + }{ + {"unexpected_after_rights", false}, + {"unexpected_before_rights", true}, + } { + t.Run(tc.name, func(t *testing.T) { + pair, err := unix.Socketpair(unix.AF_UNIX, unix.SOCK_STREAM, 0) + if err != nil { + t.Fatal(err) + } + defer unix.Close(pair[0]) + defer unix.Close(pair[1]) + sent := devNullFd(t) + if err := unix.Sendmsg(pair[0], []byte("x"), unix.UnixRights(sent), nil, 0); err != nil { + t.Fatal(err) + } + b, oob := make([]byte, 8), make([]byte, unix.CmsgSpace(4)) + _, on, flags, _, err := unix.Recvmsg(pair[1], b, oob, unix.MSG_CMSG_CLOEXEC) + if err != nil { + t.Fatal(err) + } + cmsgs, err := unix.ParseSocketControlMessage(oob[:on]) + if err != nil || len(cmsgs) != 1 { + t.Fatalf("received cmsgs=%v, err=%v", cmsgs, err) + } + delivered, err := unix.ParseUnixRights(&cmsgs[0]) + if err != nil || len(delivered) != 1 { + t.Fatalf("delivered rights=%v, err=%v", delivered, err) + } + unexpected := unix.UnixCredentials(&unix.Ucred{}) + var control []byte + if tc.unexpectedFirst { + control = append(unexpected, oob[:on]...) + } else { + control = append(append([]byte(nil), oob[:on]...), unexpected...) + } + if _, err := recvFdSets(control, flags); err == nil { + t.Fatal("unexpected control message accepted") + } + if _, err := unix.FcntlInt(uintptr(delivered[0]), unix.F_GETFD, 0); err != unix.EBADF { + if err == nil { + unix.Close(delivered[0]) + } + t.Errorf("received right %d left open after unexpected control message: %v", delivered[0], err) + } + }) + } +} diff --git a/ssh/tailssh/monitor_rpc_test.go b/ssh/tailssh/monitor_rpc_test.go index e4c246cfb..98782e704 100644 --- a/ssh/tailssh/monitor_rpc_test.go +++ b/ssh/tailssh/monitor_rpc_test.go @@ -158,7 +158,7 @@ func TestMonitorRPCMultiFd(t *testing.T) { // Three fds pass, matching the exec stdio shape. fds := []int{devNullFd(t), devNullFd(t), devNullFd(t)} - req := rpcExecReq(9, []string{"/bin/sh"}, nil, "", false, 3) + req := rpcExecReq(9, []string{"/bin/sh"}, nil, "", false, false, 3) if err := client.writeFrame(req, fds...); err != nil { t.Fatal(err) } @@ -174,18 +174,50 @@ func TestMonitorRPCMultiFd(t *testing.T) { unix.Close(fd) } - // A fourth fd in one frame is rejected by the receiver. - four := []int{devNullFd(t), devNullFd(t), devNullFd(t), devNullFd(t)} - defer closeFds(four) + // Four fds pass only with the envfd declaration, stdio plus the + // --env-fd pipe. The declaration and the delivered count must + // match. + envReq := rpcExecReq(10, []string{"/bin/sh"}, nil, "", false, true, 4) + if err := client.writeFrame(envReq, devNullFd(t), devNullFd(t), devNullFd(t), devNullFd(t)); err != nil { + t.Fatal(err) + } + if f, got, err := server.readFrame(); err != nil || !f.EnvFd || len(got) != 4 { + t.Fatalf("envfd frame = %+v, fds = %v, err = %v", f, got, err) + } else { + for _, fd := range got { + assertCLOEXEC(t, fd) + unix.Close(fd) + } + } + + // Four fds without the envfd declaration (declared 3) are rejected. line, err := json.Marshal(req) if err != nil { t.Fatal(err) } - if _, _, err := client.c.WriteMsgUnix(append(line, '\n'), unix.UnixRights(four...), nil); err != nil { + rights := unix.UnixRights( + devNullFd(t), devNullFd(t), devNullFd(t), devNullFd(t), + ) + if _, _, err := client.c.WriteMsgUnix(append(line, '\n'), rights, nil); err != nil { t.Fatal(err) } if _, _, err := server.readFrame(); err == nil { - t.Fatal("4-fd frame accepted") + t.Fatal("4 fds without the envfd declaration accepted") + } + + // A fifth fd in one frame is rejected by the receiver. + line, err = json.Marshal(envReq) + if err != nil { + t.Fatal(err) + } + rights = unix.UnixRights( + devNullFd(t), devNullFd(t), devNullFd(t), devNullFd(t), devNullFd(t), + ) + if _, _, err := client.c.WriteMsgUnix(append(line, '\n'), rights, nil); err != nil { + t.Fatal(err) + } + if _, _, err := server.readFrame(); err == nil { + t.Fatal("5-fd frame accepted") } } @@ -333,6 +365,10 @@ func TestMonitorRPCUndersizedOOBTruncates(t *testing.T) { four := []int{devNullFd(t), devNullFd(t), devNullFd(t), devNullFd(t)} // sendFds itself refuses more than rpcMaxFds descriptors. Bypass it // to feed the receiver an oversized cmsg. + var before map[int]bool + if runtime.GOOS == "linux" { + before = openFdSet(t) + } if _, _, err := client.c.WriteMsgUnix([]byte("{\"op\":\"exec\"}\n"), unix.UnixRights(four...), nil); err != nil { t.Fatal(err) } @@ -348,6 +384,13 @@ func TestMonitorRPCUndersizedOOBTruncates(t *testing.T) { if _, err := recvFdSets(tooSmall[:oobn], flags); err == nil { t.Fatal("undersized OOB buffer accepted a truncated cmsg") } + if before != nil { + for fd := range openFdSet(t) { + if !before[fd] { + t.Errorf("fd %d delivered by truncated cmsg remains open", fd) + } + } + } } // A legal >64 KiB frame with an fd is split by a shrunken send buffer, @@ -371,7 +414,7 @@ func TestMonitorRPCSplitLineFD(t *testing.T) { } big := strings.Repeat("x", 100<<10) - req := rpcExecReq(11, []string{big}, nil, "", false, 1) + req := rpcExecReq(11, []string{big}, nil, "", false, false, 1) done := make(chan error, 1) go func() { done <- client.writeFrame(req, passed) @@ -526,7 +569,7 @@ func TestMonitorRPCMultiplex(t *testing.T) { return } } - if err := server.writeFrame(rpcExitNotify(4321, 0)); err != nil { + if err := server.writeFrame(rpcExitNotify(monitorProcess{PID: 4321, ID: 1}, 0)); err != nil { t.Errorf("server exit write: %v", err) } }() @@ -701,7 +744,7 @@ func TestMonitorRPCReadTimeoutPreservesLine(t *testing.T) { peer, passed := fdPair(t) defer peer.Close() - req := rpcExecReq(21, []string{"sleep 1"}, nil, "", false, 1) + req := rpcExecReq(21, []string{"sleep 1"}, nil, "", false, false, 1) line, err := json.Marshal(req) if err != nil { t.Fatal(err) @@ -747,7 +790,7 @@ func TestMonitorRPCFrameShapes(t *testing.T) { reqs := []rpcFrame{ rpcListenReq(7, "unix", "/tmp/x.sock", true, false), rpcListenReq(8, "tcp", "127.0.0.1:0", false, true), - rpcSignalReq(9, 4321, "SIGKILL"), + rpcSignalReq(9, monitorProcess{PID: 4321, ID: 8}, "SIGKILL"), } go func() { for _, f := range reqs { diff --git a/ssh/tailssh/monitor_test.go b/ssh/tailssh/monitor_test.go index b98253efc..8b6d092e7 100644 --- a/ssh/tailssh/monitor_test.go +++ b/ssh/tailssh/monitor_test.go @@ -114,7 +114,7 @@ func trueExe(t *testing.T) string { } type exitNote struct { - pid int + pid monitorProcess code int } @@ -123,7 +123,7 @@ type exitNote struct { // notification. func collectExits(mc *monitorClient) chan exitNote { ch := make(chan exitNote, 8) - mc.SetExitCallback(func(pid, code int) { ch <- exitNote{pid, code} }) + mc.SetExitCallback(func(pid monitorProcess, code int) { ch <- exitNote{pid, code} }) return ch } @@ -170,12 +170,12 @@ func runChild(t *testing.T, mc *monitorClient, argv, env []string) string { } ctx, cancel := testCtx() defer cancel() - pid, err := mc.Exec(ctx, argv, env, "/", false, stdin, stdoutW, stderrW) + pid, err := mc.Exec(ctx, argv, env, "/", false, nil, stdin, stdoutW, stderrW) if err != nil { t.Fatalf("exec %v: %v", argv, err) } - if pid <= 0 { - t.Fatalf("exec %v: pid %d, want > 0", argv, pid) + if pid.PID <= 0 { + t.Fatalf("exec %v: pid %v, want > 0", argv, pid) } // The monitor closed its copies. Drop ours so reads see EOF once the // child exits. @@ -263,7 +263,7 @@ func TestMonitorExecNoStdio(t *testing.T) { ctx, cancel := testCtx() defer cancel() trueExe := trueExe(t) - pid, err := mc.Exec(ctx, []string{trueExe}, nil, "/", false) + pid, err := mc.Exec(ctx, []string{trueExe}, nil, "/", false, nil) if err != nil { t.Fatalf("exec %s: %v", trueExe, err) } @@ -366,17 +366,92 @@ func TestCheckAgentSocketPath(t *testing.T) { } } +// runIncubatorChild execs argv on the monitor as an incubator request +// and returns the child's stdout, fully drained until EOF so the child +// must exit. +func runIncubatorChild(t *testing.T, mc *monitorClient, argv []string) string { + t.Helper() + // stdin: read end handed to the child. Nothing is written to it. + stdin, stdinKeep, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer stdinKeep.Close() + stdout, stdoutW, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + stderr, stderrW, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + ctx, cancel := testCtx() + defer cancel() + pid, err := mc.ExecIncubator(ctx, argv, nil, "/", false, nil, stdin, stdoutW, stderrW) + if err != nil { + t.Fatalf("incubator exec %v: %v", argv, err) + } + if pid.PID <= 0 { + t.Fatalf("incubator exec %v: pid %v, want > 0", argv, pid) + } + stdoutW.Close() + stderrW.Close() + out := readAllWithDeadline(t, stdout, 5*time.Second) + if e := readAllWithDeadline(t, stderr, 5*time.Second); e != "" { + t.Logf("child %v stderr: %s", argv, e) + } + stdout.Close() + stderr.Close() + return out +} + +// TestMonitorExecIncubatorIdentityBinding pins the identity contract of +// incubator execs: the monitor rewrites the request's identity flags to +// its spawn-bound identity whatever the request claims, and refuses an +// incubator argv that is missing any of them. The child prints the +// arguments it was exec'd with, after the monitor's rewrite. +func TestMonitorExecIncubatorIdentityBinding(t *testing.T) { + groups := testGroups(t) + mc := startTestMonitor(t, os.Getuid(), os.Getgid(), groups) + + argv := []string{"/bin/sh", "-c", `printf '%s\n' "$@"`, "sh", + "--uid=1", "--gid=1", "--groups=1,2", "--local-user=not-us"} + out := runIncubatorChild(t, mc, argv) + want := strings.Join([]string{ + "--uid=" + formatID(uint32(os.Getuid())), + "--gid=" + formatID(uint32(os.Getgid())), + "--groups=" + joinGids(intToU32s(groups)), + "--local-user=testuser", + }, "\n") + "\n" + if out != want { + t.Fatalf("incubator argv after the monitor's rewrite = %q, want %q", out, want) + } +} + +// TestMonitorExecIncubatorIdentityRequired pins that an incubator exec +// missing an identity flag is refused before any child is spawned: the +// incubator's own flag defaults would otherwise run the child as root. +func TestMonitorExecIncubatorIdentityRequired(t *testing.T) { + mc := startTestMonitor(t, os.Getuid(), os.Getgid(), testGroups(t)) + argv := []string{"/bin/sh", "-c", "echo spawned", "sh", "--uid=1"} + ctx, cancel := testCtx() + defer cancel() + if _, err := mc.ExecIncubator(ctx, argv, nil, "/", false, nil); err == nil { + t.Fatal("incubator exec without --gid, --groups, and --local-user flags was accepted") + } +} + func TestMonitorSignal(t *testing.T) { mc := startTestMonitor(t, os.Getuid(), os.Getgid(), testGroups(t)) exits := collectExits(mc) - pid, err := mc.Exec(mustCtx(t), []string{"/bin/sleep", "30"}, nil, "/", false) + pid, err := mc.Exec(mustCtx(t), []string{"/bin/sleep", "30"}, nil, "/", false, nil) if err != nil { t.Fatalf("exec sleep: %v", err) } // Signaling an unknown pid must be refused. - if err := mc.Signal(mustCtx(t), pid+1000000, "SIGTERM"); err == nil { + if err := mc.Signal(mustCtx(t), monitorProcess{PID: pid.PID + 1000000, ID: pid.ID}, "SIGTERM"); err == nil { t.Fatal("signal of a pid that is not a monitor child should fail") } // A bad signal name is an error too. @@ -403,6 +478,58 @@ func mustCtx(t *testing.T) context.Context { return ctx } +// TestMonitorExecEnvFD pins the exec op's fourth descriptor: an envfd +// exec carries stdin/stdout/stderr plus the env-fd pipe, which the +// monitor maps to the child's fd 3, os/exec ExtraFiles slot 0, the +// fd the incubator's --env-fd names. +func TestMonitorExecEnvFD(t *testing.T) { + mc := startTestMonitor(t, os.Getuid(), os.Getgid(), testGroups(t)) + exits := collectExits(mc) + + // The payload pipe: what launchProcess's forwardedEnvFile builds. + envR, envW, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + go func() { + defer envW.Close() + envW.Write([]byte(`["FORWARDED=pair"]`)) + }() + + stdout, stdoutW, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer stdout.Close() + ctx, cancel := testCtx() + defer cancel() + // The child asserts the pair is visible on fd 3, and that its + // stdin, fd 0, is a separate stream, the /dev/null fd the request + // carried. + devNull, err := os.OpenFile(os.DevNull, os.O_RDONLY, 0) + if err != nil { + t.Fatal(err) + } + defer devNull.Close() + argv := []string{"/bin/sh", "-c", `v=$(cat <&3); [ "$v" = '["FORWARDED=pair"]' ] && echo fd3-ok || echo fd3-bad:$v`} + pid, err := mc.Exec(ctx, argv, nil, "/", false, envR, devNull, stdoutW, stdoutW) + if err != nil { + t.Fatalf("exec envfd: %v", err) + } + // The monitor closed its copies; drop ours so EOF arrives when the + // child exits. + stdoutW.Close() + envR.Close() + out := readAllWithDeadline(t, stdout, 5*time.Second) + if got := strings.TrimSpace(out); got != "fd3-ok" { + t.Errorf("child output = %q; want fd3-ok", got) + } + n := waitExitNote(t, exits, 5*time.Second) + if n.pid != pid || n.code != 0 { + t.Errorf("exit notification = pid %d code %d; want pid %d code 0", n.pid, n.code, pid) + } +} + // TestMonitorBadExec asserts error propagation for unspawnable and // malformed exec requests. func TestMonitorBadExec(t *testing.T) { @@ -415,7 +542,7 @@ func TestMonitorBadExec(t *testing.T) { {"sh", "-c", "echo hi"}, // relative argv[0] must be refused {}, } { - if _, err := mc.Exec(ctx, argv, nil, "/", false); err == nil { + if _, err := mc.Exec(ctx, argv, nil, "/", false, nil); err == nil { t.Fatalf("exec %v: unexpectedly succeeded", argv) } } @@ -432,7 +559,7 @@ func TestMonitorTeardown(t *testing.T) { mc := startTestMonitor(t, os.Getuid(), os.Getgid(), testGroups(t)) exits := collectExits(mc) - pid, err := mc.Exec(mustCtx(t), []string{"/bin/sleep", "30"}, nil, "/", false) + pid, err := mc.Exec(mustCtx(t), []string{"/bin/sleep", "30"}, nil, "/", false, nil) if err != nil { t.Fatalf("exec sleep: %v", err) } @@ -449,7 +576,7 @@ func TestMonitorTeardown(t *testing.T) { // not our child. Check its liveness directly: gone or a reaped // zombie on linux. On other platforms probe with signal 0. deadline := time.Now().Add(5 * time.Second) - for !processDead(pid) { + for !processDead(pid.PID) { if time.Now().After(deadline) { t.Fatalf("child %d still alive %v after monitor teardown", pid, time.Since(start)) } diff --git a/ssh/tailssh/monitor_watchdog_linux_test.go b/ssh/tailssh/monitor_watchdog_linux_test.go new file mode 100644 index 000000000..001db57ed --- /dev/null +++ b/ssh/tailssh/monitor_watchdog_linux_test.go @@ -0,0 +1,113 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build linux && !android + +package tailssh + +import ( + "context" + "os" + "os/signal" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" +) + +// TestMonitorWatchdogHelperProcess is re-exec'd as a monitor-owned session +// or one-shot forwarding child. Both ignore parent-death SIGHUP so only +// orderly monitor teardown (including its SIGKILL pass) can stop them. +func TestMonitorWatchdogHelperProcess(t *testing.T) { + for i, arg := range os.Args { + if arg != "--" || i+2 >= len(os.Args) || os.Args[i+1] != "watchdog-helper" { + continue + } + signal.Ignore(syscall.SIGHUP) + if err := os.WriteFile(os.Args[i+2], []byte(strconv.Itoa(os.Getpid())), 0600); err != nil { + os.Exit(3) + } + time.Sleep(25 * time.Second) + os.Exit(0) + } +} + +// TestMonitorCloseWatchdogForwardChild reproduces the case where a stalled +// forwarding op consumes the watchdog before the monitor can tear down its +// HUP-immune session and forwarding child groups. +func TestMonitorCloseWatchdogForwardChild(t *testing.T) { + markerDir := t.TempDir() + forwardMarker := filepath.Join(markerDir, "forward-pid") + t.Setenv("TS_TEST_SSH_FWD_PREFIX", strings.Join([]string{ + "-test.run=^TestMonitorWatchdogHelperProcess$", "-test.timeout=0", "--", "watchdog-helper", forwardMarker, + }, " ")) + mc := startTestMonitor(t, os.Getuid(), os.Getgid(), testGroups(t)) + + // The session must be running and ignoring HUP before Close starts. + sessionMarker := filepath.Join(markerDir, "session-pid") + ctx, cancel := testCtx() + session, err := mc.Exec(ctx, []string{monitorExe(t), "-test.run=^TestMonitorWatchdogHelperProcess$", "-test.timeout=0", "--", "watchdog-helper", sessionMarker}, nil, "/", false, nil) + cancel() + if err != nil { + t.Fatalf("start session: %v", err) + } + defer func() { + // Only signal this test's own session group, never a reused PID. + if b, err := os.ReadFile(sessionMarker); err == nil && strings.TrimSpace(string(b)) == strconv.Itoa(session.PID) && !processDead(session.PID) { + _ = syscall.Kill(-session.PID, syscall.SIGKILL) + } + }() + waitWatchdogMarker(t, sessionMarker, session.PID) + + requestDone := make(chan error, 1) + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 16*time.Second) + defer cancel() + _, err := mc.Listen(ctx, "tcp", "127.0.0.1:0", false) + requestDone <- err + }() + forwardPID := waitWatchdogMarker(t, forwardMarker, 0) + defer func() { + if !processDead(forwardPID) { + _ = syscall.Kill(forwardPID, syscall.SIGKILL) + } + }() + + start := time.Now() + err = mc.Close() + t.Logf("Close duration=%v error=%v; session=%d forward=%d", time.Since(start), err, session.PID, forwardPID) + if err != nil { + t.Errorf("monitor failed to complete teardown: %v", err) + } + select { + case err := <-requestDone: + t.Logf("inflight Listen returned: %v", err) + case <-time.After(2 * time.Second): + t.Error("inflight Listen did not return after Close") + } + if !processDead(forwardPID) { + t.Errorf("HUP-immune forwarding child %d survived Close", forwardPID) + } + if !processDead(session.PID) { + t.Errorf("HUP-immune session child %d survived Close", session.PID) + } +} + +func waitWatchdogMarker(t *testing.T, path string, wantPID int) int { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + if b, err := os.ReadFile(path); err == nil { + pid, err := strconv.Atoi(strings.TrimSpace(string(b))) + if err != nil || pid <= 0 || (wantPID > 0 && pid != wantPID) { + t.Fatalf("invalid helper PID marker %q: %q", path, b) + } + return pid + } + time.Sleep(20 * time.Millisecond) + } + t.Fatalf("helper did not write PID marker %q", path) + return 0 +} diff --git a/ssh/tailssh/process_unix.go b/ssh/tailssh/process_unix.go index b60be0892..f4ff35434 100644 --- a/ssh/tailssh/process_unix.go +++ b/ssh/tailssh/process_unix.go @@ -18,10 +18,36 @@ import ( gliderssh "github.com/tailscale/gliderssh" ) +// monitorProcess identifies one exec child. ID is the exec request ID, which +// distinguishes successive children even when the operating system reuses a PID. +type monitorProcess struct { + PID int + ID int64 +} + +// monExitStatus publishes an exit code to any number of waiters. The registry +// completes it once; code may be read only after done is closed. +type monExitStatus struct { + done chan struct{} + code int +} + // osSessionState holds the platform-specific state of an [sshSession]'s // process. It is embedded in [sshSession] and initialized by launchProcess. +// +// cmd describes the invocation on both paths. monChild identifies a monitor +// child; cmd.Process identifies a directly launched child. type osSessionState struct { - cmd *exec.Cmd // the session's incubator or shell process + // cmd is the session's incubator or shell process on the direct path. + // It is set but never started on the monitor path. + cmd *exec.Cmd + + monChild monitorProcess // zero on the direct path + // monExit publishes the exit status, or 128+signal for a signaled death. + monExit *monExitStatus + // monDead is closed when the monitor's RPC channel is gone, so + // waiting sessions fail instead of blocking. + monDead <-chan struct{} } // forwardedEnvChildFD is the fd the incubator child reads the forwarded environment from, sent via @@ -67,6 +93,11 @@ func canSwitchToLocalUser(lu *userMeta) error { // waitProcess waits for the session's process to exit and returns its exit // code. A non-nil error means the exit code could not be determined. func (ss *sshSession) waitProcess() (exitCode int, err error) { + // Monitor path: the child's exit arrives as the monitor's async + // exit notification, with the code documented on monExit. + if code, ok, merr := ss.waitMonitorProcess(); ok { + return code, merr + } err = ss.cmd.Wait() if err == nil { return 0, nil @@ -77,9 +108,13 @@ func (ss *sshSession) waitProcess() (exitCode int, err error) { return 1, err } -// hangupProcess asks the session's process to terminate because the session -// is over. +// hangupProcess asks the session's process to terminate because the +// session is over. On the monitor path this is hangupMonitorProcess. +// On the direct path it is a single SIGHUP to the child pid. func (ss *sshSession) hangupProcess() { + if ss.hangupMonitorProcess() { + return + } // SIGHUP = POSIX terminal-disconnect semantics; OpenSSH gets it // implicitly via PTY-master close (session.c:2246), we send it // explicitly because non-PTY sessions use pipes. diff --git a/ssh/tailssh/sessmonitor.go b/ssh/tailssh/sessmonitor.go new file mode 100644 index 000000000..194bde688 --- /dev/null +++ b/ssh/tailssh/sessmonitor.go @@ -0,0 +1,112 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build (linux && !android) || (darwin && !ios) || freebsd || openbsd + +// Session processes are launched by the connection's privileged monitor. +// tailscaled keeps the parent I/O descriptors and passes the child's stdio +// and optional environment pipe via SCM_RIGHTS. + +package tailssh + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "time" +) + +// hangupEscalation is the delay between SIGHUP and SIGKILL on session teardown. +const hangupEscalation = 5 * time.Second + +func newMonExitStatus() *monExitStatus { + return &monExitStatus{done: make(chan struct{})} +} + +func (s *monExitStatus) complete(code int) { + s.code = code + close(s.done) +} + +// launchViaMonitor passes cmd and the child's descriptors to the monitor. +// After dispatch, cancellation does not abandon the exec reply: a successful +// launch always registers the child so run can terminate it and wait for exit. +func (ss *sshSession) launchViaMonitor(cmd *exec.Cmd, envFile *os.File, stdio []*os.File, ctty bool) error { + if len(stdio) != 3 { + return fmt.Errorf("internal error: monitor exec needs 3 stdio fds, got %d", len(stdio)) + } + if err := ss.ctx.Err(); err != nil { + return err + } + mc, err := ss.conn.fwdMonitor() + if err != nil { + return err + } + child, err := mc.ExecIncubator(ss.ctx, cmd.Args, cmd.Env, cmd.Dir, ctty, envFile, stdio...) + if err != nil { + return fmt.Errorf("exec on session monitor: %w", err) + } + exit := newMonExitStatus() + ss.conn.fwd.exits.registerSessionExit(child, exit) + ss.monChild = child + ss.monExit = exit + ss.monDead = mc.Gone() + return nil +} + +// waitMonitorProcess returns the child's exit code, or an error if its monitor +// dies without reporting an exit. ok is false for directly launched sessions. +func (ss *sshSession) waitMonitorProcess() (code int, ok bool, err error) { + if ss.monExit == nil { + return 0, false, nil + } + select { + case <-ss.monExit.done: + return ss.monExit.code, true, nil + case <-ss.monDead: + // The read loop delivers notifications before closing monDead. + // Recheck here because both cases may have become ready together. + select { + case <-ss.monExit.done: + return ss.monExit.code, true, nil + default: + return 1, true, errors.New("session monitor exited before the session process") + } + } +} + +// hangupMonitorProcess sends SIGHUP, then SIGKILL after hangupEscalation if the +// child has not exited. It returns false for directly launched sessions. +func (ss *sshSession) hangupMonitorProcess() bool { + if ss.monChild.PID == 0 { + return false + } + mc := ss.conn.fwdMonitorIfAny() + if mc == nil { + // Monitor teardown owns cleanup. Its reaped PIDs may already have + // been reused, so tailscaled must not signal them directly. + return true + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := mc.Signal(ctx, ss.monChild, "SIGHUP"); err != nil { + ss.logf("ssh: SIGHUP session process group: %v", err) + } + time.AfterFunc(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) + defer cancel() + if err := mc.Signal(ctx, ss.monChild, "SIGKILL"); err != nil { + ss.vlogf("ssh: SIGKILL session process group: %v", err) + } +} diff --git a/ssh/tailssh/sessmonitor_test.go b/ssh/tailssh/sessmonitor_test.go new file mode 100644 index 000000000..ed941cdcd --- /dev/null +++ b/ssh/tailssh/sessmonitor_test.go @@ -0,0 +1,920 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build (linux && !android) || (darwin && !ios) + +// Session-through-the-monitor tests: a real gliderssh session served by +// a real tailssh conn whose child is spawned by a real ssh-monitor +// process. Both are re-exec'd through the self-exec seams. The tests +// pin the exit-status wire ordering (exit-status before output before EOF) and +// the exit-notification plumbing on the new path. + +package tailssh + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net" + "net/netip" + "os" + "os/exec" + "os/user" + "runtime" + "slices" + "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/tailcfg/nodecap" + "tailscale.com/tstest" +) + +// testIncubatorPrefix re-execs the test binary, selecting only the helper +// test, with the incubator's argv following "--" (the testing framework's +// flag parsing stops there). -test.timeout=0: the incubator child serves a +// full session, not a test with its own deadline. In tailscaled the argv +// prefix is "be-child ssh" (childproc dispatch); the monitor execs the +// prefix after the executable path. +var testIncubatorPrefix = []string{"-test.run=^TestSSHIncubatorHelperProcess$", "-test.timeout=0", "--", "ssh"} + +// incubFdsDumpMarker gates the incubator's fd-table dump: only the +// session whose argv carries this marker, as INCUB-FDS-DUMP=, +// dumps to , so a concurrently live pty session is not confused +// with the assertion target. The path travels in the exec request's +// argv. +const incubFdsDumpMarker = "INCUB-FDS-DUMP" + +// incubatorChildArgv shapes a test child's argv the way launchViaMonitor +// sends it: an incubator invocation, carrying the identity flags the +// monitor requires and rewrites to its spawn-bound identity. The values +// are placeholders; the monitor overwrites them, so these test children +// need not carry the real connection identity. +func incubatorChildArgv(argv []string) []string { + return append(slices.Clone(argv), + "--uid=1", "--gid=1", "--groups=1", "--local-user=test-user") +} + +// incubDumpArg extracts the INCUB-FDS-DUMP= dump target from the +// incubator's argv, or returns "". +func incubDumpArg(args []string) string { + prefix := incubFdsDumpMarker + "=" + joined := strings.Join(args, " ") + i := strings.Index(joined, prefix) + if i < 0 { + return "" + } + rest := joined[i+len(prefix):] + if j := strings.IndexAny(rest, " \"'\t\r\n"); j >= 0 { + rest = rest[:j] + } + return rest +} + +// TestSSHIncubatorHelperProcess is not a test; it is the entry point +// of the re-exec'd session child, the incubator. It acts only when the +// binary is exec'd with the prefix above, and returns immediately +// otherwise. +func TestSSHIncubatorHelperProcess(t *testing.T) { + for i, a := range os.Args { + if a == "--" && i+2 < len(os.Args) && os.Args[i+1] == "ssh" { + // Declared-fds pin for the session child: when this + // child's argv carries the marker, dump the exec-inherited + // fd table (stdio, the --env-fd pipe at 3) before the + // incubator starts. + if path := incubDumpArg(os.Args[i+2:]); path != "" { + dumpChildFdsTo(path, "incubator") + } + if err := beIncubator(os.Args[i+2:]); err != nil { + fmt.Fprintln(os.Stderr, "ssh incubator child:", err) + os.Exit(1) + } + // beIncubator exec'd away (login/su) or ran the command + // in-process; handleSSHInProcess exits with the child's code. + os.Exit(0) + } + } +} + +// monitorSessionSeams routes the monitor and incubator spawns to the +// self-exec helper tests and returns nothing. Cleanup restores both. +func monitorSessionSeams(t *testing.T) { + t.Helper() + oldMon, oldInc := monitorSpawnPrefix, incubatorSpawnPrefix + monitorSpawnPrefix = testMonitorPrefix + incubatorSpawnPrefix = testIncubatorPrefix + t.Cleanup(func() { monitorSpawnPrefix, incubatorSpawnPrefix = oldMon, oldInc }) +} + +// newMonitorSessionServer is newMonitorSessionServerFor with the +// existing defaults: the current local user, the SSHBehaviorV1 cap, no +// policy grant (sessions only; the Handler bypasses the recheck gates), +// and no forwarding seams. +func newMonitorSessionServer(t *testing.T, handler func(c *conn, s gliderssh.Session)) string { + t.Helper() + return newMonitorSessionServerFor(t, nil, nil, nil, false, handler) +} + +// newMonitorSessionServerFor is newMonitorSessionServer with the conn's +// bound identity, node caps, policy grant, and forwarding seams +// parametrized, for the fd-isolation tests (the PTY-master leak +// regression) and the fwd-child declared-fds pin: +// +// - lu: the conn's local user; nil = the current user (the default +// above). Under root runs the fd-isolation tests bind the conn to the +// non-root sshfwda test user, so the session children run as a +// different uid than the pty-holding test process, the cross-user +// shape of the original injection scenario. +// - caps: node caps; nil = [SSHBehaviorV1] (the V1 pin also keeps the +// incubator on the in-process branch: no login/su, no PAM). +// - rule: lb.matchingRule, the policy grant whose action and accept-env +// latching the conn uses for the forwarding gates' recheckPolicy +// (AllowLocalPortForwarding for a unix -L dial through this conn); +// nil = none (sessions only). +// - fwdSeams: route the conn's one-shot fwd children through the +// re-exec'd helper (the seam env crossing the exec boundary into +// the monitor process). +// +// handler serves each session channel; it receives the owning conn so it +// can call conn.newSSHSession(...).run(). +func newMonitorSessionServerFor( + t *testing.T, + lu *userMeta, + caps []nodecap.Cap, + rule *tailcfg.SSHRule, + fwdSeams bool, + handler func(c *conn, s gliderssh.Session), +) string { + t.Helper() + if lu == nil { + u, err := user.Current() + if err != nil { + t.Fatal(err) + } + lu, err = userLookup(u.Username) + if err != nil { + t.Fatal(err) + } + } + if caps == nil { + caps = []nodecap.Cap{nodecap.SSHBehaviorV1} + } + monitorSessionSeams(t) + // The session children are exec'd from tailscaledPath by the root + // monitor, and the fwd children (fwdSeams) run as the bound user: + // both need the reachable copy of the test binary under a root run. + exe := makeExecutableReachable(t) + if fwdSeams { + t.Setenv("TS_TEST_SSH_FWD_PREFIX", strings.Join(testFwdPrefix, " ")) + } + if rule != nil && rule.SSHUsers["test"] == "" { + rule.SSHUsers["test"] = lu.Username + } + logf := tstest.WhileTestRunningLogger(t) + + srv := &server{ + lb: &localState{ + sshEnabled: true, + varRoot: t.TempDir(), + caps: caps, + matchingRule: rule, + }, + logf: logf, + tailscaledPath: exe, + } + sc, err := srv.newConn() + if err != nil { + t.Fatal(err) + } + // Tear the conn's monitor down with the conn (HandleConn is driven + // directly below, so HandleSSHConn's teardown does not run). + t.Cleanup(sc.closeFwdMonitor) + + sc.insecureSkipTailscaleAuth = true + + um, err := userLookup(lu.Username) + if err != nil { + t.Fatal(err) + } + // /bin/sh: a predictable direct child of the incubator. + um.loginShellCached = "/bin/sh" + sc.localUser = um + // The bound user's groups, like clientAuth would have captured them + // (the incubator argv's --groups must be non-empty): for a conn bound + // to another uid use that user's own primary group, not the test + // process's (root-run) groups. + if um.Uid == strconv.Itoa(os.Getuid()) { + for _, g := range testGroups(t) { + sc.userGroupIDs = append(sc.userGroupIDs, strconv.Itoa(g)) + } + } else { + sc.userGroupIDs = []string{um.Gid} + } + sc.info = &sshConnInfo{ + sshUser: "test", + src: netip.MustParseAddrPort("1.2.3.4:32342"), + dst: netip.MustParseAddrPort("1.2.3.5:22"), + node: (&tailcfg.Node{}).View(), + uprof: tailcfg.UserProfile{}, + } + action := &tailcfg.SSHAction{Accept: true} + if rule != nil { + action = rule.Action + sc.acceptEnv = rule.AcceptEnv + // The fwd gates' recheckPolicy paths need Principals to match the + // synthetic conn info (any principal, like the fwd conn tests). + if len(rule.Principals) == 0 { + rule.Principals = []*tailcfg.SSHPrincipal{{Any: true}} + } + } + sc.action0 = action + sc.finalAction = action + sc.authCompleted.Store(true) + sc.Handler = func(s gliderssh.Session) { + handler(sc, s) + } + + ln, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + go sc.HandleConn(c) + } + }() + return ln.Addr().String() +} + +// TestSessionMonitorExitStatusOrder is the monitor-path version of +// TestExitStatusPrecedesEOF: a session whose child is exec'd by the +// per-connection ssh-monitor must keep the teardown wire order +// (exit-status, remaining output, EOF, CHANNEL_CLOSE) even though the +// child's exit arrives as an async monitor notification instead of +// cmd.Wait. The child produces output on both streams and exits 7; the +// client must see the output and the exit status, in that order. +func TestSessionMonitorExitStatusOrder(t *testing.T) { + recCh := make(chan *frameRecorder, 1) + addr := newMonitorSessionServer(t, func(c *conn, s gliderssh.Session) { + rec := &frameRecorder{Session: s} + select { + case recCh <- rec: + default: + } + c.newSSHSession(rec).run() + }) + + cl, err := gossh.Dial("tcp", addr, &gossh.ClientConfig{ + HostKeyCallback: gossh.InsecureIgnoreHostKey(), + Timeout: 15 * time.Second, + }) + if err != nil { + t.Fatal(err) + } + defer cl.Close() + s, err := cl.NewSession() + if err != nil { + t.Fatal(err) + } + + // Separate buffers: the client serves stdout and stderr from distinct + // goroutines, so they must not share an unsynchronized writer. + var stdout, stderr bytes.Buffer + s.Stdout = &stdout + s.Stderr = &stderr + err = s.Run("echo out; echo err 1>&2; exit 7") + var ee *gossh.ExitError + if !errors.As(err, &ee) { + t.Fatalf("want *gossh.ExitError, got %T: %v", err, err) + } + if got := ee.ExitStatus(); got != 7 { + t.Fatalf("exit status = %d, want 7", got) + } + // The session's output must have arrived before the teardown frames. + if got, want := stdout.String(), "out\n"; got != want { + t.Errorf("session stdout = %q; want %q", got, want) + } + if got, want := stderr.String(), "err\n"; got != want { + t.Errorf("session stderr = %q; want %q", got, want) + } + + var rec *frameRecorder + select { + case rec = <-recCh: + case <-time.After(10 * time.Second): + t.Fatal("session never started") + } + var got []string + if err := tstest.WaitFor(5*time.Second, func() error { + got = rec.got() + if len(got) < 3 { + return errNotAllFrames + } + return nil + }); err != nil { + t.Fatalf("only saw frames %v, want 3", got) + } + want := []string{"exit-status", "eof", "close"} + if !slices.Equal(got, want) { + t.Errorf("frame order = %v, want %v", got, want) + } +} + +// TestSessionMonitorPTY drives a pty session through the monitor: the +// slave fds travel to the monitor via SCM_RIGHTS, the monitor applies +// Setsid+Setctty (slave as fd 0), and the client's window-change requests +// are applied by the resizeWindow goroutine's own master descriptor. The +// client requests a pty at 10x40, the child reports its size, then the +// window is changed to 24x80 and the child reports the new size, pinning +// the resize path end to end, and the exit status is delivered. +func TestSessionMonitorPTY(t *testing.T) { + addr := newMonitorSessionServer(t, func(c *conn, s gliderssh.Session) { + c.newSSHSession(s).run() + }) + + cl, err := gossh.Dial("tcp", addr, &gossh.ClientConfig{ + HostKeyCallback: gossh.InsecureIgnoreHostKey(), + Timeout: 15 * time.Second, + }) + if err != nil { + t.Fatal(err) + } + defer cl.Close() + s, err := cl.NewSession() + if err != nil { + t.Fatal(err) + } + defer s.Close() + if err := s.RequestPty("xterm", 10, 40, gossh.TerminalModes{gossh.ECHO: 0}); err != nil { + t.Fatal(err) + } + stdin, err := s.StdinPipe() + if err != nil { + t.Fatal(err) + } + deadlineTimer := time.AfterFunc(15*time.Second, func() { cl.Close() }) + defer deadlineTimer.Stop() + + // stdout is served by a client goroutine; guard the buffer. + var out sessTestBuffer + s.Stdout = &out + s.Stderr = &out + const command = ` +stty size +read ready +while [ "$(stty size)" != "24 80" ]; do + sleep 0.05 +done +stty size +exit 3 +` + if err := s.Start(command); err != nil { + t.Fatal(err) + } + + // Wait until the first stty ran: the pty is up and resizeWindow is + // draining window changes (gliderssh's winch channel is buffered + // at one). + deadline := time.Now().Add(10 * time.Second) + for !strings.Contains(out.String(), "10 40") { + if time.Now().After(deadline) { + t.Fatalf("no initial stty output; got %q", out.String()) + } + time.Sleep(50 * time.Millisecond) + } + + // The window change must be applied to THIS session's master (the + // resize goroutine's own descriptor) and be observable + // to the child. + if err := s.WindowChange(24, 80); err != nil { + t.Fatal(err) + } + if _, err := io.WriteString(stdin, "ready\n"); err != nil { + t.Fatal(err) + } + + err = s.Wait() + var ee *gossh.ExitError + if !errors.As(err, &ee) { + t.Fatalf("want *gossh.ExitError, got %T: %v", err, err) + } + if got := ee.ExitStatus(); got != 3 { + t.Fatalf("exit status = %d, want 3", got) + } + // "rows cols" per stty(1): first the requested 10x40, then 24x80 + // after the window change. + if got, want := strings.Fields(out.String()), []string{"10", "40", "24", "80"}; !slices.Equal(got, want) { + t.Errorf("stty size outputs = %q; want %q", got, want) + } +} + +// TestSessionMonitorConnCloseKillsHupImmuneChild pins the teardown +// escalation on the conn-close paths, revocation, Shutdown, and plain +// teardown: the monitor's own teardown must SIGKILL the HUP-immune +// group, in both orderings of the session's own HUP escalation against +// the conn teardown (kick-then-close and close-without-kick). +func TestSessionMonitorConnCloseKillsHupImmuneChild(t *testing.T) { + for _, mode := range []string{"kick-then-close", "close-without-kick"} { + t.Run(mode, func(t *testing.T) { + lu := fwdTestIdentity(t) + c := newFwdTestConn(t, lu, &tailcfg.SSHAction{Accept: true}) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + ss := &sshSession{ + ctx: ctx, + conn: c, + logf: t.Logf, + } + + // An HUP-immune child, like TestSessionMonitorHangupEscalation: + // sh traps (ignores) SIGHUP, so only the group SIGKILL ends it. + // The marker gates on the trap being installed. + cmd := exec.Command("/bin/sh", "-c", "trap '' HUP; echo ready; while :; do sleep 1; done") + cmd.Args = incubatorChildArgv(cmd.Args) + stdin, stdinKeep, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer stdinKeep.Close() + stdout, stdoutW, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer stdout.Close() + stderr, stderrW, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer stderr.Close() + if err := ss.launchViaMonitor(cmd, nil, []*os.File{stdin, stdoutW, stderrW}, false); err != nil { + t.Fatalf("launchViaMonitor: %v", err) + } + stdoutW.Close() + stderrW.Close() + if err := stdout.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil { + t.Fatal(err) + } + marker := make([]byte, len("ready\n")) + if _, err := io.ReadFull(stdout, marker); err != nil { + t.Fatalf("reading ready marker: %v", err) + } + if string(marker) != "ready\n" { + t.Fatalf("child output = %q; want ready (the HUP trap is installed)", marker) + } + pid := ss.monChild.PID + + if mode == "kick-then-close" { + // The revocation kick (what killProcessOnContextDone does + // when the session ctx is canceled); its escalation timer + // races the conn teardown, which closes the monitor. + ss.hangupMonitorProcess() + } + // The conn teardown: every conn-close path funnels here + // (HandleSSHConn's deferred closeFwdMonitor). Close waits for + // the monitor to exit, so on return the teardown sweeps + // (HUP, then SIGKILL for survivors) have run. + c.closeFwdMonitor() + + // The child must be dead and reaped by the monitor's own + // teardown: signal 0 returns ESRCH once the monitor has reaped + // it. Bound: the teardown's two sweeps (≤2s each) inside + // Close's 5s monitor-exit wait, plus slack. + deadline := time.Now().Add(monTeardownReap*2 + 5*time.Second) + for { + if err := unix.Kill(pid, 0); err != nil { + return // reaped and gone + } + if time.Now().After(deadline) { + t.Fatalf("HUP-immune child %d survived monitor teardown", pid) + } + time.Sleep(100 * time.Millisecond) + } + }) + } +} + +// TestSessionMonitorTeardownKillsSamePgidStraggler pins the teardown +// SIGKILL's scope: a HUP-immune member of the session child's own +// process group whose leader dies to the teardown SIGHUP must be +// killed via the pgid set snapshot taken at teardown entry, not via +// surviving table entries. +func TestSessionMonitorTeardownKillsSamePgidStraggler(t *testing.T) { + lu := fwdTestIdentity(t) + c := newFwdTestConn(t, lu, &tailcfg.SSHAction{Accept: true}) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + ss := &sshSession{ + ctx: ctx, + conn: c, + logf: t.Logf, + } + + // The leader (sh) dies to the group SIGHUP. The nohup'd member of + // its group ignores HUP (nohup's SIG_IGN survives exec) and would + // survive the teardown under the entry-keyed SIGKILL: the first reap + // sweep reaps the leader and drops the table entry, so only the + // snapshot pgid set still names the group. The inner sh prints its + // own pid first so the test can watch it. + cmd := exec.Command("/bin/sh", "-c", + "nohup sh -c 'echo $$; exec sleep 300' & echo ready; wait") + cmd.Args = incubatorChildArgv(cmd.Args) + stdin, stdinKeep, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer stdinKeep.Close() + stdout, stdoutW, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer stdout.Close() + stderr, stderrW, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer stderr.Close() + if err := ss.launchViaMonitor(cmd, nil, []*os.File{stdin, stdoutW, stderrW}, false); err != nil { + t.Fatalf("launchViaMonitor: %v", err) + } + stdoutW.Close() + stderrW.Close() + if err := stdout.SetReadDeadline(time.Now().Add(10 * time.Second)); err != nil { + t.Fatal(err) + } + // Read until both markers arrived: "ready" (the leader is running) + // and the straggler's pid line (the nohup'd member is up). + straggler := 0 + sawReady := false + var buf []byte + deadline := time.Now().Add(10 * time.Second) + for !(sawReady && straggler != 0) { + if time.Now().After(deadline) { + t.Fatalf("child markers never arrived; got %q", buf) + } + chunk := make([]byte, 256) + n, err := stdout.Read(chunk) + if n > 0 { + buf = append(buf, chunk[:n]...) + } + if err != nil && !errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatalf("reading child output: %v", err) + } + for _, line := range strings.Fields(string(buf)) { + if line == "ready" { + sawReady = true + } + if p, err := strconv.Atoi(line); err == nil && p > 1 { + straggler = p + } + } + } + + // The conn teardown: closeFwdMonitor runs the monitor's teardown, + // group SIGHUP (kills the leader, sweep reaps it, entry dropped), + // then the SIGKILL pass over the snapshot pgid set. + c.closeFwdMonitor() + + // The straggler must be dead and gone. Bound: the teardown's two + // sweeps (≤2s each) inside Close's 5s monitor-exit wait, plus slack. + // A killed straggler whose parent is gone can linger as a zombie + // adopted by a PID 1 that does not reap (the privileged CI + // container); kill(pid, 0) succeeds for zombies, so liveness is + // checked through the /proc state on linux, where a Z state counts + // as gone. Elsewhere the adopter reaps promptly and kill(pid, 0) + // suffices. + deadline = time.Now().Add(monTeardownReap*2 + 5*time.Second) + for { + if pidGone(straggler) { + return // reaped and gone (or a reaped-pending zombie) + } + if time.Now().After(deadline) { + t.Fatalf("HUP-immune group member %d survived monitor teardown", straggler) + } + time.Sleep(100 * time.Millisecond) + } +} + +// pidGone reports whether pid no longer names a live process. On linux +// it reads /proc: a missing entry or a zombie (state Z) means gone. +// Elsewhere kill(pid, 0) is the check; the platforms in this file's +// build tag reap orphans promptly, so a lingering zombie is not +// expected there. +func pidGone(pid int) bool { + if runtime.GOOS == "linux" { + b, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)) + if err != nil { + return true // gone + } + // The state field follows the comm field, which may contain + // spaces and parentheses; take the field after the last ')'. + i := bytes.LastIndexByte(b, ')') + if i < 0 || i+2 >= len(b) { + return false + } + return b[i+2] == 'Z' + } + return unix.Kill(pid, 0) != nil +} + +// TestWaitMonitorProcessExitNotificationWins checks priority and repeatable +// reads when exit and monitor death occur before or during the wait. +func TestWaitMonitorProcessExitNotificationWins(t *testing.T) { + for i := range 100 { + dead := make(chan struct{}) + exit := newMonExitStatus() + notify := func() { + exit.complete(42) + close(dead) + } + if i%2 == 0 { + notify() + } else { + go notify() + } + ss := &sshSession{monExit: exit, monDead: dead} + for range 2 { + code, ok, err := ss.waitMonitorProcess() + if !ok || err != nil || code != 42 { + t.Fatalf("waitMonitorProcess = (%d, %v, %v); want (42, true, nil)", code, ok, err) + } + } + } +} + +// TestSessionPtyTermWiring pins the pty TERM wiring: a pty request +// whose TERM fails acceptEnvPair's value rule is dropped, and a valid +// environ-sourced TERM survives the pty request. +func TestSessionPtyTermWiring(t *testing.T) { + addr := newMonitorSessionServer(t, func(c *conn, s gliderssh.Session) { + c.newSSHSession(s).run() + }) + + // The echo rides behind a leading sleep and is read through a poll + // loop (the shape TestSessionMonitorPTY uses): output written while + // the pty's termios is still settling races the capture. + check := func(setTermEnv bool) string { + t.Helper() + cl, err := gossh.Dial("tcp", addr, &gossh.ClientConfig{ + HostKeyCallback: gossh.InsecureIgnoreHostKey(), + Timeout: 15 * time.Second, + }) + if err != nil { + t.Fatal(err) + } + defer cl.Close() + s, err := cl.NewSession() + if err != nil { + t.Fatal(err) + } + defer s.Close() + if setTermEnv { + // A valid environ-sourced TERM: accepted by acceptEnvPair's + // value rule and placed in the incubator env by incubatorEnv. + if err := s.Setenv("TERM", "dumb"); err != nil { + t.Fatal(err) + } + } + // A pty TERM that is a path: rejected by the value rule, dropped. + if err := s.RequestPty("x/bad-term", 24, 80, gossh.TerminalModes{}); err != nil { + t.Fatal(err) + } + var out sessTestBuffer + s.Stdout = &out + s.Stderr = &out + if err := s.Start(`sleep 1; echo "TERM=${TERM-unset}"; exit 3`); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(10 * time.Second) + for !strings.Contains(out.String(), "TERM=") { + if time.Now().After(deadline) { + t.Fatalf("no TERM line from the child; got %q", out.String()) + } + time.Sleep(50 * time.Millisecond) + } + err = s.Wait() + var ee *gossh.ExitError + if !errors.As(err, &ee) || ee.ExitStatus() != 3 { + t.Fatalf("session Wait = %v; want exit status 3", err) + } + return out.String() + } + + // No environ TERM: the bad pty TERM is dropped, so the child has no + // TERM from us (not the bad value, not a sanitized one). What the + // child's shell then does with an absent TERM is the shell's own + // business: macOS's /bin/sh (bash 3.2) initializes TERM=dumb itself + // when the environment lacks one, while other shells leave it unset. + // The pinned invariant is the absence of the rejected value. + wantDropped := "x/bad-term" + wantLine := "TERM=unset\r" + if runtime.GOOS == "darwin" { + wantLine = "TERM=dumb\r" // /bin/sh initializes it; see above + } + if got := check(false); strings.Contains(got, wantDropped) || !strings.Contains(got, wantLine) { + t.Errorf("child TERM after rejecting PTY TERM = %q; want %q", got, wantLine) + } + // A valid environ-sourced TERM is not overridden by the bad pty TERM + // (the old last-wins inversion). + if got := check(true); !strings.Contains(got, "TERM=dumb\r") { + t.Errorf("child TERM after rejecting PTY TERM = %q; want TERM=dumb", got) + } +} + +// sessTestBuffer is a concurrency-safe bytes.Buffer: the client serves +// stdout and stderr from distinct goroutines (the integration-tagged suite +// has its own lockedBuffer; this one is local to the monitor session tests). +type sessTestBuffer struct { + mu sync.Mutex + b bytes.Buffer +} + +func (out *sessTestBuffer) Write(p []byte) (int, error) { + out.mu.Lock() + defer out.mu.Unlock() + return out.b.Write(p) +} + +func (out *sessTestBuffer) String() string { + out.mu.Lock() + defer out.mu.Unlock() + return out.b.String() +} + +// TestSessionMonitorHangupEscalation pins the teardown escalation: a +// session child group that survives the teardown SIGHUP is SIGKILLed +// after hangupEscalation, and its exit code is 128+SIGKILL, the shell +// convention. +func TestSessionMonitorHangupEscalation(t *testing.T) { + lu := fwdTestIdentity(t) + c := newFwdTestConn(t, lu, &tailcfg.SSHAction{Accept: true}) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + ss := &sshSession{ + ctx: ctx, + conn: c, + logf: t.Logf, + } + + // An HUP-immune child: sh traps (ignores) SIGHUP and its own children + // re-spawn, so only the group SIGKILL ends it. The marker gates the + // hangup on the trap being installed. + cmd := exec.Command("/bin/sh", "-c", "trap '' HUP; echo ready; while :; do sleep 1; done") + cmd.Args = incubatorChildArgv(cmd.Args) + stdin, stdinKeep, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer stdinKeep.Close() + stdout, stdoutW, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer stdout.Close() + stderr, stderrW, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer stderr.Close() + if err := ss.launchViaMonitor(cmd, nil, []*os.File{stdin, stdoutW, stderrW}, false); err != nil { + t.Fatalf("launchViaMonitor: %v", err) + } + stdoutW.Close() + stderrW.Close() + // Read just the marker (the child never exits, so no EOF read here). + if err := stdout.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil { + t.Fatal(err) + } + marker := make([]byte, len("ready\n")) + if _, err := io.ReadFull(stdout, marker); err != nil { + t.Fatalf("reading ready marker: %v", err) + } + if string(marker) != "ready\n" { + t.Fatalf("child output = %q; want ready (the HUP trap is installed)", marker) + } + + ss.hangupMonitorProcess() + + // The child must die via the SIGKILL escalation (128+9) within the + // escalation window plus slack. + deadline := time.Now().Add(hangupEscalation + 5*time.Second) + for { + select { + case <-ss.monExit.done: + code := ss.monExit.code + if want := 128 + int(unix.SIGKILL); code != want { + t.Fatalf("exit code = %d, want %d (128+SIGKILL)", code, want) + } + return + case <-time.After(100 * time.Millisecond): + if time.Now().After(deadline) { + t.Fatalf("child survived SIGHUP by %v", hangupEscalation+5*time.Second) + } + } + } +} + +// TestLaunchViaMonitorRefusesCanceledContext pins the pre-flight ctx +// refusal at the top of launchViaMonitor: a session whose ctx is +// already canceled must refuse the launch before the exec op is +// written, without spawning a monitor to do it. +func TestLaunchViaMonitorRefusesCanceledContext(t *testing.T) { + lu := fwdTestIdentity(t) + c := newFwdTestConn(t, lu, &tailcfg.SSHAction{Accept: true}) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + ss := &sshSession{ + ctx: ctx, + conn: c, + logf: t.Logf, + } + + stdin, stdinKeep, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer stdinKeep.Close() + stdout, stdoutW, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer stdout.Close() + stderr, stderrW, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer stderr.Close() + cmd := exec.Command("/bin/sh", "-c", "echo doomed; sleep 30") + cmd.Args = incubatorChildArgv(cmd.Args) + err = ss.launchViaMonitor(cmd, nil, []*os.File{stdin, stdoutW, stderrW}, false) + stdoutW.Close() + stderrW.Close() + if !errors.Is(err, context.Canceled) { + t.Fatalf("launchViaMonitor = %v; want context.Canceled", err) + } + if mc := c.fwdMonitorIfAny(); mc != nil { + t.Fatal("launchViaMonitor spawned a monitor for a canceled session") + } +} + +// TestHangupMonitorProcessAfterMonitorClosed checks that teardown neither +// recreates the monitor nor signals an unrelated process with a reused PID. +func TestHangupMonitorProcessAfterMonitorClosed(t *testing.T) { + lu := fwdTestIdentity(t) + c := newFwdTestConn(t, lu, &tailcfg.SSHAction{Accept: true}) + if _, err := c.fwdMonitor(); err != nil { + t.Fatal(err) + } + c.closeFwdMonitor() + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, "cat") + stdin, err := cmd.StdinPipe() + if err != nil { + t.Fatal(err) + } + var output bytes.Buffer + cmd.Stdout = &output + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + defer func() { + cmd.Process.Kill() + cmd.Wait() + }() + ss := &sshSession{ + ctx: ctx, + conn: c, + logf: t.Logf, + monChild: monitorProcess{PID: cmd.Process.Pid, ID: 1}, + } + if !ss.hangupMonitorProcess() { + t.Fatal("monitor session took the direct hangup path") + } + if got := c.fwdMonitorIfAny(); got != nil { + t.Fatal("hangup recreated a closed monitor") + } + if _, err := io.WriteString(stdin, "alive\n"); err != nil { + t.Fatal(err) + } + stdin.Close() + if err := cmd.Wait(); err != nil { + t.Fatalf("unrelated process was signaled: %v", err) + } + if output.String() != "alive\n" { + t.Fatalf("unrelated process output = %q", output.String()) + } +}