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..a8974d1c4 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" @@ -608,11 +609,15 @@ func tryExecLogin(dlogf logger.Logf, ia incubatorArgs) error { dlogf("failed to get login args: %s", err) return nil } - loginArgs := ia.loginArgs(loginCmdPath) - dlogf("logging in with %+v", loginArgs) - environ := append(ia.rootExecEnviron(), ia.forwardedEnv...) + if runtime.GOOS == darwin && ia.cmd != "" { + return runDarwinLoginCommand(dlogf, ia, loginCmdPath, environ) + } + + loginArgs := ia.loginArgs(loginCmdPath, "") + dlogf("logging in with %+v", loginArgs) + // If Exec works, the Go code will not proceed past this: err = unix.Exec(loginCmdPath, loginArgs, environ) @@ -620,6 +625,71 @@ func tryExecLogin(dlogf logger.Logf, ia incubatorArgs) error { return err } +// darwinExitStatusScript is the /bin/sh script that macOS login runs for a +// command. It runs the command in the login shell ($0) and writes the +// command's exit status to the file named by $2, because macOS login itself +// always exits 0. See https://github.com/tailscale/tailscale/issues/18256. +// +// The script shares the terminal's foreground process group with the +// command, so it traps SIGINT and SIGQUIT to survive a Ctrl-C and record +// the command's 128+signal status. Trapped, unlike ignored, signals revert +// to their default action in the command. +const darwinExitStatusScript = `trap : INT QUIT; "$0" -c "$1"; echo $? >"$2"` + +// runDarwinLoginCommand runs ia.cmd via macOS login as a child process and +// exits with the command's exit status, read from a status file that +// [darwinExitStatusScript] writes. login closes all descriptors above +// stderr, so a pipe can't carry the status. It only returns on error. +// +// login stays in the incubator's process group, so the monitor's group +// signals still reach it. The incubator catches the terminal-generated +// signals so that they only affect the command, as when login was exec'd. +func runDarwinLoginCommand(dlogf logger.Logf, ia incubatorArgs, loginCmdPath string, environ []string) error { + statusFile, err := os.CreateTemp("/tmp", "tailscale-ssh-exit-") + if err != nil { + return err + } + defer os.Remove(statusFile.Name()) + defer statusFile.Close() + if err := statusFile.Chown(ia.uid, ia.gid); err != nil { + return err + } + + loginArgs := ia.loginArgs(loginCmdPath, statusFile.Name()) + dlogf("logging in with %+v", loginArgs) + + signal.Notify(make(chan os.Signal, 1), syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTSTP) + + cmd := exec.Command(loginCmdPath, loginArgs[1:]...) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + cmd.Env = environ + if err := cmd.Run(); err != nil { + if _, ok := errors.AsType[*exec.ExitError](err); !ok { + return err + } + } + + // A missing status means the script didn't finish, for example + // because a signal killed it, so report failure rather than login's 0. + code := 1 + if c := cmd.ProcessState.ExitCode(); c > 0 { + code = c + } + // Read through the descriptor opened at creation, not the path, + // which the session user can replace. + if b, err := io.ReadAll(io.LimitReader(statusFile, 16)); err == nil { + if n, err := strconv.Atoi(strings.TrimSpace(string(b))); err == nil && n >= 0 && n <= 255 { + code = n + } + } + statusFile.Close() + os.Remove(statusFile.Name()) + os.Exit(code) + return nil +} + // trySU attempts to start a login shell using su. If su is available and // supports the necessary arguments, this returns true, plus the result of // executing su. Otherwise, it returns (false, nil). @@ -1379,7 +1449,9 @@ func fileExists(path string) bool { } // loginArgs returns the arguments to use to exec the login binary. -func (ia *incubatorArgs) loginArgs(loginCmdPath string) []string { +// On macOS, a command runs via [darwinExitStatusScript], which writes the +// command's exit status to exitStatusPath. +func (ia *incubatorArgs) loginArgs(loginCmdPath, exitStatusPath string) []string { switch runtime.GOOS { case darwin: args := []string{ @@ -1397,7 +1469,7 @@ func (ia *incubatorArgs) loginArgs(loginCmdPath string) []string { args[2] = "-pq" // -q is "quiet" which suppresses the login banner } if ia.cmd != "" { - args = append(args, ia.loginShell, "-c", ia.cmd) + args = append(args, "/bin/sh", "-c", darwinExitStatusScript, ia.loginShell, ia.cmd, exitStatusPath) } return args 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