diff --git a/.github/workflows/ssh-integrationtest.yml b/.github/workflows/ssh-integrationtest.yml index 3dab7c25d..adf519264 100644 --- a/.github/workflows/ssh-integrationtest.yml +++ b/.github/workflows/ssh-integrationtest.yml @@ -1,4 +1,4 @@ -# Run the ssh integration tests in various Docker containers. +# Run the ssh integration tests in various Docker containers and on macOS. # These tests can also be run locally via `make sshintegrationtest`. name: "ssh-integrationtest" @@ -49,3 +49,38 @@ jobs: - name: Run SSH integration tests (${{ matrix.base }}) run: | docker build --build-arg="BASE=${{ matrix.base }}" -t "${{ matrix.tag }}" ssh/tailssh/testcontainers + + ssh-integrationtest-macos: + runs-on: macos-latest + steps: + - name: Check out code + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - name: Build test binaries + run: | + ./tool/go test -tags integrationtest -c ./ssh/tailssh -o /tmp/tailssh.test + ./tool/go build -o /tmp/tailscaled ./cmd/tailscaled + - name: Set up test user and Paramiko + run: | + sudo dseditgroup -o create groupone + sudo dseditgroup -o create grouptwo + # The Linux containers also give testuser /bin/sh. zsh, the macOS + # default, turns ECHO back on for the commands it runs, which + # TestIntegrationPTYTerminalModes notices. + sudo sysadminctl -addUser testuser -password "$(uuidgen)" -shell /bin/sh + sudo dseditgroup -o edit -a testuser -t user groupone + sudo dseditgroup -o edit -a testuser -t user grouptwo + sudo createhomedir -c -u testuser + sudo -H python3 -m pip install paramiko==3.5.1 || sudo -H python3 -m pip install --break-system-packages paramiko==3.5.1 + - name: Run SSH integration tests as root + working-directory: /tmp + run: | + eval $(ssh-agent -s) + sudo --preserve-env=SSH_AUTH_SOCK TAILSCALED_PATH=/tmp/tailscaled ./tailssh.test -test.v \ + -test.run 'TestSSHAgentForwarding|TestIntegration|TestOpenSSHExitCodes|TestLocalUnixForwardingHalfClose' + - name: Run SSH integration tests as testuser + working-directory: /tmp + run: | + sudo touch /tmp/tailscalessh.log + sudo chown testuser /tmp/tailscalessh.log + sudo -u testuser env TAILSCALED_PATH=/tmp/tailscaled sh -c 'eval $(ssh-agent -s) && ./tailssh.test -test.v \ + -test.run "TestSSHAgentForwarding|TestIntegration|TestOpenSSHExitCodes|TestLocalUnixForwardingHalfClose|TestDoDropPrivileges"' diff --git a/ssh/tailssh/incubator.go b/ssh/tailssh/incubator.go index 7f5727113..aea92a05c 100644 --- a/ssh/tailssh/incubator.go +++ b/ssh/tailssh/incubator.go @@ -23,6 +23,7 @@ import ( "log/syslog" "os" "os/exec" + "os/signal" "path/filepath" "runtime" "slices" @@ -62,6 +63,11 @@ func registerIncubator() { childproc.Add("sftp", beSFTP) childproc.Add("ssh-monitor", beMonitor) childproc.Add("ssh-fwd", beFwdChild) + if runtime.GOOS == darwin { + // Only macOS login needs its exit status relayed. + // See [runLoginRelayingExitStatus]. + childproc.Add(loginCmdChildMode, beLoginCmd) + } } var ptyName = func(f *os.File) (string, error) { @@ -577,11 +583,17 @@ func runningAsRoot() bool { // // 1. login cannot be used to execute commands except on macOS. // 2. On Linux and BSD, login requires a TTY to keep running. +// 3. On macOS, login exits 0 no matter how the command it ran exited. // -// In these cases, tryExecLogin returns (false, nil) to indicate that processing +// In cases 1 and 2, tryExecLogin returns nil to indicate that processing // should fall through to other methods, such as using the su command. // -// Note that this uses unix.Exec to replace the current process, so in cases +// Case 3 matters for commands and for shells without a TTY; see +// [incubatorArgs.loginNeedsExitStatusRelay]. For those, login is run as a +// child instead and the exit status is relayed around it by +// runLoginRelayingExitStatus, after which this process exits with that status. +// +// Otherwise, this uses unix.Exec to replace the current process, so in cases // where we actually do run login, no subsequent Go code will execute. func tryExecLogin(dlogf logger.Logf, ia incubatorArgs) error { // Only the macOS version of the login command supports executing a @@ -608,6 +620,19 @@ func tryExecLogin(dlogf logger.Logf, ia incubatorArgs) error { dlogf("failed to get login args: %s", err) return nil } + + if ia.loginNeedsExitStatusRelay(runtime.GOOS) { + self, err := os.Executable() + if err != nil { + return fmt.Errorf("finding tailscaled to relay the exit status through login: %w", err) + } + code, err := runLoginRelayingExitStatus(dlogf, ia, loginCmdPath, self) + if err != nil { + return err + } + os.Exit(code) + } + loginArgs := ia.loginArgs(loginCmdPath) dlogf("logging in with %+v", loginArgs) @@ -1382,25 +1407,10 @@ func fileExists(path string) bool { func (ia *incubatorArgs) loginArgs(loginCmdPath string) []string { switch runtime.GOOS { case darwin: - args := []string{ - loginCmdPath, - "-f", // already authenticated - - // login typically discards the previous environment, but we want to - // preserve any environment variables that we currently have. - "-p", - - "-h", ia.remoteIP, // -h is "remote host" - ia.localUser, - } - if !ia.hasTTY { - args[2] = "-pq" // -q is "quiet" which suppresses the login banner - } if ia.cmd != "" { - args = append(args, ia.loginShell, "-c", ia.cmd) + return ia.darwinLoginArgs(loginCmdPath, ia.loginShell, "-c", ia.cmd) } - - return args + return ia.darwinLoginArgs(loginCmdPath) case linux: if distro.Get() == distro.Arch && !fileExists("/etc/pam.d/remote") { // See https://github.com/tailscale/tailscale/issues/4924 @@ -1417,6 +1427,253 @@ func (ia *incubatorArgs) loginArgs(loginCmdPath string) []string { panic("unimplemented") } +// darwinLoginArgs returns the arguments to exec the macOS login binary at +// loginCmdPath, which runs prog (a program and its arguments) as ia.localUser, +// or the user's shell if prog is empty. +func (ia *incubatorArgs) darwinLoginArgs(loginCmdPath string, prog ...string) []string { + args := []string{ + loginCmdPath, + "-f", // already authenticated + + // login typically discards the previous environment, but we want to + // preserve any environment variables that we currently have. + "-p", + + "-h", ia.remoteIP, // -h is "remote host" + ia.localUser, + } + if !ia.hasTTY { + args[2] = "-pq" // -q is "quiet" which suppresses the login banner + } + return append(args, prog...) +} + +// loginNeedsExitStatusRelay reports whether a session that tryExecLogin hands +// to login on goos must relay the command's exit status around login rather +// than exec into it. +// +// macOS login runs the program it is given as a child and then exits 0 +// regardless of how that program exited, so exec'ing into it would report +// every command, and every shell fed a script on stdin ("ssh -T host < +// script"), as successful to the SSH client. Interactive shells with a TTY +// and SFTP keep exec'ing into login unchanged. +func (ia *incubatorArgs) loginNeedsExitStatusRelay(goos string) bool { + if goos != darwin || ia.isSFTP { + return false + } + if ia.isShell { + return !ia.hasTTY + } + return ia.cmd != "" +} + +// loginCmdChildMode is the "tailscaled be-child" mode that login runs, in +// place of the user's shell, when the incubator relays a command's exit +// status around macOS login. See runLoginRelayingExitStatus. +const loginCmdChildMode = "ssh-login-cmd" + +// loginCmdSpawnPrefix is the argv prefix, after the executable path, that +// runLoginRelayingExitStatus passes to login to run beLoginCmd. Tests +// override it to re-exec the test binary. +var loginCmdSpawnPrefix = []string{"be-child", loginCmdChildMode} + +// runLoginRelayingExitStatus runs the session (ia.cmd, or the user's shell if +// ia.isShell) through the login command at loginCmdPath, like tryExecLogin, +// but as a child rather than with exec, and returns the session's exit status, +// which login itself does not report on macOS. +// +// login is told to run "self be-child ssh-login-cmd" (beLoginCmd), which runs +// the user's shell exactly as login would have and writes the shell's exit +// status to a file created here and owned by the local user. login closes +// inherited descriptors, so a file named by path is used rather than a pipe. +// beLoginCmd opens the file and unlinks it as soon as it starts, and the +// status is read back through this process's own descriptor, so replacing the +// file at that path cannot make this process, which runs as root, read +// anything else. +// +// login stays in this process's process group, as it would have had this +// process exec'd into it, so that signals the ssh-monitor sends to the +// session's group, including its SIGKILL escalation, reach login and the +// command. With a TTY, that group is the terminal's foreground group, so this +// process ignores the terminal's SIGINT and SIGQUIT while it waits. +// +// If no status is recorded, for instance because beLoginCmd was killed, it +// returns login's own exit status if that is non-zero, and 1 otherwise. It +// never reports success for a command whose status is unknown. +func runLoginRelayingExitStatus(dlogf logger.Logf, ia incubatorArgs, loginCmdPath, self string) (int, error) { + // Use /tmp rather than os.TempDir: the local user must be able to reach + // the file, and this process's $TMPDIR, if set, may be private to root. + f, err := os.CreateTemp("/tmp", "tailscale-ssh-status-") + if err != nil { + return 0, err + } + defer f.Close() + defer removeIfSameFile(f) // in case beLoginCmd never ran + if err := f.Chown(ia.uid, ia.gid); err != nil { + return 0, err + } + + prog := append([]string{self}, loginCmdSpawnPrefix...) + prog = append(prog, + "--status-file="+f.Name(), + "--login-shell="+ia.loginShell, + ) + if ia.isShell { + prog = append(prog, "--shell") + } else { + prog = append(prog, "--cmd="+ia.cmd) + } + loginArgs := ia.darwinLoginArgs(loginCmdPath, prog...) + dlogf("logging in with %+v", loginArgs) + + environ := append(ia.rootExecEnviron(), ia.forwardedEnv...) + cmd := loginRelayCommand(loginCmdPath, environ, loginArgs[1:]) + + sigs := make(chan os.Signal, 1) + signal.Notify(sigs, syscall.SIGINT, syscall.SIGQUIT) + defer signal.Stop(sigs) + + runErr := cmd.Run() + if runErr != nil { + if _, ok := runErr.(*exec.ExitError); !ok { + return 0, runErr + } + } + + if code, ok := readExitStatus(f); ok { + return code, nil + } + dlogf("no exit status recorded by %s; login: %v", loginCmdChildMode, cmd.ProcessState) + if code := processExitStatus(cmd.ProcessState); code != 0 { + return code, nil + } + return 1, nil +} + +// loginRelayCommand returns the command that runLoginRelayingExitStatus uses +// to run login. Unlike newCommand, it never puts login in a new process group +// (not even the terminal's foreground group): login must stay in this +// process's group, which the ssh-monitor signals to terminate the session. +func loginRelayCommand(loginCmdPath string, environ, args []string) *exec.Cmd { + cmd := exec.Command(loginCmdPath, args...) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + cmd.Env = environ + return cmd +} + +// removeIfSameFile removes f's path if it still names f. +func removeIfSameFile(f *os.File) { + fi, err := f.Stat() + if err != nil { + return + } + if pfi, err := os.Lstat(f.Name()); err == nil && os.SameFile(fi, pfi) { + os.Remove(f.Name()) + } +} + +// readExitStatus reads the exit status that beLoginCmd recorded in f. +// It reports false if f does not hold a valid exit status. +func readExitStatus(f *os.File) (code int, ok bool) { + var buf [16]byte + n, err := f.ReadAt(buf[:], 0) + if err != nil && err != io.EOF { + return 0, false + } + code, err = strconv.Atoi(strings.TrimSpace(string(buf[:n]))) + if err != nil || code < 0 || code > 255 { + return 0, false + } + return code, true +} + +// processExitStatus returns the exit status of a process that has exited, using the +// shell convention of 128+n for a process killed by signal n. +func processExitStatus(ps *os.ProcessState) int { + if ws, ok := ps.Sys().(syscall.WaitStatus); ok && ws.Signaled() { + return 128 + int(ws.Signal()) + } + return ps.ExitCode() +} + +// beLoginCmd is the entrypoint to the "tailscaled be-child ssh-login-cmd" +// subcommand, which macOS login runs as the local user on behalf of +// runLoginRelayingExitStatus. It runs --cmd with the user's --login-shell, +// or with --shell runs the shell itself, and exits with the shell's exit +// status after writing it to --status-file. +func beLoginCmd(args []string) error { + code, err := runLoginCmd(args) + if err != nil { + return err + } + os.Exit(code) + return nil +} + +// runLoginCmd implements beLoginCmd, returning the exit status rather than +// exiting. +func runLoginCmd(args []string) (int, error) { + var statusFile, loginShell, cmdStr string + var isShell bool + flags := flag.NewFlagSet(loginCmdChildMode, flag.ContinueOnError) + flags.StringVar(&statusFile, "status-file", "", "file to write the command's exit status to") + flags.StringVar(&loginShell, "login-shell", "", "path to the user's login shell") + flags.StringVar(&cmdStr, "cmd", "", "the command to run with the login shell") + flags.BoolVar(&isShell, "shell", false, "run the login shell itself rather than --cmd") + if err := flags.Parse(args); err != nil { + return 0, err + } + if statusFile == "" || loginShell == "" { + return 0, errors.New("--status-file and --login-shell are required") + } + + // Open the status file now and unlink it, so that it does not outlive + // the session even if this process or the incubator is killed. The + // incubator holds its own descriptor to read the status from. If it + // cannot be opened, run the command anyway; the incubator then reports + // a failure. + sf, err := os.OpenFile(statusFile, os.O_WRONLY|os.O_TRUNC, 0) + if err == nil { + defer sf.Close() + os.Remove(statusFile) + } + + // Run the shell as a login shell, as login itself would when given it + // as the program to run: argv[0] is the shell's name prefixed by "-". + var cmd *exec.Cmd + if isShell { + cmd = exec.Command(loginShell) + } else { + cmd = exec.Command(loginShell, "-c", cmdStr) + } + cmd.Args[0] = "-" + filepath.Base(loginShell) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + + // With a TTY, this process shares the terminal's foreground process + // group with the command, so it also receives the terminal's SIGINT and + // SIGQUIT. Leave + // those to the command and outlive it to record its status. (Signals + // caught here are reset to their default action in the command.) + sigs := make(chan os.Signal, 1) + signal.Notify(sigs, syscall.SIGINT, syscall.SIGQUIT) + defer signal.Stop(sigs) + + if err := cmd.Run(); err != nil { + if _, ok := err.(*exec.ExitError); !ok { + return 0, err + } + } + code := processExitStatus(cmd.ProcessState) + if sf != nil { + fmt.Fprintf(sf, "%d\n", code) + } + return code, nil +} + func shellArgs(isShell bool, cmd string) []string { if isShell { if runtime.GOOS == freebsd || runtime.GOOS == openbsd { diff --git a/ssh/tailssh/incubator_test.go b/ssh/tailssh/incubator_test.go index a5a07f0b1..e63cc8d50 100644 --- a/ssh/tailssh/incubator_test.go +++ b/ssh/tailssh/incubator_test.go @@ -11,9 +11,13 @@ import ( "fmt" "net/netip" "os" + "os/exec" "os/user" + "path/filepath" "slices" + "strconv" "strings" + "syscall" "testing" gliderssh "github.com/tailscale/gliderssh" @@ -465,3 +469,280 @@ func TestDirectExecRootFallbackRefused(t *testing.T) { } } } + +func TestLoginNeedsExitStatusRelay(t *testing.T) { + for _, tt := range []struct { + name string + goos string + ia incubatorArgs + want bool + }{ + {name: "darwin-cmd", goos: darwin, ia: incubatorArgs{cmd: "exit 7"}, want: true}, + {name: "darwin-cmd-tty", goos: darwin, ia: incubatorArgs{cmd: "exit 7", hasTTY: true}, want: true}, + {name: "darwin-shell", goos: darwin, ia: incubatorArgs{isShell: true}, want: true}, + {name: "darwin-shell-tty", goos: darwin, ia: incubatorArgs{isShell: true, hasTTY: true}, want: false}, + {name: "darwin-sftp", goos: darwin, ia: incubatorArgs{isSFTP: true, cmd: "tailscaled be-child sftp"}, want: false}, + {name: "linux-cmd", goos: linux, ia: incubatorArgs{cmd: "exit 7"}, want: false}, + {name: "linux-shell", goos: linux, ia: incubatorArgs{isShell: true}, want: false}, + {name: "freebsd-cmd", goos: freebsd, ia: incubatorArgs{cmd: "exit 7"}, want: false}, + } { + t.Run(tt.name, func(t *testing.T) { + if got := tt.ia.loginNeedsExitStatusRelay(tt.goos); got != tt.want { + t.Errorf("loginNeedsExitStatusRelay(%q) = %v; want %v", tt.goos, got, tt.want) + } + }) + } +} + +func TestDarwinLoginArgs(t *testing.T) { + ia := incubatorArgs{localUser: "alice", remoteIP: "100.64.0.1"} + if got, want := ia.darwinLoginArgs("/usr/bin/login"), []string{"/usr/bin/login", "-f", "-pq", "-h", "100.64.0.1", "alice"}; !slices.Equal(got, want) { + t.Errorf("no tty, no prog: got %q; want %q", got, want) + } + ia.hasTTY = true + got := ia.darwinLoginArgs("/usr/bin/login", "/bin/zsh", "-c", "exit 7") + want := []string{"/usr/bin/login", "-f", "-p", "-h", "100.64.0.1", "alice", "/bin/zsh", "-c", "exit 7"} + if !slices.Equal(got, want) { + t.Errorf("tty, prog: got %q; want %q", got, want) + } +} + +func TestReadExitStatus(t *testing.T) { + for _, tt := range []struct { + content string + code int + ok bool + }{ + {"7\n", 7, true}, + {"0\n", 0, true}, + {"255", 255, true}, + {"137\n", 137, true}, + {"", 0, false}, + {"256\n", 0, false}, + {"-1\n", 0, false}, + {"x\n", 0, false}, + } { + f, err := os.CreateTemp(t.TempDir(), "status") + if err != nil { + t.Fatal(err) + } + if _, err := f.WriteString(tt.content); err != nil { + t.Fatal(err) + } + code, ok := readExitStatus(f) + f.Close() + if code != tt.code || ok != tt.ok { + t.Errorf("readExitStatus(%q) = %d, %v; want %d, %v", tt.content, code, ok, tt.code, tt.ok) + } + } +} + +func TestRunLoginCmd(t *testing.T) { + dir := t.TempDir() + + // run runs runLoginCmd with a fresh status file, opened beforehand as + // runLoginRelayingExitStatus does, and returns the exit status and the + // status read back through that descriptor. + run := func(t *testing.T, args ...string) (code int, recorded string) { + t.Helper() + f, err := os.CreateTemp(dir, "status") + if err != nil { + t.Fatal(err) + } + defer f.Close() + code, err = runLoginCmd(append([]string{"--status-file=" + f.Name()}, args...)) + if err != nil { + t.Fatal(err) + } + if _, err := os.Lstat(f.Name()); !os.IsNotExist(err) { + t.Errorf("status file still present after runLoginCmd: %v", err) + } + var buf [32]byte + n, _ := f.ReadAt(buf[:], 0) + return code, string(buf[:n]) + } + + for _, tt := range []struct { + cmd string + want int + }{ + {"true", 0}, + {"exit 7", 7}, + {"kill -9 $$", 128 + 9}, + } { + t.Run(tt.cmd, func(t *testing.T) { + code, recorded := run(t, "--login-shell=/bin/sh", "--cmd="+tt.cmd) + if code != tt.want { + t.Errorf("exit status = %d; want %d", code, tt.want) + } + if want := fmt.Sprintf("%d\n", tt.want); recorded != want { + t.Errorf("recorded status = %q; want %q", recorded, want) + } + }) + } + + // The shell runs as a login shell, like login runs it: argv[0] is "-sh". + out := filepath.Join(dir, "argv0") + run(t, "--login-shell=/bin/sh", `--cmd=echo "$0" > `+out) + if b, _ := os.ReadFile(out); strings.TrimSpace(string(b)) != "-sh" { + t.Errorf("shell argv[0] = %q; want %q", b, "-sh") + } + + // With --shell, the shell is run with no arguments. + shell := filepath.Join(dir, "shell") + shellOut := filepath.Join(dir, "shell-args") + if err := os.WriteFile(shell, []byte("#!/bin/sh\necho \"$#\" > "+shellOut+"\nexit 6\n"), 0o755); err != nil { + t.Fatal(err) + } + if code, recorded := run(t, "--login-shell="+shell, "--shell"); code != 6 || recorded != "6\n" { + t.Errorf("--shell: exit status %d, recorded %q; want 6, %q", code, recorded, "6\n") + } + if b, _ := os.ReadFile(shellOut); strings.TrimSpace(string(b)) != "0" { + t.Errorf("--shell: shell got %q arguments; want 0", b) + } + + // A missing status file does not prevent the command from running. + if code, err := runLoginCmd([]string{"--status-file=" + filepath.Join(dir, "missing"), "--login-shell=/bin/sh", "--cmd=exit 3"}); err != nil || code != 3 { + t.Errorf("runLoginCmd with missing status file = %d, %v; want 3, nil", code, err) + } + if _, err := os.Stat(filepath.Join(dir, "missing")); !os.IsNotExist(err) { + t.Errorf("runLoginCmd created the missing status file: %v", err) + } +} + +// testLoginCmdPrefix re-execs the test binary as beLoginCmd, selecting only +// TestSSHLoginCmdHelperProcess; in tailscaled the prefix is +// "be-child ssh-login-cmd". +var testLoginCmdPrefix = []string{"-test.run=^TestSSHLoginCmdHelperProcess$", "-test.timeout=0", "--", loginCmdChildMode} + +// TestSSHLoginCmdHelperProcess is not a test; it is the entry point of the +// re-exec'd beLoginCmd child that the fake login in +// TestRunLoginRelayingExitStatus runs. It returns immediately otherwise. +func TestSSHLoginCmdHelperProcess(t *testing.T) { + for i, a := range os.Args { + if a == "--" && i+1 < len(os.Args) && os.Args[i+1] == loginCmdChildMode { + if err := beLoginCmd(os.Args[i+2:]); err != nil { + fmt.Fprintln(os.Stderr, "ssh-login-cmd child:", err) + os.Exit(1) + } + } + } +} + +// fakeDarwinLogin mimics how macOS login handles "login -f [-pq] [-h host] +// user prog [args...]": it runs prog as a child with descriptors above 2 +// closed and then exits 0 no matter how prog exited. +const fakeDarwinLogin = `#!/bin/sh +while [ $# -gt 0 ]; do + case "$1" in + -f|-p|-q|-pq) shift ;; + -h) shift 2 ;; + *) break ;; + esac +done +shift # user +"$@" 3>&- 4>&- 5>&- 6>&- 7>&- 8>&- 9>&- +exit 0 +` + +func TestRunLoginRelayingExitStatus(t *testing.T) { + oldPrefix := loginCmdSpawnPrefix + loginCmdSpawnPrefix = testLoginCmdPrefix + t.Cleanup(func() { loginCmdSpawnPrefix = oldPrefix }) + + self, err := os.Executable() + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + writeLogin := func(name, script string) string { + p := filepath.Join(dir, name) + if err := os.WriteFile(p, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + return p + } + darwinLogin := writeLogin("login", fakeDarwinLogin) + shell6 := writeLogin("shell6", "#!/bin/sh\nexit 6\n") + + ia := incubatorArgs{ + uid: os.Getuid(), + gid: os.Getgid(), + localUser: "alice", + remoteIP: "100.64.0.1", + loginShell: "/bin/sh", + } + for _, tt := range []struct { + name string + login string + cmd string + shell string // if set, a shell session with this login shell + want int + }{ + {name: "success", login: darwinLogin, cmd: "true", want: 0}, + {name: "failure", login: darwinLogin, cmd: "exit 7", want: 7}, + {name: "signal", login: darwinLogin, cmd: "kill -9 $$", want: 128 + 9}, + {name: "shell", login: darwinLogin, shell: shell6, want: 6}, + // Without a recorded status, a failing login's status is used, and + // a "successful" one is never reported as the command's success. + {name: "login-fails", login: writeLogin("login-fails", "#!/bin/sh\nexit 3\n"), cmd: "true", want: 3}, + {name: "login-skips-prog", login: writeLogin("login-skips", "#!/bin/sh\nexit 0\n"), cmd: "true", want: 1}, + } { + t.Run(tt.name, func(t *testing.T) { + ia := ia + ia.cmd = tt.cmd + if tt.shell != "" { + ia.isShell = true + ia.loginShell = tt.shell + } + code, err := runLoginRelayingExitStatus(t.Logf, ia, tt.login, self) + if err != nil { + t.Fatal(err) + } + if code != tt.want { + t.Errorf("exit status = %d; want %d", code, tt.want) + } + }) + } +} + +// TestLoginRelayStaysInProcessGroup verifies that login, run by +// runLoginRelayingExitStatus, stays in the incubator's process group, which +// is the group the ssh-monitor signals (SIGHUP, then SIGKILL) to terminate a +// session. A TTY must not move it to a group of its own. +func TestLoginRelayStaysInProcessGroup(t *testing.T) { + // newCommand, used before, puts the command in a new foreground process + // group when there is a TTY; the relay must not, TTY or not. + cmd := loginRelayCommand("/usr/bin/login", nil, []string{"-f", "alice"}) + if a := cmd.SysProcAttr; a != nil && (a.Setpgid || a.Setsid || a.Foreground) { + t.Errorf("login SysProcAttr = %+v; want it to stay in the incubator's process group", a) + } + + if _, err := exec.LookPath("ps"); err != nil { + t.Skip("no ps") + } + oldPrefix := loginCmdSpawnPrefix + loginCmdSpawnPrefix = testLoginCmdPrefix + t.Cleanup(func() { loginCmdSpawnPrefix = oldPrefix }) + self, err := os.Executable() + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + pgidFile := filepath.Join(dir, "pgid") + login := filepath.Join(dir, "login") + if err := os.WriteFile(login, []byte("#!/bin/sh\nps -o pgid= -p $$ > "+pgidFile+"\n"+strings.TrimPrefix(fakeDarwinLogin, "#!/bin/sh\n")), 0o755); err != nil { + t.Fatal(err) + } + ia := incubatorArgs{uid: os.Getuid(), gid: os.Getgid(), localUser: "alice", remoteIP: "100.64.0.1", loginShell: "/bin/sh", cmd: "true"} + if _, err := runLoginRelayingExitStatus(t.Logf, ia, login, self); err != nil { + t.Fatal(err) + } + b, err := os.ReadFile(pgidFile) + if err != nil || strings.TrimSpace(string(b)) == "" { + t.Skipf("ps could not report login's process group: %q, %v", b, err) + } + if got, want := strings.TrimSpace(string(b)), strconv.Itoa(syscall.Getpgrp()); got != want { + t.Errorf("login ran in process group %s; want the incubator's, %s", got, want) + } +} diff --git a/ssh/tailssh/sessmonitor_test.go b/ssh/tailssh/sessmonitor_test.go index 836f9dadb..ac62b265f 100644 --- a/ssh/tailssh/sessmonitor_test.go +++ b/ssh/tailssh/sessmonitor_test.go @@ -95,6 +95,9 @@ func TestSSHIncubatorHelperProcess(t *testing.T) { if path := incubDumpArg(os.Args[i+2:]); path != "" { dumpChildFdsTo(path, "incubator") } + // On macOS, login runs os.Executable, which is this test + // binary, so route it to TestSSHLoginCmdHelperProcess. + loginCmdSpawnPrefix = testLoginCmdPrefix if err := beIncubator(os.Args[i+2:]); err != nil { fmt.Fprintln(os.Stderr, "ssh incubator child:", err) os.Exit(1) diff --git a/ssh/tailssh/tailssh_integration_session_test.go b/ssh/tailssh/tailssh_integration_session_test.go index bf8168903..e180f53d4 100644 --- a/ssh/tailssh/tailssh_integration_session_test.go +++ b/ssh/tailssh/tailssh_integration_session_test.go @@ -16,6 +16,7 @@ import ( "os/exec" "path/filepath" "regexp" + "runtime" "slices" "strings" "testing" @@ -135,6 +136,13 @@ type ptyShell struct { // startPTYShell starts an interactive shell on cl with a pty allocated // per req. func startPTYShell(t *testing.T, cl *ssh.Client, req ptyRequest) *ptyShell { + t.Helper() + return startPTYSession(t, cl, req, "") +} + +// startPTYSession starts cmd on cl with a pty allocated per req. An +// empty cmd starts an interactive shell. +func startPTYSession(t *testing.T, cl *ssh.Client, req ptyRequest, cmd string) *ptyShell { t.Helper() s, err := cl.NewSession() if err != nil { @@ -150,8 +158,13 @@ func startPTYShell(t *testing.T, cl *ssh.Client, req ptyRequest) *ptyShell { if err := s.RequestPty(req.term, req.rows, req.cols, req.modes); err != nil { t.Fatalf("RequestPty: %v", err) } - if err := s.Shell(); err != nil { - t.Fatalf("Shell: %v", err) + if cmd == "" { + err = s.Shell() + } else { + err = s.Start(cmd) + } + if err != nil { + t.Fatalf("starting session: %v", err) } go func() { p.waitc <- s.Wait() }() return p @@ -207,14 +220,15 @@ func (p *ptyShell) queryValue(t *testing.T, cmd, key string) string { return val } -// parentCmd prints the command name of the shell's parent process. -const parentCmd = `printf 'parent=%s\n' "$(cat /proc/$PPID/comm)"` +// parentCmd prints the command name of the shell's parent process. It +// falls back to ps where there is no /proc, as on macOS. +const parentCmd = `printf 'parent=%s\n' "$(cat /proc/$PPID/comm 2>/dev/null || basename "$(ps -o comm= -p $PPID)")"` // loginWaitsForShell reports whether the shell's parent process is // login(1). That is the case when login forks the shell and waits for -// it, as the shadow-utils login on Ubuntu and the BusyBox login on -// Alpine do, rather than exec'ing it. Both exit 0 whatever the shell's -// exit status. +// it, as the shadow-utils login on Ubuntu, the BusyBox login on Alpine, +// and the macOS login do, rather than exec'ing it. All of them exit 0 +// whatever the shell's exit status. func (p *ptyShell) loginWaitsForShell(t *testing.T) bool { t.Helper() return p.queryValue(t, parentCmd, "parent") == "login" @@ -323,10 +337,10 @@ func TestIntegrationPTYTerminalModes(t *testing.T) { t.Run("shell", func(t *testing.T) { for _, tt := range tests { p := startPTYShell(t, cl, ptyRequest{term: "xterm", rows: 24, cols: 80, modes: tt.modes}) - if p.loginWaitsForShell(t) && !isBusyBoxLogin() { + if p.loginWaitsForShell(t) && runtime.GOOS == "linux" && !isBusyBoxLogin() { t.Skip("KNOWN BUG: shadow-utils login resets the client's terminal modes") } - out := p.queryValue(t, `printf 'modes=%s\n' "$(stty -a | tr ' \n' ',,')"`, "modes") + out := p.queryValue(t, `printf 'modes=%s\n' "$(stty -a | tr ' \t\n' ',,,')"`, "modes") p.send(t, "exit") check(t, tt.modes, tt.want, strings.ReplaceAll(out, ",", " ")) } @@ -355,6 +369,60 @@ func TestIntegrationPTYExec(t *testing.T) { }) } +// TestIntegrationPTYInterrupt tests that a Ctrl-C typed in a pty +// session's terminal reaches only the command: a command that traps +// SIGINT runs its trap and exits with its own status, and one that +// doesn't dies from SIGINT. +func TestIntegrationPTYInterrupt(t *testing.T) { + forEachBehavior(t, func(t *testing.T, forceV1Behavior bool) { + cl := dialSessionTestClient(t, testServerOpts{forceV1Behavior: forceV1Behavior}) + // interrupt starts cmd, which must print "ready" once it is + // ready for the Ctrl-C, types a Ctrl-C, and returns the + // session's output and the result of [ssh.Session.Wait]. + interrupt := func(t *testing.T, cmd string) (string, error) { + t.Helper() + p := startPTYSession(t, cl, defaultPTY, cmd) + if err := tstest.WaitFor(20*time.Second, func() error { + if !strings.Contains(p.output(), "ready") { + return errors.New("no ready marker") + } + return nil + }); err != nil { + t.Fatalf("%v; output: %q", err, p.output()) + } + if _, err := p.stdin.Write([]byte{0x03}); err != nil { + t.Fatal(err) + } + select { + case err := <-p.waitc: + return p.output(), err + case <-time.After(20 * time.Second): + t.Fatalf("timeout waiting for session to exit; output: %q", p.output()) + } + panic("unreachable") + } + t.Run("trapped", func(t *testing.T) { + out, err := interrupt(t, `trap 'echo caught; exit 3' INT; echo ready; while :; do sleep 1; done`) + if strings.Contains(out, "Session terminated, killing shell") { + // util-linux su shares the terminal's foreground + // process group with the command, catches the + // SIGINT, and kills the command. + t.Skip("KNOWN BUG: su kills the command on Ctrl-C") + } + if code, sig := exitStatus(t, err); code != 3 || sig != "" { + t.Errorf("exit status = %d, signal %q; want 3; output: %q", code, sig, out) + } + if !strings.Contains(out, "caught") { + t.Errorf("command's SIGINT trap didn't run; output: %q", out) + } + }) + t.Run("default", func(t *testing.T) { + out, err := interrupt(t, `echo ready; exec sleep 30`) + checkSignaled(t, err, out, 2) + }) + }) +} + // TestIntegrationPTYTerm tests that the pty request's terminal type is // the session's $TERM, both for commands and for login shells. func TestIntegrationPTYTerm(t *testing.T) { @@ -637,6 +705,24 @@ func TestIntegrationOpenSSHInteractivePTY(t *testing.T) { }) } +// checkSignaled checks the exit status of a session whose process died +// from signal number signum. See [TestIntegrationPTYExitStatus] for the +// expected status. +func checkSignaled(t *testing.T, err error, output string, signum int) { + t.Helper() + code, sig := exitStatus(t, err) + if sig != "" { + t.Errorf("got exit-signal %q; the server is not expected to send one", sig) + } + want := 128 + signum + if strings.Contains(output, "[tailscale-ssh: process died:") { + want = 1 + } + if code != want { + t.Errorf("exit status = %d, want %d; output: %q", code, want, output) + } +} + // TestIntegrationPTYExitStatus tests the exit status the server reports // when a session's shell exits with a code or is killed by a signal. // @@ -649,22 +735,6 @@ func TestIntegrationOpenSSHInteractivePTY(t *testing.T) { // KNOWN BUG: this pins the current behavior. OpenSSH's sshd sends // "exit-signal" for a signal death, and the two paths should agree. func TestIntegrationPTYExitStatus(t *testing.T) { - // checkSignaled checks the exit status of a session whose shell - // killed itself with signal number signum. - checkSignaled := func(t *testing.T, err error, output string, signum int) { - t.Helper() - code, sig := exitStatus(t, err) - if sig != "" { - t.Errorf("got exit-signal %q; the server is not expected to send one", sig) - } - want := 128 + signum - if strings.Contains(output, "[tailscale-ssh: process died:") { - want = 1 - } - if code != want { - t.Errorf("exit status = %d, want %d; output: %q", code, want, output) - } - } forEachBehavior(t, func(t *testing.T, forceV1Behavior bool) { cl := dialSessionTestClient(t, testServerOpts{forceV1Behavior: forceV1Behavior}) // startShell starts an interactive shell. It skips the test if