From eba00ab3638983a0c274e2ea271476c80fcd8acf Mon Sep 17 00:00:00 2001 From: James Tucker Date: Sat, 24 Oct 2026 02:52:59 +0000 Subject: [PATCH] ssh/tailssh: route SSH forwarding through the privileged monitor Route tailssh's forwarding through the per-connection ssh-monitor, so on unix forwarded sockets are dialed and bound by children with the authenticated local user's credentials, never by root tailscaled. - unix -L, direct-streamlocal: the lexical allowlist check stays in tailscaled as coarse policy. The allowlist is home, /tmp, and /run/user/. Relative and abstract paths are rejected. The dial then runs as the user through the monitor. The EvalSymlinks re-validation is dropped, and the kernel's DAC is the boundary. The allowlist is capped. A home directory that cleans to "/" or is empty would prefix-match every absolute path, and such an entry is dropped instead. Paths at or beyond the sun_path capacity reject lexically rather than dying at bind or dial with a generic EINVAL. - unix -R, streamlocal-forward: the listener is created by a user-cred child with umask-at-bind 0600 and unlink-if-owned. Closing it does not unlink the socket, and the stale file on cancel is accepted. - TCP -R, tcpip-forward: a tailssh-owned handler replaces gliderssh's ForwardedTCPHandler. The bind goes through the monitor's listen op with the local user's credentials, so privileged ports fail by kernel construction for non-root-mapped users. Root-mapped users are allowed, as in OpenSSH. Bind addresses are loopback-only unless TS_SSH_FORWARD_GATEWAY_PORTS is set, the equivalent of sshd's GatewayPorts. - agent forwarding: the socket and its containing directory are created by a user-cred child, a 0600 socket in a 0700 user-owned directory, instead of a root-run MkdirTemp, Chmod, and Chown sequence. Session-end cleanup is unchanged. The monitor is spawned lazily on the first forwarding or agent need, from the tailscaled binary, and closed when the SSH connection ends. closeFwdMonitor latches a closed flag under the fwd lock, so a caller racing the teardown is refused by fwdMonitor, or reads the current state without spawning through fwdMonitorIfAny, instead of respawning a monitor nobody ever closes. plan9 keeps today's behavior through a build-tagged seam, fwdmonitor.go and fwdplan9.go. There is no monitor on plan9. Unix forwarding is rejected there, and reverse TCP forwarding keeps the gliderssh handler with the mayReversePortForwardTo gate. Tests cover conn-level callbacks against a real monitor and real one-shot fwd children: allowlist rejections, user-owned 0600 sockets, a foreign sticky-dir socket not unlinked, loopback, gateway-ports, and privileged-port TCP binds, agent directory hygiene and cleanup, and TS_SSH_DISABLE_FORWARDING coverage, plus refused respawn after teardown. The unix-fwd root-dial regressions cover a static in-allowlist symlink to a root-owned 0600 canary, which must fail permission denied as the bound user, and a dir-swap race, which must never serve the protected canary. Updates tailscale/corp#50380 Signed-off-by: James Tucker --- ssh/tailssh/fwdchild.go | 40 +- ssh/tailssh/fwdmonitor.go | 536 +++++++ ssh/tailssh/fwdmonitor_test.go | 1269 +++++++++++++++++ ssh/tailssh/fwdplan9.go | 120 ++ ssh/tailssh/monitor.go | 55 +- ssh/tailssh/monitor_client.go | 13 + ssh/tailssh/monitor_rpc.go | 17 + ssh/tailssh/monitor_test.go | 2 + ssh/tailssh/process_unix.go | 61 +- ssh/tailssh/process_unix_test.go | 123 +- ssh/tailssh/tailssh.go | 56 +- .../tailssh_integration_exitcodes_test.go | 9 + ssh/tailssh/tailssh_integration_test.go | 26 +- 13 files changed, 2217 insertions(+), 110 deletions(-) create mode 100644 ssh/tailssh/fwdmonitor.go create mode 100644 ssh/tailssh/fwdmonitor_test.go create mode 100644 ssh/tailssh/fwdplan9.go diff --git a/ssh/tailssh/fwdchild.go b/ssh/tailssh/fwdchild.go index 8c2ad1536..38089de0b 100644 --- a/ssh/tailssh/fwdchild.go +++ b/ssh/tailssh/fwdchild.go @@ -19,6 +19,14 @@ // err the op failed, with the reason preserved in // the reply // +// After a successful send the child holds its descriptor copy and stays +// alive until the monitor closes the result channel, its receipt +// acknowledgment, and only then closes the descriptor and exits. On +// darwin the kernel's unix-socket GC reclaims a socket whose only +// reference is an in-flight SCM_RIGHTS message, so the sender's copy +// must cover the handoff until the receiver owns the descriptor; see +// beFwdChild and the monitor_rpc.go header. +// // The monitor side of the protocol, fwdSpawnChild and fwdReadResult // below, drives these children. The op handlers live in monitor.go. @@ -48,6 +56,20 @@ import ( // agent dir is created before the umask change, so it keeps 0700. const fwdUmask = 0o177 +// fwdResultAckWait bounds the child's wait for the monitor's receipt +// acknowledgment after sending its result descriptor. The monitor +// closes the result channel immediately after taking ownership, so the +// wait normally ends at once; the deadline only covers a monitor that +// died without closing. +const fwdResultAckWait = 30 * time.Second + +// agentDirRoot is the only parent an agent-forwarding directory is +// created under. The child runs with no environment, so os.TempDir +// cannot redirect it, and it names the parent explicitly anyway; +// tailscaled's removal pins the same root. See removeAgentForwardingDir +// and checkAgentSocketPath. +const agentDirRoot = "/tmp" + // fwdMaxStatus caps the child's status line. Anything longer is a broken // child, not a long error message. const fwdMaxStatus = 4096 @@ -292,8 +314,20 @@ func beFwdChild(args []string) error { f.Close() return fmt.Errorf("ssh-fwd: sending result: %w", err) } - // Close our dup. The kernel holds its own reference from the sendmsg, - // so the monitor's copy survives. + // Hold the descriptor, and this process, until the monitor has + // received the relayed socket. On darwin, a socket whose only + // reference is an in-flight SCM_RIGHTS message is reclaimed by the + // kernel's unix-socket garbage collector before the receiver's + // recvmsg: the receive side is flushed and buffered data discarded, + // while recvmsg still returns a usable-looking descriptor that then + // reads EOF with its peer alive. The monitor closes its end of the + // result channel right after taking ownership of the descriptor, so + // the EOF here is the receipt acknowledgment. The deadline bounds + // the wait against a monitor that died without closing; the + // monitor's teardown SIGHUP also ends this process. + c.SetReadDeadline(time.Now().Add(fwdResultAckWait)) + var ack [1]byte + c.Read(ack[:]) // EOF on receipt, or deadline: exit either way f.Close() return nil } @@ -335,7 +369,7 @@ func fwdChildWork(fa fwdArgs) (*os.File, string, error) { case fa.op == "listen" && fa.agent: // Agent-forwarding socket. See fwdUmask and ListenAgent. The // dir's cleanup is the caller's. - dir, err := os.MkdirTemp("", "auth-agent") + dir, err := os.MkdirTemp(agentDirRoot, "auth-agent") if err != nil { return nil, "", err } diff --git a/ssh/tailssh/fwdmonitor.go b/ssh/tailssh/fwdmonitor.go new file mode 100644 index 000000000..da22dba6d --- /dev/null +++ b/ssh/tailssh/fwdmonitor.go @@ -0,0 +1,536 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build (linux && !android) || (darwin && !ios) || freebsd || openbsd + +// The monitor-backed forwarding paths. On unix, all forwarded sockets are +// dialed and bound by one-shot children of the per-connection ssh-monitor +// running with the authenticated local user's credentials. +// +// - unix -L, direct-streamlocal: the lexical allowlist check stays in +// tailscaled as coarse policy, then the dial runs as the user. See +// conn.fwdAllowedSocketPath for the path policy. +// - unix -R, streamlocal-forward: the listener child binds with +// umask-at-bind and unlink-if-owned semantics. The socket is 0600 and +// user-owned from the moment it exists. +// - TCP -R, tcpip-forward: the bind goes through the monitor's listen +// op, run by a user-cred listener child. Privileged ports fail with +// EACCES for non-root-mapped users. Bind addresses are +// loopback-only unless TS_SSH_FORWARD_GATEWAY_PORTS is set. +// - agent forwarding: the socket and its containing directory are +// created by a user-cred child. The socket is 0600 in a 0700 +// user-owned directory. +// + +package tailssh + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "syscall" + + "golang.org/x/sys/unix" + + "tailscale.com/types/logger" + + gliderssh "github.com/tailscale/gliderssh" + 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 +// spawn to the conn's localUser, with the uid, gid, and groups from +// clientAuth. +type fwdState struct { + mu sync.Mutex + mon *monitorClient + + // 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. + closed bool +} + +// fwdMonitor returns the conn's monitor, spawning it on first use with +// the spawn-bound identity documented on fwdState. +func (c *conn) fwdMonitor() (*monitorClient, error) { + c.fwd.mu.Lock() + defer c.fwd.mu.Unlock() + if c.fwd.mon != nil { + return c.fwd.mon, nil + } + if c.fwd.closed { + return nil, errors.New("monitor closed at connection teardown") + } + uid, gid, groups, err := c.fwdCreds() + if err != nil { + return nil, err + } + // The monitor is exec'd from the tailscaled binary; in tests + // os.Executable() is the test binary. The incubator spawn takes the + // same path from srv.tailscaledPath. + exe := c.srv.tailscaledPath + if exe == "" { + exe, err = os.Executable() + if err != nil { + return nil, fmt.Errorf("ssh-monitor: executable: %w", err) + } + } + 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) + } + 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. +func (c *conn) fwdMonitorIfAny() *monitorClient { + c.fwd.mu.Lock() + defer c.fwd.mu.Unlock() + return c.fwd.mon +} + +// fwdCreds returns the monitor's spawn identity, parsing like the +// incubator's argv does. The ids are carried at their 32-bit ABI width. +func (c *conn) fwdCreds() (uid, gid uint32, groups []uint32, err error) { + u64, err := strconv.ParseUint(c.localUser.Uid, 10, 32) + if err != nil { + return 0, 0, nil, fmt.Errorf("forwarding: parsing local user uid %q: %w", c.localUser.Uid, err) + } + g64, err := strconv.ParseUint(c.localUser.Gid, 10, 32) + if err != nil { + return 0, 0, nil, fmt.Errorf("forwarding: parsing local user gid %q: %w", c.localUser.Gid, err) + } + for _, g := range c.userGroupIDs { + v, err := strconv.ParseUint(g, 10, 32) + if err != nil { + return 0, 0, nil, fmt.Errorf("forwarding: parsing local user group %q: %w", g, err) + } + groups = append(groups, uint32(v)) + } + return uint32(u64), uint32(g64), groups, nil +} + +// closeFwdMonitor closes the conn's monitor, if one was spawned. It +// runs from HandleSSHConn's defer after the SSH connection is done. +// Closing the RPC channel triggers the monitor's teardown in monitor.go. +// Closing a second time is a no-op. +func (c *conn) closeFwdMonitor() { + c.fwd.mu.Lock() + mc := c.fwd.mon + c.fwd.mon = nil + c.fwd.closed = true + c.fwd.mu.Unlock() + if mc == nil { + return + } + if err := mc.Close(); err != nil { + c.logf("ssh: closing forwarding monitor: %v", err) + } +} + +// fwdMaxSunPathLen is the sun_path capacity. It is the lexical length +// cap on unix socket paths, the same one gliderssh's path validator +// enforced. The cap is 108 on Linux and 104 on macOS. +var fwdMaxSunPathLen = len(unix.RawSockaddrUnix{}.Path) + +// fwdAllowedSocketPath applies the lexical socket-path allowlist and +// returns the cleaned path to dial or bind. The allowlist is the same one +// gliderssh's UnixForwardingOptions enforced: the user's home directory, +// /tmp, and /run/user/. Relative paths and abstract socket names +// (a leading "@") are rejected. +func (c *conn) fwdAllowedSocketPath(socketPath string) (string, error) { + if !filepath.IsAbs(socketPath) || strings.HasPrefix(socketPath, "@") || strings.ContainsRune(socketPath, 0) { + return "", fmt.Errorf("socket path %q must be an absolute filesystem path: %w", socketPath, gliderssh.ErrRejected) + } + cleaned := filepath.Clean(socketPath) + // The sun_path length cap rejects over-long paths lexically, per + // fwdMaxSunPathLen. + if len(cleaned) >= fwdMaxSunPathLen { + return "", fmt.Errorf("socket path too long (%d >= %d): %w", len(cleaned), fwdMaxSunPathLen, gliderssh.ErrRejected) + } + for _, dir := range []string{c.localUser.HomeDir, "/tmp", filepath.Join("/run/user", c.localUser.Uid)} { + prefix := filepath.Clean(dir) + if dir == "" || prefix == string(filepath.Separator) { + // A home dir of "/" cleans to the separator itself, whose prefix + // matches every absolute path and collapses the coarse + // allowlist to "any absolute path". Drop the entry. + continue + } + if !strings.HasSuffix(prefix, string(filepath.Separator)) { + prefix += string(filepath.Separator) + } + if strings.HasPrefix(cleaned, prefix) { + return cleaned, nil + } + } + return "", fmt.Errorf("socket path %q is not in an allowed directory: %w", cleaned, gliderssh.ErrRejected) +} + +// fwdDialUnix is the unix -L path (direct-streamlocal): dial socketPath +// through a one-shot child with the local user's credentials. +func (c *conn) fwdDialUnix(ctx gliderssh.Context, socketPath string) (net.Conn, error) { + path, err := c.fwdAllowedSocketPath(socketPath) + if err != nil { + return nil, err + } + mc, err := c.fwdMonitor() + if err != nil { + return nil, err + } + uc, err := mc.Dial(ctx, path) + if err != nil { + return nil, fmt.Errorf("dial unix socket %q: %w", path, err) + } + return uc, nil +} + +// fwdListenUnix is the unix -R path, streamlocal-forward. It listens at +// socketPath through a one-shot child with the local user's credentials, +// umasking before the bind so the socket is created directly at 0600 +// user-owned, and unlinking an existing socket only when the session uid +// owns it. Closing the returned listener does not unlink the socket +// file; a canceled forward may leave a stale socket that the next bind's +// unlink-if-owned reclaims. +func (c *conn) fwdListenUnix(ctx gliderssh.Context, socketPath string) (net.Listener, error) { + path, err := c.fwdAllowedSocketPath(socketPath) + if err != nil { + return nil, err + } + mc, err := c.fwdMonitor() + if err != nil { + return nil, err + } + return mc.Listen(ctx, "unix", path, true) // unlink: if-owned +} + +// fwdListenAgent returns the agent-forwarding listener and socket path, +// both created by a child with the local user's credentials: a 0700 +// user-owned temp dir and, inside it, a 0600 user-owned socket. Removing +// the directory is the caller's job at session end. lu is the session's +// local user, unused on unix. +func (c *conn) fwdListenAgent(ctx gliderssh.Context, lu *userMeta) (net.Listener, string, error) { + _ = lu + mc, err := c.fwdMonitor() + if err != nil { + return nil, "", err + } + return mc.ListenAgent(ctx) +} + +// fwdTCPHandler is tailssh's replacement for gliderssh's +// ForwardedTCPHandler, serving "tcpip-forward" and +// "cancel-tcpip-forward". The bind goes through the conn's monitor, so +// the listener is created by a child bound to the local user's +// credentials; privileged ports below 1024 fail with EACCES for +// non-root-mapped users. Bind addresses are loopback-only unless +// sshForwardGatewayPorts is set. +type fwdTCPHandler struct { + conn *conn + + mu sync.Mutex + forwards map[string]net.Listener +} + +// The remote-forward request and channel payloads of RFC 4254 §7. +type fwdRemoteForwardRequest struct { + BindAddr string + BindPort uint32 +} + +type fwdRemoteForwardSuccess struct { + BindPort uint32 +} + +type fwdRemoteForwardCancelRequest struct { + BindAddr string + BindPort uint32 +} + +type fwdRemoteForwardChannelData struct { + DestAddr string + DestPort uint32 + OriginAddr string + OriginPort uint32 +} + +// fwdLoopbackBindAddr reports the bind address to use for a reverse TCP +// forward and whether the requested one is permitted. Only loopback is +// allowed, 127.0.0.0/8 and ::1, unless TS_SSH_FORWARD_GATEWAY_PORTS is +// set. An empty address binds 127.0.0.1. The listener resolves +// "localhost". +func fwdLoopbackBindAddr(bindAddr string) (string, bool) { + if sshForwardGatewayPorts() { + return bindAddr, true + } + switch bindAddr { + case "": + // ssh(1) documents -R without an address as binding loopback. Bind + // it explicitly so the listener is unambiguous. + return "127.0.0.1", true + case "localhost": + return bindAddr, true + } + if ip := net.ParseIP(bindAddr); ip != nil && ip.IsLoopback() { + return bindAddr, true + } + return "", false +} + +// HandleSSHRequest serves tcpip-forward and cancel-tcpip-forward. The +// bind-address policy and the monitor bind live here. +func (h *fwdTCPHandler) HandleSSHRequest(ctx gliderssh.Context, _ *gliderssh.Server, req *gossh.Request) (bool, []byte) { + h.mu.Lock() + if h.forwards == nil { + h.forwards = make(map[string]net.Listener) + } + h.mu.Unlock() + sshConn, ok := ctx.Value(gliderssh.ContextKeyConn).(gossh.Conn) + if !ok { + return false, nil + } + switch req.Type { + case "tcpip-forward": + var reqPayload fwdRemoteForwardRequest + if err := gossh.Unmarshal(req.Payload, &reqPayload); err != nil { + return false, nil + } + if !h.conn.mayReversePortForwardTo(ctx, reqPayload.BindAddr, reqPayload.BindPort) { + return false, []byte("port forwarding is disabled") + } + bindAddr, ok := fwdLoopbackBindAddr(reqPayload.BindAddr) + if !ok { + return false, []byte("binding to non-loopback addresses is not permitted") + } + mc, err := h.conn.fwdMonitor() + if err != nil { + h.conn.logf("ssh: reverse port forward: %v", err) + return false, []byte{} + } + ln, err := mc.Listen(ctx, "tcp", net.JoinHostPort(bindAddr, strconv.Itoa(int(reqPayload.BindPort))), false) + if err != nil { + // A privileged port under a non-root bound identity fails the + // bind with EACCES. + h.conn.logf("ssh: reverse port forward bind %s:%d: %v", reqPayload.BindAddr, reqPayload.BindPort, err) + return false, []byte{} + } + + // If the bind port was 0, use the actual port in the forwards map. + destPort := reqPayload.BindPort + if tl, ok := ln.Addr().(*net.TCPAddr); ok { + destPort = uint32(tl.Port) + } + addr := net.JoinHostPort(reqPayload.BindAddr, strconv.Itoa(int(destPort))) + h.mu.Lock() + h.forwards[addr] = ln + h.mu.Unlock() + go func() { + <-ctx.Done() + h.mu.Lock() + fln, ok := h.forwards[addr] + h.mu.Unlock() + if ok { + fln.Close() + } + }() + go func() { + defer func() { + h.mu.Lock() + if h.forwards[addr] == ln { + delete(h.forwards, addr) + } + h.mu.Unlock() + ln.Close() + }() + for { + nc, err := ln.Accept() + if err != nil { + return + } + originAddr, originPortStr, _ := net.SplitHostPort(nc.RemoteAddr().String()) + originPort, _ := strconv.ParseUint(originPortStr, 10, 16) + payload := gossh.Marshal(&fwdRemoteForwardChannelData{ + DestAddr: reqPayload.BindAddr, + DestPort: destPort, + OriginAddr: originAddr, + OriginPort: uint32(originPort), + }) + go func() { + ch, reqs, err := sshConn.OpenChannel("forwarded-tcpip", payload) + if err != nil { + nc.Close() + return + } + go gossh.DiscardRequests(reqs) + fwdBicopy(ctx, ch, nc) + }() + } + }() + return true, gossh.Marshal(&fwdRemoteForwardSuccess{destPort}) + + case "cancel-tcpip-forward": + var reqPayload fwdRemoteForwardCancelRequest + if err := gossh.Unmarshal(req.Payload, &reqPayload); err != nil { + return false, nil + } + addr := net.JoinHostPort(reqPayload.BindAddr, strconv.Itoa(int(reqPayload.BindPort))) + h.mu.Lock() + ln, ok := h.forwards[addr] + if ok { + delete(h.forwards, addr) + } + h.mu.Unlock() + if ok { + ln.Close() + } + return true, nil + + default: + return false, nil + } +} + +// fwdBicopy copies data bidirectionally between c1 and c2 until both +// directions complete or the context is canceled, half-closing the write +// side of each destination on EOF (RFC 4254 §5.3). +func fwdBicopy(ctx context.Context, c1, c2 io.ReadWriteCloser) { + defer c1.Close() + defer c2.Close() + + var wg sync.WaitGroup + wg.Go(func() { + defer fwdHalfCloseWrite(c1) + _, _ = io.Copy(c1, c2) + }) + wg.Go(func() { + defer fwdHalfCloseWrite(c2) + _, _ = io.Copy(c2, c1) + }) + + done := make(chan struct{}) + go func() { + wg.Wait() + close(done) + }() + select { + case <-done: + return + case <-ctx.Done(): + c1.Close() + c2.Close() + <-done + } +} + +// fwdHalfCloseWrite signals EOF on the write side of c if c supports +// CloseWrite, as *net.TCPConn, *net.UnixConn, and gossh.Channel do. +// Otherwise the deferred full Close in fwdBicopy handles cleanup. +func fwdHalfCloseWrite(c io.ReadWriteCloser) { + type closeWriter interface { + CloseWrite() error + } + if cw, ok := c.(closeWriter); ok { + _ = cw.CloseWrite() + } +} + +// wireReverseForwarding installs the conn's reverse TCP forwarding +// request handlers. On unix they are fwdTCPHandler's, binding through +// the monitor. +func (c *conn) wireReverseForwarding(ss *gliderssh.Server) { + h := &fwdTCPHandler{conn: c} + ss.RequestHandlers["tcpip-forward"] = h.HandleSSHRequest + ss.RequestHandlers["cancel-tcpip-forward"] = h.HandleSSHRequest +} + +// removeAgentForwardingDir removes the agent-forwarding directory dir at +// session end. The removal runs with the daemon's credentials while dir +// and everything in it belong to the connection's user, so a hostile +// user must not steer it. It is refused unless dir is still a directory +// directly under agentDirRoot, and agentDirRoot is itself root-owned, so +// no component of the path can be swapped for a symlink by the session +// user. The removal is resolved relative to a pinned handle on +// agentDirRoot, which follows no symlinks in the name or below it. If +// the checked directory was swapped for a user-owned one between the +// check and the removal, what is removed is still only a user-owned +// entry in agentDirRoot, which the user can remove itself. Failures are +// logged, never fatal: a leftover temp dir is the fallback. +func removeAgentForwardingDir(dir string, lu *userMeta, logf logger.Logf) { + if filepath.Dir(dir) != agentDirRoot || !strings.HasPrefix(filepath.Base(dir), "auth-agent") { + logf("ssh: refusing to remove agent forwarding dir %s: not an auth-agent directory directly inside %s", dir, agentDirRoot) + return + } + fi, err := os.Stat(agentDirRoot) + if err != nil { + logf("ssh: agent forwarding dir root %s: %v", agentDirRoot, err) + return + } + st, ok := fi.Sys().(*syscall.Stat_t) + if !ok { + logf("ssh: refusing to remove agent forwarding dir %s: %s owner not available", dir, agentDirRoot) + return + } + if st.Uid != 0 { + logf("ssh: refusing to remove agent forwarding dir %s: %s is not root-owned", dir, agentDirRoot) + return + } + r, err := os.OpenRoot(agentDirRoot) + if err != nil { + logf("ssh: agent forwarding dir root %s: %v", agentDirRoot, err) + return + } + defer r.Close() + name := filepath.Base(dir) + fi, err = r.Lstat(name) + if err != nil { + if !os.IsNotExist(err) { + logf("ssh: agent forwarding dir %s: %v", dir, err) + } + return + } + if err := checkAgentDirRemovable(fi, lu); err != nil { + logf("ssh: refusing to remove agent forwarding dir %s: %v", dir, err) + return + } + if err := r.RemoveAll(name); err != nil { + logf("ssh: removing agent forwarding dir: %v", err) + } +} + +// checkAgentDirRemovable verifies one agent-forwarding directory before +// its root-run removal: a directory (never a symlink), owned by the +// connection's user, with no group or other permission bits — the shape +// MkdirTemp leaves behind. +func checkAgentDirRemovable(fi os.FileInfo, lu *userMeta) error { + if !fi.Mode().IsDir() { + return errors.New("agent forwarding dir is not a directory") + } + uid, err := strconv.ParseUint(lu.Uid, 10, 32) + if err != nil { + return fmt.Errorf("agent forwarding dir: parsing bound uid %q: %w", lu.Uid, err) + } + st, ok := fi.Sys().(*syscall.Stat_t) + if !ok { + return errors.New("agent forwarding dir: owner not available") + } + if st.Uid != uint32(uid) { + return fmt.Errorf("agent forwarding dir owned by uid %d, want %d", st.Uid, uid) + } + if fi.Mode().Perm()&0o077 != 0 { + return fmt.Errorf("agent forwarding dir mode %04o is group- or other-accessible", fi.Mode().Perm()) + } + return nil +} diff --git a/ssh/tailssh/fwdmonitor_test.go b/ssh/tailssh/fwdmonitor_test.go new file mode 100644 index 000000000..97138cdac --- /dev/null +++ b/ssh/tailssh/fwdmonitor_test.go @@ -0,0 +1,1269 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build (linux && !android) || (darwin && !ios) || freebsd || openbsd + +// Conn-level tests for the monitor-backed forwarding paths: unix -L, +// unix -R, TCP -R, and agent forwarding. The tested entry points are +// mayForwardLocalUnixTo, mayReverseUnixForwardTo, fwdTCPHandler, and +// handleSSHAgentForwarding. The forwarding-path tests drive a real conn +// with a real monitor and real one-shot fwd children through the +// self-exec seams in fwdchild_test.go. TestFwdAllowedSocketPathCaps and +// TestFwdMonitorClosedRefusesRespawn exercise the lexical policy and +// the closed flag directly. Under root the conn binds to the non-root +// test user, so the cross-uid closures are pinned: socket ownership, +// permission-denied dials, and kernel privileged-port refusal. Non-root +// runs bind to the current user. + +package tailssh + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net" + "net/netip" + "os" + "os/user" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync" + "sync/atomic" + "syscall" + "testing" + "time" + + gliderssh "github.com/tailscale/gliderssh" + gossh "golang.org/x/crypto/ssh" + "tailscale.com/envknob" + "tailscale.com/net/memnet" + "tailscale.com/tailcfg" + testssh "tailscale.com/tempfork/sshtest/ssh" +) + +// fwdTestIdentity returns the local user the conn binds its monitor to. +// Under root it is the non-root test user, so sockets created by the +// forwarding children are owned by the session user. Otherwise it is the +// current user, where a non-root tailscaled binds the monitor to itself. +func fwdTestIdentity(t *testing.T) *userMeta { + t.Helper() + if os.Getuid() == 0 { + uid, gid := ensureFwdTestUser(t) + return &userMeta{User: user.User{ + Username: fwdTestUser, + Uid: strconv.Itoa(uid), + Gid: strconv.Itoa(gid), + HomeDir: "/nonexistent", // no home needed. Tests use /tmp paths. + }} + } + u, err := user.Current() + if err != nil { + t.Fatalf("user.Current: %v", err) + } + return &userMeta{User: *u} +} + +// newFwdTestConn returns a conn whose forwarding paths go through a real +// monitor (spawned lazily on first use), bound to lu's identity, with the +// given final action. It registers the monitor self-exec seams and closes +// the monitor on cleanup. +func newFwdTestConn(t *testing.T, lu *userMeta, final *tailcfg.SSHAction) *conn { + t.Helper() + exe := makeExecutableReachable(t) + // The override must reach the monitor process, which spawns the fwd + // children. It therefore travels through the environment. + t.Setenv("TS_TEST_SSH_FWD_PREFIX", strings.Join(testFwdPrefix, " ")) + old := monitorSpawnPrefix + monitorSpawnPrefix = testMonitorPrefix + t.Cleanup(func() { monitorSpawnPrefix = old }) + + groups := []string{} + if g, err := os.Getgroups(); err == nil { + for _, v := range g { + groups = append(groups, strconv.Itoa(v)) + } + } else { + t.Fatalf("os.Getgroups: %v", err) + } + c := &conn{ + // t.Logf so bind/spawn failures are visible in test output. + // tailscaledPath is the reachable copy of the test binary: the + // monitor exec'd from it spawns the fwd children from the same + // path, and under a root run the bound user can exec the copy + // but not the original. + srv: &server{logf: t.Logf, tailscaledPath: exe}, + localUser: lu, + userGroupIDs: groups, + finalAction: final, + } + t.Cleanup(c.closeFwdMonitor) + return c +} + +// fwdTestCtx returns a gliderssh.Context for driving the conn callbacks and +// handlers directly, whose ContextKeyConn value is sshConn and which is +// canceled by the returned cancel func. Every other Value lookup returns +// true, matching process_unix_test.go's agentFwdContext. +func fwdTestCtx(sshConn gossh.Conn) (gliderssh.Context, context.CancelFunc) { + ctx, cancel := context.WithCancel(context.Background()) + return fwdTestContext{Context: ctx, Mutex: &sync.Mutex{}, conn: sshConn}, cancel +} + +// fwdTestContext implements gliderssh.Context. Value serves ContextKeyConn +// and returns true otherwise. Everything else is inert. The embedded mutex +// satisfies the interface's Locker requirement, like process_unix_test.go's +// agentFwdContext. +type fwdTestContext struct { + context.Context + *sync.Mutex + conn gossh.Conn +} + +func (c fwdTestContext) Value(key any) any { + if key == gliderssh.ContextKeyConn { + return c.conn + } + return true +} +func (fwdTestContext) User() string { return "test" } +func (fwdTestContext) SessionID() string { return "test" } +func (fwdTestContext) ClientVersion() string { return "2.0" } +func (fwdTestContext) ServerVersion() string { return "2.0" } +func (fwdTestContext) RemoteAddr() net.Addr { return nil } +func (fwdTestContext) LocalAddr() net.Addr { return nil } +func (fwdTestContext) Permissions() *gliderssh.Permissions { return nil } +func (fwdTestContext) SetValue(key, value any) {} + +// fwdTestSSHConn is a gossh.ServerConn stub for the TCP -R handler. +// OpenChannel returns an echo channel. What the client writes through the +// forwarded TCP connection comes back, so bicopy is exercised end to end. +type fwdTestSSHConn struct{ gossh.Conn } + +// OpenChannel returns an echo channel so the accept loop and bicopy are +// exercised end to end. The handler type-asserts the ContextKeyConn value +// to gossh.Conn. A real server hands it a *gossh.ServerConn. +func (fwdTestSSHConn) OpenChannel(name string, data []byte) (gossh.Channel, <-chan *gossh.Request, error) { + if name != "forwarded-tcpip" { + return nil, nil, fmt.Errorf("unexpected channel type %q", name) + } + return newEchoChannel(), nil, nil +} + +// echoChannel is a gossh.Channel that echoes its Write payload back out of +// Read. bicopy(ch, nc) then makes the TCP peer see its own writes. +type echoChannel struct { + buf chan []byte + closed chan struct{} + closeMu sync.Mutex +} + +func newEchoChannel() *echoChannel { + return &echoChannel{buf: make(chan []byte, 16), closed: make(chan struct{})} +} + +func (e *echoChannel) Read(p []byte) (int, error) { + select { + case b := <-e.buf: + return copy(p, b), nil + case <-e.closed: + return 0, io.EOF + } +} + +func (e *echoChannel) Write(p []byte) (int, error) { + select { + case e.buf <- bytes.Clone(p): + return len(p), nil + case <-e.closed: + return 0, errors.New("channel closed") + } +} + +func (e *echoChannel) Close() error { + e.closeMu.Lock() + defer e.closeMu.Unlock() + select { + case <-e.closed: + default: + close(e.closed) + } + return nil +} + +func (e *echoChannel) CloseWrite() error { return nil } +func (e *echoChannel) SendRequest(string, bool, []byte) (bool, error) { + return false, nil +} +func (e *echoChannel) Stderr() io.ReadWriter { return e } + +// fwdTmpDir creates a directory under /tmp, inside the socket-path +// allowlist, that the monitor's bound identity can use. Root runs create +// it as root and chmod it 0777 for the non-root bound user. +func fwdTmpDir(t *testing.T) string { + t.Helper() + dir, err := os.MkdirTemp("/tmp", "tailssh-fwd-test-") + if err != nil { + t.Fatal(err) + } + if err := os.Chmod(dir, 0o777); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + return dir +} + +// statOwnerMode returns the owner uid and permission bits of path. +func statOwnerMode(t *testing.T, path string) (int, os.FileMode) { + t.Helper() + fi, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + st, ok := fi.Sys().(*syscall.Stat_t) + if !ok { + t.Fatalf("stat %q: unsupported syscall.Stat_t type %T", path, fi.Sys()) + } + return int(st.Uid), fi.Mode().Perm() +} + +// setDeadlineConn gives every blocking read/write in these tests a +// deadline so nothing can wedge the suite. +func setDeadlineConn(t *testing.T, c net.Conn) { + t.Helper() + dl := time.Now().Add(10 * time.Second) + if err := c.SetDeadline(dl); err != nil { + t.Fatal(err) + } +} + +// TestFwdConnLocalUnixDial drives mayForwardLocalUnixTo (unix -L) through +// a real monitor: a dial to an accessible socket in /tmp returns a live +// connection dialed as the bound identity, and paths outside the +// allowlist (or relative/abstract) are rejected. +func TestFwdConnLocalUnixDial(t *testing.T) { + lu := fwdTestIdentity(t) + c := newFwdTestConn(t, lu, &tailcfg.SSHAction{ + Accept: true, + AllowLocalPortForwarding: true, + }) + + socketPath := filepath.Join(fwdTmpDir(t), "service.sock") + ln, err := net.Listen("unix", socketPath) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + // The test process owns the socket and may be root while the conn + // binds to the non-root test user, so make it connectable by the + // bound identity. TestFwdDialRoundTrip and TestFwdDialCrossUser pin + // the permission-denied direction; here we assert the conn-level path + // returns a live conn. + if err := os.Chmod(socketPath, 0o666); err != nil { + t.Fatal(err) + } + go func() { + for { + sc, err := ln.Accept() + if err != nil { + return + } + go func() { + defer sc.Close() + io.Copy(sc, sc) + }() + } + }() + + ctx, _ := fwdTestCtx(nil) + uc, err := c.mayForwardLocalUnixTo(ctx, socketPath) + if err != nil { + t.Fatalf("mayForwardLocalUnixTo(%q): %v", socketPath, err) + } + defer uc.Close() + setDeadlineConn(t, uc) + + want := "GET /_ping HTTP/1.1\r\n\r\n" + if _, err := uc.Write([]byte(want)); err != nil { + t.Fatalf("write through forwarded conn: %v", err) + } + got := make([]byte, len(want)) + if _, err := io.ReadFull(uc, got); err != nil { + t.Fatalf("read through forwarded conn: %v", err) + } + if string(got) != want { + t.Errorf("echo = %q; want %q", got, want) + } + + // Paths outside the allowed directories are rejected. + for _, bad := range []string{"/var/run/docker.sock", "/etc/evil.sock"} { + _, err := c.mayForwardLocalUnixTo(ctx, bad) + if err == nil { + t.Errorf("dial %q: unexpectedly allowed", bad) + continue + } + if !errors.Is(err, gliderssh.ErrRejected) || !strings.Contains(err.Error(), "not in an allowed directory") { + t.Errorf("dial %q error = %v; want an ErrRejected \"not in an allowed directory\"", bad, err) + } + } + // Relative and abstract paths are rejected. + for _, bad := range []string{"relative.sock", "@/tmp/abstract.sock"} { + _, err := c.mayForwardLocalUnixTo(ctx, bad) + if !errors.Is(err, gliderssh.ErrRejected) { + t.Errorf("dial %q error = %v; want ErrRejected", bad, err) + } + } +} + +// TestFwdConnReverseUnixListen drives mayReverseUnixForwardTo (unix -R): +// the returned listener's socket is 0600 and owned by the bound identity. +// Data flows through it, and a foreign-owned live socket in a sticky +// directory is not unlinked in the root run. +func TestFwdConnReverseUnixListen(t *testing.T) { + lu := fwdTestIdentity(t) + uid, _ := strconv.Atoi(lu.Uid) + c := newFwdTestConn(t, lu, &tailcfg.SSHAction{ + Accept: true, + AllowLocalPortForwarding: true, // for the dial-side half of the round trip + AllowRemotePortForwarding: true, + }) + + socketPath := filepath.Join(fwdTmpDir(t), "reverse.sock") + ctx, _ := fwdTestCtx(nil) + ln, err := c.mayReverseUnixForwardTo(ctx, socketPath) + if err != nil { + t.Fatalf("mayReverseUnixForwardTo(%q): %v", socketPath, err) + } + t.Cleanup(func() { ln.Close() }) + + // Socket created by the monitor's child: 0600, owned by the bound + // identity (the non-root test user under root runs). + gotUid, mode := statOwnerMode(t, socketPath) + if mode != 0o600 { + t.Errorf("socket mode = %o; want 0600", mode) + } + if gotUid != uid { + t.Errorf("socket uid = %d; want %d (the session user)", gotUid, uid) + } + + // Round trip: accept on the reverse listener, dial it through the + // conn's own -L path, which is self-consistent because the same user + // can reach its own 0600 socket. + go func() { + sc, err := ln.Accept() + if err != nil { + return + } + defer sc.Close() + io.Copy(sc, sc) + }() + uc, err := c.mayForwardLocalUnixTo(ctx, socketPath) + if err != nil { + t.Fatalf("dial reverse socket through -L path: %v", err) + } + defer uc.Close() + setDeadlineConn(t, uc) + want := "hello reverse" + if _, err := uc.Write([]byte(want)); err != nil { + t.Fatalf("write: %v", err) + } + got := make([]byte, len(want)) + if _, err := io.ReadFull(uc, got); err != nil { + t.Fatalf("read: %v", err) + } + if string(got) != want { + t.Errorf("echo = %q; want %q", got, want) + } + + // Root run: a foreign root-owned live socket in sticky /tmp is not + // unlinked by a bind from the non-root session user. The bind fails + // EADDRINUSE and the original socket still accepts. Subtest so the + // non-root round trip above passes on its own and this guard's skip + // cannot erase it. + t.Run("foreign-socket-not-unlinked", func(t *testing.T) { + if os.Getuid() != 0 { + t.Skipf("non-root run: bound identity is the current user, so the foreign-socket case is same-uid; TestFwdListenUnlinkIfOwned pins it at monitor level") + } + foreignPath := filepath.Join(fwdTmpDir(t), "foreign.sock") + foreignLn, err := net.Listen("unix", foreignPath) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { foreignLn.Close() }) + go func() { + for { + sc, err := foreignLn.Accept() + if err != nil { + return + } + sc.Close() + } + }() + if _, err := c.mayReverseUnixForwardTo(ctx, foreignPath); err == nil { + t.Fatal("bind over foreign-owned socket: unexpectedly allowed") + } else if !strings.Contains(err.Error(), "address already in use") { + t.Errorf("bind over foreign socket error = %v; want EADDRINUSE", err) + } + // The foreign socket was not unlinked and still accepts. + if _, _, err := statOwnerModeOK(foreignPath); err != nil { + t.Fatalf("foreign socket unlinked by refused bind: %v", err) + } + if _, err := net.Dial("unix", foreignPath); err != nil { + t.Errorf("foreign socket no longer accepts: %v", err) + } + }) +} + +func statOwnerModeOK(path string) (int, os.FileMode, error) { + fi, err := os.Stat(path) + if err != nil { + return 0, 0, err + } + st, ok := fi.Sys().(*syscall.Stat_t) + if !ok { + return 0, 0, fmt.Errorf("unsupported Stat_t %T", fi.Sys()) + } + return int(st.Uid), fi.Mode().Perm(), nil +} + +// TestFwdTCPHandler drives the tailssh-owned tcpip-forward handler: a +// loopback bind goes through the monitor's user-cred listener child and +// accepts with data echoing through the SSH channel stub. Non-loopback +// binds are rejected unless TS_SSH_FORWARD_GATEWAY_PORTS is set, and a +// privileged port is refused for a non-root bound identity. +func TestFwdTCPHandler(t *testing.T) { + lu := fwdTestIdentity(t) + c := newFwdTestConn(t, lu, &tailcfg.SSHAction{ + Accept: true, + AllowRemotePortForwarding: true, + }) + + ctx, cancel := fwdTestCtx(fwdTestSSHConn{}) + t.Cleanup(cancel) + h := &fwdTCPHandler{conn: c} + tcpReq := func(addr string, port uint32) *gossh.Request { + return &gossh.Request{ + Type: "tcpip-forward", + WantReply: true, + Payload: gossh.Marshal(fwdRemoteForwardRequest{BindAddr: addr, BindPort: port}), + } + } + + // 127.0.0.1:0 binds via the monitor's child and accepts. Data written + // by a local dialer echoes back through the SSH channel stub. + ok, payload := h.HandleSSHRequest(ctx, nil, tcpReq("127.0.0.1", 0)) + if !ok { + t.Fatalf("tcpip-forward 127.0.0.1:0 rejected: %s", payload) + } + var succ fwdRemoteForwardSuccess + if err := gossh.Unmarshal(payload, &succ); err != nil { + t.Fatal(err) + } + if succ.BindPort == 0 { + t.Fatal("reply carried no concrete port") + } + fwdAddr := net.JoinHostPort("127.0.0.1", strconv.Itoa(int(succ.BindPort))) + tc, err := net.DialTimeout("tcp", fwdAddr, 5*time.Second) + if err != nil { + t.Fatalf("dial forwarded listener %s: %v", fwdAddr, err) + } + defer tc.Close() + setDeadlineConn(t, tc) + want := "ping through reverse tcp forward" + if _, err := tc.Write([]byte(want)); err != nil { + t.Fatalf("write to forwarded listener: %v", err) + } + got := make([]byte, len(want)) + if _, err := io.ReadFull(tc, got); err != nil { + t.Fatalf("read from forwarded listener: %v", err) + } + if string(got) != want { + t.Errorf("echo = %q; want %q", got, want) + } + + // Canceling the request's context closes the listener through the + // conn's ctx-done goroutine. + cancel() + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + if conn, err := net.DialTimeout("tcp", fwdAddr, time.Second); err != nil { + break // listener closed + } else { + conn.Close() + time.Sleep(50 * time.Millisecond) + } + } + + // Non-loopback binds are rejected without the gateway-ports knob… + ctx2, cancel2 := fwdTestCtx(fwdTestSSHConn{}) + t.Cleanup(cancel2) + if ok, msg := h.HandleSSHRequest(ctx2, nil, tcpReq("0.0.0.0", 0)); ok { + t.Fatal("tcpip-forward 0.0.0.0:0 allowed without TS_SSH_FORWARD_GATEWAY_PORTS") + } else if !bytes.Contains(msg, []byte("non-loopback")) { + t.Errorf("rejection message = %q; want non-loopback notice", msg) + } + // …and allowed with it. The knob widens address policy only, and the + // bind still runs with the user's credentials. + envknob.SetenvForTest(t, "TS_SSH_FORWARD_GATEWAY_PORTS", "1") + if ok, msg := h.HandleSSHRequest(ctx2, nil, tcpReq("0.0.0.0", 0)); !ok { + t.Fatalf("tcpip-forward 0.0.0.0:0 rejected with TS_SSH_FORWARD_GATEWAY_PORTS: %s", msg) + } + cancel2() + + // Privileged ports fail at the kernel for the non-root bound + // identity, matching OpenSSH's rule that only root binds privileged + // ports. The port-80 refusal above pins that the bind runs as the + // bound user. Only where the kernel enforces the restriction: + // privileged CI containers often set ip_unprivileged_port_start to + // 0, which lets any uid bind any port, and darwin does not restrict + // the range at all. + if unprivilegedPrivilegedBinds() { + t.Log("skipping the privileged-port refusal: the kernel allows unprivileged privileged binds") + } else { + ctx3, cancel3 := fwdTestCtx(fwdTestSSHConn{}) + t.Cleanup(cancel3) + if ok, msg := h.HandleSSHRequest(ctx3, nil, tcpReq("127.0.0.1", 80)); ok { + t.Fatalf("tcpip-forward 127.0.0.1:80 allowed for non-root bound identity %q", lu.Username) + } else { + t.Logf("privileged bind rejected: %s", msg) + } + cancel3() + } +} + +// TestFwdTCPHandlerPolicyGate pins the handler's policy gates: the final +// action's AllowRemotePortForwarding and TS_SSH_DISABLE_FORWARDING. +func TestFwdTCPHandlerPolicyGate(t *testing.T) { + lu := fwdTestIdentity(t) + denied := newFwdTestConn(t, lu, &tailcfg.SSHAction{ + Accept: true, + AllowRemotePortForwarding: false, + }) + ctx, cancel := fwdTestCtx(fwdTestSSHConn{}) + t.Cleanup(cancel) + h := &fwdTCPHandler{conn: denied} + req := &gossh.Request{ + Type: "tcpip-forward", + WantReply: true, + Payload: gossh.Marshal(fwdRemoteForwardRequest{BindAddr: "127.0.0.1", BindPort: 0}), + } + if ok, msg := h.HandleSSHRequest(ctx, nil, req); ok { + t.Fatal("tcpip-forward allowed without AllowRemotePortForwarding") + } else if !bytes.Contains(msg, []byte("port forwarding is disabled")) { + t.Errorf("rejection message = %q", msg) + } + + envknob.SetenvForTest(t, "TS_SSH_DISABLE_FORWARDING", "1") + if ok, msg := h.HandleSSHRequest(ctx, nil, req); ok { + t.Fatal("tcpip-forward allowed with TS_SSH_DISABLE_FORWARDING") + } else if !bytes.Contains(msg, []byte("port forwarding is disabled")) { + t.Errorf("rejection message = %q", msg) + } + cancel() +} + +// TestFwdDisableForwarding pins that TS_SSH_DISABLE_FORWARDING rejects all +// four forwarding paths. +func TestFwdDisableForwarding(t *testing.T) { + envknob.SetenvForTest(t, "TS_SSH_DISABLE_FORWARDING", "1") + lu := fwdTestIdentity(t) + c := newFwdTestConn(t, lu, &tailcfg.SSHAction{ + Accept: true, + AllowLocalPortForwarding: true, + AllowRemotePortForwarding: true, + AllowAgentForwarding: true, + }) + ctx, cancel := fwdTestCtx(fwdTestSSHConn{}) + t.Cleanup(cancel) + + if _, err := c.mayForwardLocalUnixTo(ctx, "/tmp/anything.sock"); !errors.Is(err, gliderssh.ErrRejected) { + t.Errorf("unix -L error = %v; want ErrRejected", err) + } + if _, err := c.mayReverseUnixForwardTo(ctx, "/tmp/anything.sock"); !errors.Is(err, gliderssh.ErrRejected) { + t.Errorf("unix -R error = %v; want ErrRejected", err) + } + h := &fwdTCPHandler{conn: c} + req := &gossh.Request{ + Type: "tcpip-forward", + WantReply: true, + Payload: gossh.Marshal(fwdRemoteForwardRequest{BindAddr: "127.0.0.1", BindPort: 0}), + } + if ok, msg := h.HandleSSHRequest(ctx, nil, req); ok { + t.Error("TCP -R allowed with TS_SSH_DISABLE_FORWARDING") + } else if !bytes.Contains(msg, []byte("port forwarding is disabled")) { + t.Errorf("TCP -R rejection message = %q", msg) + } + // Agent forwarding silently does not start, as before. + ss, s := newAgentTestSession(t, c) + if err := ss.handleSSHAgentForwarding(s, lu); err != nil { + t.Errorf("handleSSHAgentForwarding: %v", err) + } + if ss.agentListener != nil { + t.Error("agent listener started with TS_SSH_DISABLE_FORWARDING") + } + cancel() +} + +// TestFwdFullStackLocalUnix is the full-stack -L test. A real SSH +// connection from an sshtest client over memnet reaches a real tailssh +// server with a real policy, with SSHUsers mapping alice to the bound +// user. The direct-streamlocal dial goes through the conn's lazily +// spawned real monitor and its one-shot fwd child. The service reads a +// fixed-length payload under a deadline, echoes it, and on linux reports +// the dialer's peer uid, which must be the monitor's bound uid. +func TestFwdFullStackLocalUnix(t *testing.T) { + lu := fwdTestIdentity(t) + boundUID, err := strconv.Atoi(lu.Uid) + if err != nil { + t.Fatalf("parse bound uid %q: %v", lu.Uid, err) + } + + // The monitor seam overrides must be in place before the conn lazily + // spawns its monitor on the -L dial. + exe := makeExecutableReachable(t) + t.Setenv("TS_TEST_SSH_FWD_PREFIX", strings.Join(testFwdPrefix, " ")) + old := monitorSpawnPrefix + monitorSpawnPrefix = testMonitorPrefix + t.Cleanup(func() { monitorSpawnPrefix = old }) + + // The service socket is in the allowlist's /tmp and is created by the + // test process, which may be root while the conn binds to the + // non-root test user, so it must be reachable by the bound identity. + socketPath := filepath.Join(fwdTmpDir(t), "svc.sock") + ln, err := net.Listen("unix", socketPath) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + if err := os.Chmod(socketPath, 0o666); err != nil { + t.Fatal(err) + } + + payload := []byte("GET /_ping HTTP/1.1\r\n\r\n") // fixed, known length + type serviceResult struct { + peerUID int + err error + } + svc := make(chan serviceResult, 1) + go func() { + sc, err := ln.Accept() + if err != nil { + svc <- serviceResult{err: err} + return + } + defer sc.Close() + if err := sc.SetDeadline(time.Now().Add(10 * time.Second)); err != nil { + svc <- serviceResult{err: err} + return + } + got := make([]byte, len(payload)) + if _, err := io.ReadFull(sc, got); err != nil { + svc <- serviceResult{err: fmt.Errorf("service read: %w", err)} + return + } + if !bytes.Equal(got, payload) { + svc <- serviceResult{err: fmt.Errorf("service got %q, want %q", got, payload)} + return + } + // The dialer is the monitor's fwd child, so its credentials are + // the conn's bound identity. peerCredUID is linux-only. + peerUID := -1 + if runtime.GOOS == "linux" { + peerUID, err = peerCredUID(sc) + if err != nil { + svc <- serviceResult{err: fmt.Errorf("service peer cred: %w", err)} + return + } + } + if _, err := sc.Write(payload); err != nil { + svc <- serviceResult{err: fmt.Errorf("service echo: %w", err)} + return + } + svc <- serviceResult{peerUID: peerUID} + }() + + // The server runs a real auth flow with alice mapped to the bound + // local user and -L forwarding allowed. + rule := &tailcfg.SSHRule{ + SSHUsers: map[string]string{"alice": lu.Username}, + Action: &tailcfg.SSHAction{Accept: true, AllowLocalPortForwarding: true}, + Principals: []*tailcfg.SSHPrincipal{ + {Any: true}, + }, + } + s := &server{ + logf: t.Logf, + tailscaledPath: exe, // the reachable copy; see makeExecutableReachable + lb: &localState{ + sshEnabled: true, + varRoot: t.TempDir(), + matchingRule: rule, + }, + } + + src, dst := netip.MustParseAddrPort("100.100.100.101:2231"), netip.MustParseAddrPort("100.100.100.102:22") + clientConn, serverConn := memnet.NewTCPConn(src, dst, 1024) + // Deadline on the client side of the memnet transport, so nothing can + // wedge the test waiting on a transport that stopped making progress. + if err := clientConn.SetDeadline(time.Now().Add(30 * time.Second)); err != nil { + t.Fatal(err) + } + + var wg sync.WaitGroup + wg.Go(func() { + cl, chans, reqs, err := testssh.NewClientConn(clientConn, clientConn.RemoteAddr().String(), &testssh.ClientConfig{ + User: "alice", + HostKeyCallback: testssh.InsecureIgnoreHostKey(), + Timeout: 15 * time.Second, + }) + if err != nil { + t.Errorf("client handshake: %v", err) + return + } + client := testssh.NewClient(cl, chans, reqs) + defer client.Close() + + uc, err := client.Dial("unix", socketPath) + if err != nil { + t.Errorf("client -L dial %q: %v", socketPath, err) + return + } + defer uc.Close() + // No deadline on the channel-backed conn because x/crypto channels + // do not support deadlines. The memnet transport deadline above + // and the fixed-length reads bound this side instead. + if _, err := uc.Write(payload); err != nil { + t.Errorf("write through forwarded conn: %v", err) + return + } + got := make([]byte, len(payload)) + if _, err := io.ReadFull(uc, got); err != nil { + t.Errorf("read through forwarded conn: %v", err) + return + } + if !bytes.Equal(got, payload) { + t.Errorf("echo = %q; want %q", got, payload) + } + }) + if err := s.HandleSSHConn(serverConn); err != nil { + t.Errorf("HandleSSHConn: %v", err) + } + wg.Wait() + + select { + case r := <-svc: + if r.err != nil { + t.Fatalf("service: %v", r.err) + } + if runtime.GOOS == "linux" && r.peerUID != boundUID { + t.Errorf("service observed peer uid %d; want %d (the conn's bound identity, not root tailscaled)", r.peerUID, boundUID) + } + case <-time.After(10 * time.Second): + t.Fatal("service never saw the forwarded connection") + } +} + +// fwdTestCtxTimeout is fwdTestCtx with a deadline. The race test's dial +// attempts each carry a short budget so nothing can wedge the loop. +func fwdTestCtxTimeout(timeout time.Duration) (gliderssh.Context, context.CancelFunc) { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + return fwdTestContext{Context: ctx, Mutex: &sync.Mutex{}, conn: nil}, cancel +} + +// canaryListener is a marker-emitting canary unix socket for the +// root-dial-TOCTOU regression tests. Every accepted connection is served +// exactly one marker write and closed. markers is buffered so the accept +// loop never blocks. The test drains it to assert which side ever got +// served. +type canaryListener struct { + ln *net.UnixListener + markers chan string + done chan struct{} // closed when the accept loop exits +} + +// listenCanary binds the canary socket at path with a umask-at-bind mode +// and starts its marker-emitting accept loop. See canaryListener for the +// markers channel semantics. The mode 0o600 comes from umask 0o177 and +// 0o666 from umask 0o111, so the socket is created directly at the +// requested mode. +func listenCanary(t *testing.T, path string, mode int, marker string) *canaryListener { + t.Helper() + old := syscall.Umask(0o777 &^ mode) + ln, err := net.Listen("unix", path) + syscall.Umask(old) + if err != nil { + t.Fatalf("listen canary %q: %v", path, err) + } + c := &canaryListener{ + ln: ln.(*net.UnixListener), + markers: make(chan string, 64), + done: make(chan struct{}), + } + go func() { + defer close(c.done) + for { + sc, err := ln.Accept() + if err != nil { + return + } + sc.(*net.UnixConn).SetDeadline(time.Now().Add(5 * time.Second)) + sc.Write([]byte(marker + "\n")) + sc.Close() + select { + case c.markers <- marker: + default: + } + } + }() + return c +} + +// close stops the canary's accept loop and closes the socket. +// Closing the listener also unlinks the socket file. +func (c *canaryListener) close() { + c.ln.Close() + <-c.done +} + +// TestFwdConnLocalUnixSymlinkToProtectedSocket pins the static-symlink +// variant of the root-dial race: a symlink inside an allowed directory +// may resolve anywhere, and the dial runs with the bound user's own +// permissions. +// +// The reachable half runs everywhere: a symlink inside the allowed /tmp +// dir to a socket the bound identity can open is served. The protected +// half is root-only: a root-owned 0600 canary outside the allowed +// directories, behind an in-allowlist symlink, must fail permission +// denied for the bound user. TestFwdDialCrossUser pins the same check +// at monitor level. +func TestFwdConnLocalUnixSymlinkToProtectedSocket(t *testing.T) { + lu := fwdTestIdentity(t) + c := newFwdTestConn(t, lu, &tailcfg.SSHAction{ + Accept: true, + AllowLocalPortForwarding: true, + }) + + dir := fwdTmpDir(t) + ctx, cancel := fwdTestCtx(nil) + t.Cleanup(cancel) + + // Reachable half, in every run. The allowlist does not resolve + // symlinks, so the user's own connect permission is the boundary. + reachable := filepath.Join(dir, "reachable.sock") + rl, err := net.Listen("unix", reachable) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { rl.Close() }) + if err := os.Chmod(reachable, 0o666); err != nil { + t.Fatal(err) + } + go func() { + for { + sc, err := rl.Accept() + if err != nil { + return + } + go func() { + defer sc.Close() + sc.SetDeadline(time.Now().Add(10 * time.Second)) + io.Copy(sc, sc) + }() + } + }() + okLink := filepath.Join(dir, "ok-link.sock") + if err := os.Symlink(reachable, okLink); err != nil { + t.Fatal(err) + } + uc, err := c.mayForwardLocalUnixTo(ctx, okLink) + if err != nil { + t.Fatalf("dial through in-allowlist symlink to reachable socket: %v", err) + } + setDeadlineConn(t, uc) + want := "symlink-dac" + if _, err := uc.Write([]byte(want)); err != nil { + t.Fatalf("write through symlinked forward: %v", err) + } + got := make([]byte, len(want)) + if _, err := io.ReadFull(uc, got); err != nil { + t.Fatalf("read through symlinked forward: %v", err) + } + if string(got) != want { + t.Errorf("echo through symlinked forward = %q, want %q", got, want) + } + uc.Close() + + // Protected half (root runs only): a root-owned 0600 canary outside + // the allowed directories, behind an in-allowlist symlink. Subtest so + // the reachable half above passes on its own and this guard's skip + // cannot erase it. + t.Run("protected-socket-dac", func(t *testing.T) { + if os.Getuid() != 0 { + t.Skipf("protected half is root-only: creating a socket protected against the bound user %q requires another uid; a root run of the suite exercises it (monitor-level DAC pin: TestFwdDialCrossUser)", lu.Username) + } + escape := filepath.Join("/var/run", fmt.Sprintf("tailssh-fwd-symlink-%d", os.Getpid())) + if err := os.MkdirAll(escape, 0o755); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(escape) }) + protected := filepath.Join(escape, "canary.sock") + canary := listenCanary(t, protected, 0o600, "PROTECTED") + t.Cleanup(canary.close) + evilLink := filepath.Join(dir, "evil-link.sock") + if err := os.Symlink(protected, evilLink); err != nil { + t.Fatal(err) + } + + // Every dial attempt through the symlink must fail with the kernel's + // EACCES as the bound user. None may reach the canary. + for i := 0; i < 5; i++ { + uc, err := c.mayForwardLocalUnixTo(ctx, evilLink) + if err == nil { + uc.Close() + t.Fatalf("root-dial regression: dial through in-allowlist symlink to root-owned 0600 socket SUCCEEDED as bound user %q", lu.Username) + } + if errors.Is(err, gliderssh.ErrRejected) { + t.Errorf("dial %q: allowlist rejected a lexically-allowed symlink path (%v); the boundary must be DAC, not path strings", evilLink, err) + } + if !strings.Contains(err.Error(), "permission denied") { + t.Errorf("dial %q error = %v, want permission denied (the bound user's DAC)", evilLink, err) + } + } + + // Control dial: the canary is served directly, without the forward, + // proving it is alive. + ctrl, err := net.Dial("unix", protected) + if err != nil { + t.Fatalf("control dial of canary: %v", err) + } + if err := ctrl.SetDeadline(time.Now().Add(5 * time.Second)); err != nil { + t.Fatal(err) + } + buf := make([]byte, 64) + n, err := io.ReadFull(ctrl, buf[:len("PROTECTED\n")]) + if err != nil { + t.Fatalf("control read of canary marker: %v", err) + } + if string(buf[:n]) != "PROTECTED\n" { + t.Fatalf("canary control marker = %q", buf[:n]) + } + ctrl.Close() + select { + case m := <-canary.markers: + if m != "PROTECTED" { + t.Fatalf("unexpected canary marker %q", m) + } + default: + t.Fatal("control marker not recorded by canary") + } + // The five forwarded attempts through the symlink were all refused. + if got := len(canary.markers); got != 0 { + t.Errorf("canary served %d extra connections after the control dial; the forwarded attempts reached the protected socket (root-dial race regression)", got) + } + }) +} + +// TestFwdConnLocalUnixDirSwapRaceNeverServesProtectedSocket is the +// direct pin of the race variant of the root-dial race: a parent +// directory is concurrently switched between the real directory and a +// symlink to an escape directory while forwarded dial attempts run. The +// dial runs as the connection's bound user, so a root-owned 0600 canary +// behind the raced path must never be served, and EACCES-classified +// attempts prove the symlink windows were hit. Root runs only. +func TestFwdConnLocalUnixDirSwapRaceNeverServesProtectedSocket(t *testing.T) { + if os.Getuid() != 0 { + t.Skip("root-only test: the race pin needs a protected (root-owned 0600) canary facing a non-root bound user; run under sudo") + } + lu := fwdTestIdentity(t) + c := newFwdTestConn(t, lu, &tailcfg.SSHAction{ + Accept: true, + AllowLocalPortForwarding: true, + }) + + base := fwdTmpDir(t) // 0777, inside the allowlist + owned := filepath.Join(base, "owned") + aside := filepath.Join(base, "aside") + for _, d := range []string{owned, aside} { + if err := os.Mkdir(d, 0o755); err != nil { + t.Fatal(err) + } + } + // The escape directory is outside the tested path's own tree, like + // /var/run/docker.sock. It is traversable by every user, and its + // canary is protected by socket mode alone. + escape := filepath.Join("/var/run", fmt.Sprintf("tailssh-fwd-race-%d", os.Getpid())) + if err := os.MkdirAll(escape, 0o755); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(escape) }) + canaryPath := filepath.Join(escape, "canary.sock") + dialPath := filepath.Join(owned, "canary.sock") + + // The swap loop alternates between the real empty directory + // and a symlink to the escape directory. It holds each state about + // 3ms so both are well represented across the dial attempts. A + // failed step restores the real-dir state, so the loop self-heals. + stop := make(chan struct{}) + swapsDone := make(chan struct{}) + var swaps, attempts, dials, eacces, enoent atomic.Int64 + hold := func() { + select { + case <-stop: + case <-time.After(3 * time.Millisecond): + } + } + go func() { + defer close(swapsDone) + for { + select { + case <-stop: + return + default: + } + os.Remove(aside) + if err := os.Rename(owned, aside); err != nil { + continue + } + if err := os.Symlink(escape, owned); err != nil { + os.Rename(aside, owned) + continue + } + swaps.Add(1) + hold() // symlink state is in place + os.Remove(owned) + if err := os.Rename(aside, owned); err != nil { + os.Mkdir(owned, 0o755) + } + hold() + } + }() + t.Cleanup(func() { + close(stop) + <-swapsDone + }) + + // One forwarded dial attempt for the raced path, classified. + probe := func() (servedMarker string, class string) { + gctx, cancel := fwdTestCtxTimeout(8 * time.Second) + defer cancel() + attempts.Add(1) + uc, err := c.mayForwardLocalUnixTo(gctx, dialPath) + if err != nil { + switch s := err.Error(); { + case strings.Contains(s, "permission denied"): + eacces.Add(1) + return "", "eacces" + case strings.Contains(s, "no such file"): + enoent.Add(1) + return "", "enoent" + default: + return "", "err" + } + } + dials.Add(1) + defer uc.Close() + if err := uc.SetDeadline(time.Now().Add(3 * time.Second)); err != nil { + t.Errorf("SetDeadline on forward conn: %v", err) + return "", "ok" + } + buf := make([]byte, 128) + n, _ := uc.Read(buf) + return strings.TrimSpace(string(buf[:n])), "ok" + } + + const controlMarker = "CTL-CANARY" + const protectedMarker = "PRT-CANARY" + + // In the control phase, an accessible 0666 canary proves the harness + // delivers markers through raced forwards when the target is + // user-accessible. + control := listenCanary(t, canaryPath, 0o666, controlMarker) + served := 0 + for i := 0; i < 60; i++ { + if marker, class := probe(); class == "ok" { + if marker != controlMarker { + t.Fatalf("control phase served unexpected marker %q", marker) + } + served++ + break + } + } + if served == 0 { + t.Fatalf("control configuration never delivered a marker; cannot attest the race harness (swaps so far: %d, attempts: %d)", swaps.Load(), attempts.Load()) + } + t.Logf("control configuration: marker delivered (attempts so far: %d, swaps: %d)", attempts.Load(), swaps.Load()) + control.close() + // The stdlib unix listener's Close already unlinked the socket, so + // the removal tolerates ENOENT. The path must be gone before the + // protected canary rebinds it. + if err := os.Remove(canaryPath); err != nil && !os.IsNotExist(err) { + t.Fatal(err) + } + + // In the protected phase, a root-owned 0600 canary behind the very same + // raced path. It must never serve. + protected := listenCanary(t, canaryPath, 0o600, protectedMarker) + t.Cleanup(protected.close) + const raceAttempts = 200 + for i := 0; i < raceAttempts; i++ { + marker, class := probe() + if class == "ok" { + t.Fatalf("root-dial race regression: attempt %d reached the protected canary through the raced forward (marker %q)", i, marker) + } + if marker != "" { + t.Fatalf("root-dial regression: attempt %d received %q from beyond the forward; the protected canary was served", i, marker) + } + } + if got := len(protected.markers); got != 0 { + t.Fatalf("REGRESSION: protected canary served %d connections through the raced forward", got) + } + if got := eacces.Load(); got == 0 { + t.Fatalf("no dial attempt hit the protected canary through the swapped symlink (%d attempts, %d swaps); the race harness did not exercise the symlink state", attempts.Load(), swaps.Load()) + } + if got := enoent.Load(); got == 0 { + t.Logf("note: no ENOENT-classified attempt observed (%d attempts)", attempts.Load()) + } + t.Logf("protected canary never served: %d total attempts, %d succeeded, %d EACCES (symlink state hit, DAC-refused), %d ENOENT, %d swaps", + attempts.Load(), dials.Load(), eacces.Load(), enoent.Load(), swaps.Load()) +} + +// 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 +// capacity reject lexically. +func TestFwdAllowedSocketPathCaps(t *testing.T) { + for _, home := range []string{"/", "//", ""} { + c := &conn{localUser: &userMeta{User: user.User{Username: "u", Uid: "1000", Gid: "1000", HomeDir: home}}} + for _, bad := range []string{"/var/run/docker.sock", "/etc/passwd", "/root/x.sock", "/home"} { + if _, err := c.fwdAllowedSocketPath(bad); err == nil { + t.Errorf("fwdAllowedSocketPath(%q) with HomeDir %q = nil error; want rejection (a /-home must not match every path)", bad, home) + } + } + // The unconditional entries survive a collapsed home. + for _, ok := range []string{"/tmp/x.sock", "/run/user/1000/x.sock"} { + if _, err := c.fwdAllowedSocketPath(ok); err != nil { + t.Errorf("fwdAllowedSocketPath(%q) with HomeDir %q: %v; want allowed", ok, home, err) + } + } + } + // The sun_path length cap rejects at and above the cap and passes + // below, still inside an allowed dir. + c := &conn{localUser: &userMeta{User: user.User{Username: "u", Uid: "1000", Gid: "1000", HomeDir: "/home/u"}}} + if _, err := c.fwdAllowedSocketPath("/tmp/" + strings.Repeat("a", fwdMaxSunPathLen)); err == nil { + t.Errorf("path of length %d accepted; want the sun_path cap to reject", len("/tmp/")+fwdMaxSunPathLen) + } + if _, err := c.fwdAllowedSocketPath("/tmp/" + strings.Repeat("a", fwdMaxSunPathLen-6)); err != nil { + t.Errorf("path below the sun_path cap rejected: %v", err) + } +} + +// TestFwdMonitorClosedRefusesRespawn pins the closed flag on fwdState. +// See fwdState.closed. Once the conn's teardown has run, fwdMonitor must +// refuse to spawn for every late caller, including session launch, unix +// and TCP forwarding, and agent forwarding. +func TestFwdMonitorClosedRefusesRespawn(t *testing.T) { + lu := fwdTestIdentity(t) + c := newFwdTestConn(t, lu, &tailcfg.SSHAction{Accept: true}) + if _, err := c.fwdMonitor(); err != nil { + t.Fatalf("spawning monitor: %v", err) + } + c.closeFwdMonitor() + + if _, err := c.fwdMonitor(); err == nil { + t.Fatal("fwdMonitor spawned a monitor after closeFwdMonitor; want refusal (nobody would close it)") + } + if mc := c.fwdMonitorIfAny(); mc != nil { + t.Fatal("fwdMonitor left a monitor in fwd.mon after closeFwdMonitor") + } + // Closing again stays a no-op. + c.closeFwdMonitor() +} + +// TestRemoveAgentForwardingDirRefuses pins the session-end removal guard +// for the agent-forwarding directory. The directory was created by a +// child running as the connection's user and the removal runs with the +// daemon's credentials, so only the shape the child was supposed to +// produce — a real directory (never a symlink) named auth-agent*, +// directly inside the root-owned agentDirRoot, owned by the connection's +// user with no group or other access — is removed. A symlink entry, a +// directory outside agentDirRoot, and a loosened mode are all refused +// and left in place. +func TestRemoveAgentForwardingDirRefuses(t *testing.T) { + if fi, err := os.Stat(agentDirRoot); err != nil || !fi.Mode().IsDir() { + t.Skipf("agentDirRoot %s unavailable: %v", agentDirRoot, err) + } + if st, ok := fi2stat(t, agentDirRoot); !ok || st.Uid != 0 { + t.Skipf("agentDirRoot %s is not root-owned; the pin needs the standard temp root", agentDirRoot) + } + lu := &userMeta{User: user.User{Uid: strconv.Itoa(os.Getuid()), Username: "self"}} + + // Positive control: the real shape is removed. + dir, err := os.MkdirTemp(agentDirRoot, "auth-agent") + if err != nil { + t.Fatal(err) + } + removeAgentForwardingDir(dir, lu, t.Logf) + if _, err := os.Stat(dir); !os.IsNotExist(err) { + t.Fatalf("agent dir %q still exists after removal (err=%v)", dir, err) + } + + // A symlink entry is never followed: the symlink is refused and its + // target untouched. + d, err := os.MkdirTemp(agentDirRoot, "auth-agent") + if err != nil { + t.Fatal(err) + } + os.Remove(d) + target := t.TempDir() + if err := os.Symlink(target, d); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.Remove(d) }) + removeAgentForwardingDir(d, lu, t.Logf) + if _, err := os.Stat(d); err != nil { + t.Fatalf("steered symlink entry %q was removed", d) + } + if _, err := os.Stat(target); err != nil { + t.Fatalf("symlink target %q removed through the steered entry", target) + } + + // A directory outside agentDirRoot is refused, whatever its name. + outside := filepath.Join(t.TempDir(), "auth-agent-outside") + if err := os.Mkdir(outside, 0o700); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(outside) }) + removeAgentForwardingDir(outside, lu, t.Logf) + if _, err := os.Stat(outside); err != nil { + t.Fatalf("outside dir %q was removed", outside) + } + + // A loosened mode is refused: the dir stays behind. + loose, err := os.MkdirTemp(agentDirRoot, "auth-agent") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(loose) }) + if err := os.Chmod(loose, 0o711); err != nil { + t.Fatal(err) + } + removeAgentForwardingDir(loose, lu, t.Logf) + if _, err := os.Stat(loose); err != nil { + t.Fatalf("loose-mode dir %q was removed", loose) + } +} + +// fi2stat returns the syscall.Stat_t of path, reporting ok=false when +// the platform does not expose one. +func fi2stat(t *testing.T, path string) (syscall.Stat_t, bool) { + t.Helper() + fi, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + st, ok := fi.Sys().(*syscall.Stat_t) + return *st, ok +} diff --git a/ssh/tailssh/fwdplan9.go b/ssh/tailssh/fwdplan9.go new file mode 100644 index 000000000..acb300b41 --- /dev/null +++ b/ssh/tailssh/fwdplan9.go @@ -0,0 +1,120 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build plan9 + +// The plan9 forwarding seam. plan9 keeps today's forwarding behavior: +// tailscaled binds and dials forwarded sockets itself, with no monitor +// because SysProcAttr.Credential and SCM_RIGHTS are unavailable. Reverse +// TCP forwarding keeps gliderssh's ForwardedTCPHandler with the +// mayReversePortForwardTo policy callback. + +package tailssh + +import ( + "net" + "os" + "path/filepath" + "strconv" + + "tailscale.com/types/logger" + + gliderssh "github.com/tailscale/gliderssh" +) + +// fwdState is the conn's forwarding state. On plan9 there is no monitor, +// so it carries nothing. +type fwdState struct{} + +// fwdDialUnix is the unix -L path. The gliderssh callback rejects on +// plan9. See the file comment. +func (c *conn) fwdDialUnix(ctx gliderssh.Context, socketPath string) (net.Conn, error) { + cb := gliderssh.NewLocalUnixForwardingCallback(c.unixForwardingOptions()) + return cb(ctx, socketPath) +} + +// fwdListenUnix is the unix -R path. The gliderssh callback rejects on +// plan9. See the file comment. +func (c *conn) fwdListenUnix(ctx gliderssh.Context, socketPath string) (net.Listener, error) { + cb := gliderssh.NewReverseUnixForwardingCallback(c.unixForwardingOptions()) + return cb(ctx, socketPath) +} + +// fwdListenAgent returns the agent-forwarding listener and socket path. +// plan9 keeps today's behavior. tailscaled creates the socket with +// gliderssh.NewAgentListener and hands it, and its containing directory, +// to the session user with explicit chmod/chown. +func (c *conn) fwdListenAgent(ctx gliderssh.Context, lu *userMeta) (net.Listener, string, error) { + ln, err := gliderssh.NewAgentListener() + if err != nil { + return nil, "", err + } + defer func() { + if err != nil && ln != nil { + ln.Close() + } + }() + + // 31 bits so that the values fit an int on every platform. + uid, err := strconv.ParseUint(lu.Uid, 10, 31) + if err != nil { + return nil, "", err + } + gid, err := strconv.ParseUint(lu.Gid, 10, 31) + if err != nil { + return nil, "", err + } + socket := ln.Addr().String() + dir := filepath.Dir(socket) + // Hand the socket and its containing directory to the user, like + // sshd's agent forwarding. The dir stays 0700 as MkdirTemp created it + // until the socket is in place and owned by the user, then it is + // chowned to the user too so the session can reach its socket. + if err := os.Chmod(socket, 0o600); err != nil { + return nil, "", err + } + if err := os.Chown(socket, int(uid), int(gid)); err != nil { + return nil, "", err + } + if err := os.Chown(dir, int(uid), int(gid)); err != nil { + return nil, "", err + } + // Defensively restore the 0700 mode. + if err := os.Chmod(dir, 0o700); err != nil { + return nil, "", err + } + return ln, socket, nil +} + +// removeAgentForwardingDir removes the agent-forwarding directory dir. +// plan9 has no monitor: tailscaled created the directory itself and +// handed it to the session user, and the removal runs with the same +// credentials, so there is no privilege boundary to defend. +func removeAgentForwardingDir(dir string, lu *userMeta, logf logger.Logf) { + if err := os.RemoveAll(dir); err != nil { + logf("ssh: removing agent forwarding dir: %v", err) + } +} + +// closeFwdMonitor is a no-op on plan9 because there is no monitor. +func (c *conn) closeFwdMonitor() {} + +// wireReverseForwarding installs plan9's reverse TCP forwarding +// handlers. They are today's gliderssh ForwardedTCPHandler plus the +// mayReversePortForwardTo policy callback. +func (c *conn) wireReverseForwarding(ss *gliderssh.Server) { + ss.ReversePortForwardingCallback = c.mayReversePortForwardTo + fwdHandler := &gliderssh.ForwardedTCPHandler{} + ss.RequestHandlers["tcpip-forward"] = fwdHandler.HandleSSHRequest + ss.RequestHandlers["cancel-tcpip-forward"] = fwdHandler.HandleSSHRequest +} + +// unixForwardingOptions returns the Unix forwarding options scoped to +// the authenticated local user. Socket paths are restricted to the +// user's home directory, /tmp, and /run/user/. +func (c *conn) unixForwardingOptions() gliderssh.UnixForwardingOptions { + return gliderssh.UnixForwardingOptions{ + AllowedDirectories: gliderssh.UserSocketDirectories(c.localUser.HomeDir, c.localUser.Uid), + BindUnlink: true, + } +} diff --git a/ssh/tailssh/monitor.go b/ssh/tailssh/monitor.go index d6326d67a..ba7a15b13 100644 --- a/ssh/tailssh/monitor.go +++ b/ssh/tailssh/monitor.go @@ -67,6 +67,12 @@ type monitor struct { children map[int]*monChild hup chan os.Signal broken bool // a reply or notification write failed. Leave the loop. + + // pendingFds holds relayed dial/listen descriptors, keyed by request + // ID, from the reply write until tailscaled's fdack receipt. See + // replyFD and the monitor_rpc.go header for the darwin kernel + // behavior this coverage exists for. + pendingFds map[int64]int } // monitorArgs are the monitor's spawn arguments, in the style of @@ -164,10 +170,11 @@ func beMonitor(args []string) error { defer signal.Stop(hup) m := &monitor{ - conn: newRPCConn(conn), - args: ma, - children: make(map[int]*monChild), - hup: hup, + conn: newRPCConn(conn), + args: ma, + children: make(map[int]*monChild), + pendingFds: make(map[int64]int), + hup: hup, } return m.loop() } @@ -290,6 +297,12 @@ func (m *monitor) handle(f rpcFrame, fds []int) { case opSignal: closeFds(fds) m.handleSignal(f) + case opFdAck: + closeFds(fds) + if fd, ok := m.pendingFds[f.ID]; ok { + delete(m.pendingFds, f.ID) + unix.Close(fd) + } case opDial: closeFds(fds) m.handleDial(f) @@ -489,8 +502,9 @@ func (m *monitor) handleListen(f rpcFrame) { // reports for the agent-forwarding listen op. The child runs as the // connection's user, and tailscaled removes the socket's directory as // root when the session closes, so a misbehaving child must not be able -// to steer that removal elsewhere: the path must be an absolute -// listener.sock inside an auth-agent temp directory. +// to steer that removal elsewhere: the path must be a listener.sock +// directly inside an auth-agent temp directory directly inside +// agentDirRoot. func checkAgentSocketPath(p string) error { if !filepath.IsAbs(p) { return fmt.Errorf("agent socket path %q is not absolute", p) @@ -498,7 +512,11 @@ func checkAgentSocketPath(p string) error { if filepath.Base(p) != "listener.sock" { return fmt.Errorf("agent socket path %q does not name listener.sock", p) } - if dir := filepath.Base(filepath.Dir(p)); !strings.HasPrefix(dir, "auth-agent") { + dir := filepath.Dir(p) + if filepath.Dir(dir) != agentDirRoot { + return fmt.Errorf("agent socket %q is not directly inside %s", p, agentDirRoot) + } + if base := filepath.Base(dir); !strings.HasPrefix(base, "auth-agent") { return fmt.Errorf("agent socket %q is not inside an auth-agent directory", p) } return nil @@ -546,16 +564,23 @@ func (m *monitor) killChild(c *monChild) { } } -// replyFD writes a reply carrying one descriptor and closes the -// monitor's copy after the write. After sendmsg the kernel holds its -// own reference to the passed file, so the peer's copy survives ours -// closing. +// replyFD writes a reply carrying one descriptor. On success the +// descriptor stays open, parked in pendingFds until tailscaled's fdack: +// on darwin, closing the sender's copy while the descriptor's only +// reference is the in-flight SCM_RIGHTS message lets the kernel's +// unix-socket GC reclaim the socket (receive side flushed, buffered +// data discarded) before the receiver's recvmsg, producing a relayed +// socket that reads EOF with its peer still alive. The receiver's +// acknowledgment is what releases the hold. On a write failure the +// channel is broken and the descriptor is closed here. func (m *monitor) replyFD(f rpcFrame, fd int) { err := m.conn.writeFrame(f, fd) - unix.Close(fd) if err != nil { + unix.Close(fd) m.broken = true + return } + m.pendingFds[f.ID] = fd } // sweep reaps exited children with wait4(WNOHANG) and drops them from @@ -629,6 +654,12 @@ func (m *monitor) notifyExit(pid, code int) { // survived the HUP and reaps again. 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. + for id, fd := range m.pendingFds { + unix.Close(fd) + delete(m.pendingFds, id) + } // Snapshot the pgid set at teardown entry. A group member can // outlive its reaped leader, so the SIGKILL pass keys on this // remembered set rather than on surviving table entries. diff --git a/ssh/tailssh/monitor_client.go b/ssh/tailssh/monitor_client.go index 2b48a8c23..10400b95c 100644 --- a/ssh/tailssh/monitor_client.go +++ b/ssh/tailssh/monitor_client.go @@ -107,6 +107,17 @@ func (mc *monitorClient) readLoop() { if err != nil { return } + // Acknowledge receipt of any relayed descriptors so the monitor + // releases its hold on its copies. The recvmsg in readFrame is + // what transfers ownership; see the monitor_rpc.go header for + // the darwin kernel behavior the acknowledgment covers. A write + // failure means the channel is going away; the monitor's + // teardown closes its parked copies either way. + if len(fds) > 0 { + mc.writeMu.Lock() + _ = mc.rpc.writeFrame(rpcFdAckReq(f.ID)) + mc.writeMu.Unlock() + } mc.dispatch(f, fds) } } @@ -242,6 +253,8 @@ func (mc *monitorClient) Signal(ctx context.Context, pid int, sig string) error // Dial dials a unix socket through a one-shot child running with the // connection's bound identity and returns the connected socket. +// The returned socket is acknowledged to the monitor on receipt, which +// releases the monitor's held copy; see the monitor_rpc.go header. func (mc *monitorClient) Dial(ctx context.Context, addr string) (*net.UnixConn, error) { _, fds, err := mc.call(ctx, rpcDialReq(0, addr)) if err != nil { diff --git a/ssh/tailssh/monitor_rpc.go b/ssh/tailssh/monitor_rpc.go index bd55cccbf..a848ebbc9 100644 --- a/ssh/tailssh/monitor_rpc.go +++ b/ssh/tailssh/monitor_rpc.go @@ -25,6 +25,15 @@ // line that follows it, regardless of how the kernel shapes reads. See // recvFdSets, sendFds and rpcMaxLine for the descriptor and line-size // rules. +// +// A dial or listen reply's descriptor is held open by its sender until +// the receiver acknowledges it with an fdack frame naming the reply's +// request ID. On darwin, a socket whose only reference is an in-flight +// SCM_RIGHTS message is reclaimed by the kernel's unix-socket garbage +// collector: its receive side is flushed and buffered data discarded +// while recvmsg still returns a usable descriptor. Continuous +// process-owned coverage across the handoff, released only on receipt, +// closes that window. package tailssh @@ -49,6 +58,7 @@ const ( opSignal = "signal" // request {pid, sig}. reply {ok} opPing = "ping" // request {}. reply {ok} opExit = "exit" // unsolicited notification {pid, code}. no ID + opFdAck = "fdack" // request {id of the reply whose descriptors were received}. no fds, no reply ) const ( @@ -157,6 +167,13 @@ func rpcExitNotify(pid, code int) rpcFrame { return rpcFrame{Op: opExit, Pid: pid, Code: code} } +// rpcFdAckReq acknowledges receipt of the descriptors a reply with the +// given request ID carried. The sender of those descriptors holds its own +// copies until this arrives; see replyFD in monitor.go for why. +func rpcFdAckReq(replyID int64) rpcFrame { + return rpcFrame{ID: replyID, Op: opFdAck} +} + // maxFdsForOp reports the maximum number of SCM_RIGHTS descriptors a // frame of op may carry in either direction. Exec carries child stdio. // Dial and listen replies carry the connected or bound socket. diff --git a/ssh/tailssh/monitor_test.go b/ssh/tailssh/monitor_test.go index b66b2caa5..b98253efc 100644 --- a/ssh/tailssh/monitor_test.go +++ b/ssh/tailssh/monitor_test.go @@ -351,6 +351,8 @@ func TestCheckAgentSocketPath(t *testing.T) { {"/tmp/auth-agent123456/listener.sock", true}, {"/tmp/auth-agent/listener.sock", true}, {"/tmp/auth-agent123/inner/listener.sock", false}, // nested dir + {"/home/u/auth-agent123/listener.sock", false}, // outside agentDirRoot + {"/var/run/auth-agent123/listener.sock", false}, // outside agentDirRoot {"tmp/auth-agent123/listener.sock", false}, // not absolute {"/tmp/auth-agent123/other.sock", false}, // wrong file name {"/tmp/other123/listener.sock", false}, // wrong dir name diff --git a/ssh/tailssh/process_unix.go b/ssh/tailssh/process_unix.go index 8789d4544..b60be0892 100644 --- a/ssh/tailssh/process_unix.go +++ b/ssh/tailssh/process_unix.go @@ -13,7 +13,6 @@ import ( "os/exec" "path/filepath" "runtime" - "strconv" "syscall" gliderssh "github.com/tailscale/gliderssh" @@ -100,6 +99,9 @@ func systemHostKeyFile(typ string) string { // handleSSHAgentForwarding starts a Unix socket listener and in the background // forwards agent connections between the listener and the gliderssh.Session. // On success, it assigns ss.agentListener. +// +// The listener and its containing directory are created by a user-cred +// child through conn.fwdListenAgent. See the docs there for the modes. func (ss *sshSession) handleSSHAgentForwarding(s gliderssh.Session, lu *userMeta) error { if !gliderssh.AgentRequested(ss) || !ss.conn.finalAction.AllowAgentForwarding { return nil @@ -111,56 +113,29 @@ func (ss *sshSession) handleSSHAgentForwarding(s gliderssh.Session, lu *userMeta return nil } ss.logf("ssh: agent forwarding requested") - ln, err := gliderssh.NewAgentListener() + ln, socket, err := ss.conn.fwdListenAgent(s.Context(), lu) if err != nil { return err } - defer func() { - if err != nil && ln != nil { - ln.Close() - } - }() - - // 31 bits so that the values fit an int on every platform. - uid, err := strconv.ParseUint(lu.Uid, 10, 31) - if err != nil { - return err + // The listener's own address is the kernel's bound path; socket is + // the path the child reported and the monitor validated. They must + // agree: the cleanup removes the directory of the validated path, so + // a child whose report and actual bind disagree is refused. + if got := ln.Addr().String(); got != socket { + ln.Close() + return fmt.Errorf("agent forwarding socket path %q does not match the listener's bound path %q", socket, got) } - gid, err := strconv.ParseUint(lu.Gid, 10, 31) - if err != nil { - return err - } - socket := ln.Addr().String() - dir := filepath.Dir(socket) - // Make sure the socket is accessible only by the user, and hand the - // socket and its containing directory to the user (like sshd's - // agent forwarding): the dir stays 0700 (as MkdirTemp created it) - // until the socket is in place and owned by the user, then the dir - // is chowned to the user too so the session can reach its socket - // without it being group/world-accessible. - if err := os.Chmod(socket, 0600); err != nil { - return err - } - if err := os.Chown(socket, int(uid), int(gid)); err != nil { - return err - } - if err := os.Chown(dir, int(uid), int(gid)); err != nil { - return err - } - // Defensively restore the 0700 mode in case the umask or a future - // change loosened it. - if err := os.Chmod(dir, 0700); err != nil { - return err - } - - go gliderssh.ForwardAgentConnections(ln, s) ss.agentListener = ln + go gliderssh.ForwardAgentConnections(ln, s) return nil } // closeAgentForwarding closes the agent forwarding listener and removes the // temporary directory that holds its socket, so neither outlives the -// session. +// session. The removal rules are platform-specific: on the monitor +// platforms the directory was created by a user-cred child while the +// removal runs with the daemon's credentials; see +// removeAgentForwardingDir in fwdmonitor.go and fwdplan9.go. func (ss *sshSession) closeAgentForwarding() { ln := ss.agentListener if ln == nil { @@ -169,7 +144,5 @@ func (ss *sshSession) closeAgentForwarding() { ss.agentListener = nil dir := filepath.Dir(ln.Addr().String()) ln.Close() - if err := os.RemoveAll(dir); err != nil { - ss.logf("ssh: removing agent forwarding dir: %v", err) - } + removeAgentForwardingDir(dir, ss.conn.localUser, ss.logf) } diff --git a/ssh/tailssh/process_unix_test.go b/ssh/tailssh/process_unix_test.go index 050d316ed..05fc98fca 100644 --- a/ssh/tailssh/process_unix_test.go +++ b/ssh/tailssh/process_unix_test.go @@ -8,14 +8,16 @@ package tailssh import ( "context" "errors" - "fmt" "net" "os" "os/user" "path/filepath" + "strconv" + "strings" "sync" "syscall" "testing" + "time" gliderssh "github.com/tailscale/gliderssh" gossh "golang.org/x/crypto/ssh" @@ -64,10 +66,15 @@ type agentFwdSession struct { func (s agentFwdSession) Context() gliderssh.Context { return s.ctx } -func newAgentTestSession() (*sshSession, *agentFwdSession) { - c := &conn{ - srv: &server{logf: logger.Discard}, - finalAction: &tailcfg.SSHAction{Accept: true, AllowAgentForwarding: true}, +// newAgentTestSession returns a minimal sshSession (with its gliderssh +// Session stub) on the given conn, for driving handleSSHAgentForwarding. +// The conn comes from the test at hand: agent tests pass a monitor-backed +// conn (fwdmonitor_test.go's newFwdTestConn) so the listener is created by +// the bound-identity child. +func newAgentTestSession(t *testing.T, c *conn) (*sshSession, *agentFwdSession) { + t.Helper() + if c.srv == nil { + c.srv = &server{logf: logger.Discard} } ctx := agentFwdContext{Context: context.Background(), Mutex: &sync.Mutex{}} ss := &sshSession{ @@ -79,16 +86,21 @@ func newAgentTestSession() (*sshSession, *agentFwdSession) { } // TestAgentForwardDirCleanup verifies that the agent forwarding socket's -// temp directory is removed when the session ends. +// temp directory is removed when the session ends, driving the real +// handleSSHAgentForwarding path (the socket and dir are created by the +// monitor's bound-identity child). func TestAgentForwardDirCleanup(t *testing.T) { - ln, err := gliderssh.NewAgentListener() - if err != nil { - t.Fatal(err) - } - ss, _ := newAgentTestSession() - ss.agentListener = ln + lu := fwdTestIdentity(t) + c := newFwdTestConn(t, lu, &tailcfg.SSHAction{Accept: true, AllowAgentForwarding: true}) + ss, s := newAgentTestSession(t, c) - dir := filepath.Dir(ln.Addr().String()) + if err := ss.handleSSHAgentForwarding(s, lu); err != nil { + t.Fatalf("handleSSHAgentForwarding: %v", err) + } + if ss.agentListener == nil { + t.Fatal("agent listener not set") + } + dir := filepath.Dir(ss.agentListener.Addr().String()) if _, err := os.Stat(dir); err != nil { t.Fatalf("stat agent dir: %v", err) } @@ -102,23 +114,29 @@ func TestAgentForwardDirCleanup(t *testing.T) { // TestHandleSSHAgentForwardingDirHygiene verifies the socket and its // containing directory are accessible only by the local user (0600 socket, -// 0700 user-owned directory), not group/world-accessible root-owned state. +// 0700 user-owned directory), created by a child with the session user's +// credentials, not group/world-accessible root-owned state. Root runs +// bind the monitor to the non-root test user. Non-root runs bind to the +// current user, where a non-root tailscaled forwards as itself. func TestHandleSSHAgentForwardingDirHygiene(t *testing.T) { - if os.Geteuid() != 0 { - t.Skipf("skipping when not running as root: os.Chown is required") + lu := fwdTestIdentity(t) + uid, err := strconv.Atoi(lu.Uid) + if err != nil { + t.Fatal(err) } - - const uid, gid = 1234, 1235 - ss, s := newAgentTestSession() - lu := &userMeta{User: user.User{Username: "alice", Uid: fmt.Sprint(uid), Gid: fmt.Sprint(gid)}} + c := newFwdTestConn(t, lu, &tailcfg.SSHAction{Accept: true, AllowAgentForwarding: true}) + ss, s := newAgentTestSession(t, c) if err := ss.handleSSHAgentForwarding(s, lu); err != nil { t.Fatalf("handleSSHAgentForwarding: %v", err) } t.Cleanup(ss.closeAgentForwarding) + // The session environment's SSH_AUTH_SOCK is the listener's address. socketPath := ss.agentListener.Addr().String() - dir := filepath.Dir(socketPath) + if !strings.HasPrefix(filepath.Dir(socketPath), "/tmp/auth-agent") { + t.Errorf("agent socket path %q not in a /tmp/auth-agent* dir", socketPath) + } si, err := os.Stat(socketPath) if err != nil { @@ -131,7 +149,7 @@ func TestHandleSSHAgentForwardingDirHygiene(t *testing.T) { t.Errorf("socket uid = %d; want %d", si.Sys().(*syscall.Stat_t).Uid, uid) } - di, err := os.Stat(dir) + di, err := os.Stat(filepath.Dir(socketPath)) if err != nil { t.Fatalf("stat dir: %v", err) } @@ -142,3 +160,64 @@ func TestHandleSSHAgentForwardingDirHygiene(t *testing.T) { t.Errorf("dir uid = %d; want %d (must be owned by the session user, not root)", di.Sys().(*syscall.Stat_t).Uid, uid) } } + +// fakeFileInfo backs the checkAgentDirRemovable table: it lets the +// wrong-owner and not-a-directory cases run without a second uid. +type fakeFileInfo struct { + name string + mode os.FileMode + sys any +} + +func (fi fakeFileInfo) Name() string { return fi.name } +func (fi fakeFileInfo) Size() int64 { return 0 } +func (fi fakeFileInfo) Mode() os.FileMode { return fi.mode } +func (fi fakeFileInfo) ModTime() time.Time { return time.Time{} } +func (fi fakeFileInfo) IsDir() bool { return fi.Mode().IsDir() } +func (fi fakeFileInfo) Sys() any { return fi.sys } + +// TestCheckAgentDirRemovable pins the removal guard for the +// agent-forwarding directory. The path was reported by a child running +// as the connection's user, and the removal runs as root: only a real +// directory (Lstat, so a symlink does not pass), owned by the bound +// user and without group or other access, may be removed. +func TestCheckAgentDirRemovable(t *testing.T) { + lu := &userMeta{User: user.User{Uid: "1000", Username: "u"}} + // A real MkdirTemp directory: the shape the fwd child is supposed + // to produce, owned by the current user. + dir, err := os.MkdirTemp("", "auth-agent") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + fi, err := os.Lstat(dir) + if err != nil { + t.Fatal(err) + } + luSelf := &userMeta{User: user.User{Uid: strconv.Itoa(os.Getuid()), Username: "self"}} + if err := checkAgentDirRemovable(fi, luSelf); err != nil { + t.Fatalf("checkAgentDirRemovable(real MkdirTemp dir) = %v, want nil", err) + } + + if err := checkAgentDirRemovable(fakeFileInfo{name: "auth-agent1", mode: 0o700 | os.ModeDir, sys: &syscall.Stat_t{Uid: 1000}}, lu); err != nil { + t.Fatalf("checkAgentDirRemovable(bound-user dir) = %v, want nil", err) + } + + for _, tt := range []struct { + name string + fi os.FileInfo + lu *userMeta + }{ + {"group-accessible dir", fakeFileInfo{name: "auth-agent1", mode: 0o750 | os.ModeDir, sys: &syscall.Stat_t{Uid: 1000}}, lu}, + {"world-accessible dir", fakeFileInfo{name: "auth-agent1", mode: 0o755 | os.ModeDir, sys: &syscall.Stat_t{Uid: 1000}}, lu}, + {"symlink to a directory", fakeFileInfo{name: "auth-agent1", mode: 0o777 | os.ModeSymlink, sys: &syscall.Stat_t{Uid: 1000}}, lu}, + {"regular file", fakeFileInfo{name: "listener.sock", mode: 0o600, sys: &syscall.Stat_t{Uid: 1000}}, lu}, + {"dir owned by another uid", fakeFileInfo{name: "auth-agent1", mode: 0o700 | os.ModeDir, sys: &syscall.Stat_t{Uid: 0}}, lu}, + {"dir without stat owner", fakeFileInfo{name: "auth-agent1", mode: 0o700 | os.ModeDir, sys: struct{}{}}, lu}, + } { + err := checkAgentDirRemovable(tt.fi, tt.lu) + if err == nil { + t.Errorf("checkAgentDirRemovable(%s) = nil, want an error", tt.name) + } + } +} diff --git a/ssh/tailssh/tailssh.go b/ssh/tailssh/tailssh.go index 50a164a12..0eb8bdb95 100644 --- a/ssh/tailssh/tailssh.go +++ b/ssh/tailssh/tailssh.go @@ -53,7 +53,10 @@ var ( sshVerboseLogging = envknob.RegisterBool("TS_DEBUG_SSH_VLOG") sshDisableSFTP = envknob.RegisterBool("TS_SSH_DISABLE_SFTP") sshDisableForwarding = envknob.RegisterBool("TS_SSH_DISABLE_FORWARDING") - sshDisablePTY = envknob.RegisterBool("TS_SSH_DISABLE_PTY") + // sshForwardGatewayPorts permits reverse TCP forwards to bind + // non-loopback addresses. It is the equivalent of sshd's GatewayPorts. + sshForwardGatewayPorts = envknob.RegisterBool("TS_SSH_FORWARD_GATEWAY_PORTS") + sshDisablePTY = envknob.RegisterBool("TS_SSH_DISABLE_PTY") // sshLoginGraceTime is the TS_SSH_LOGIN_GRACE_TIME knob. It is // the maximum allowed duration between accepting a connection and @@ -177,6 +180,8 @@ func (srv *server) HandleSSHConn(nc net.Conn) error { } srv.trackActiveConn(c, true) // add defer srv.trackActiveConn(c, false) // remove + // The connection is done when HandleConn returns. See closeFwdMonitor. + defer c.closeFwdMonitor() c.HandleConn(nc) // Return nil to signal to netstack's interception that it doesn't need to @@ -229,6 +234,9 @@ func (srv *server) OnPolicyChange() { // in any order. // - c.handleSessionPostSSHAuth // - c.mayForwardLocalPortTo followed by gliderssh.DirectTCPIPHandler +// - c.mayForwardLocalUnixTo, the unix -L dial +// - c.mayReverseUnixForwardTo, the unix -R bind +// - c.wireReverseForwarding's "tcpip-forward" handlers, the TCP -R bind type conn struct { *gliderssh.Server srv *server @@ -273,6 +281,12 @@ type conn struct { // acquire mu and then srv.mu. mu sync.Mutex // protects the following sessions []*sshSession + + // fwd is the connection's forwarding state. On unix it holds the + // lazily-spawned per-connection ssh-monitor that dials and binds + // forwarded sockets with the local user's credentials. On plan9 it is + // empty. + fwd fwdState } func (c *conn) logf(format string, args ...any) { @@ -497,7 +511,6 @@ func (srv *server) newConn() (*conn, error) { c := &conn{srv: srv} now := srv.now() c.connID = fmt.Sprintf("ssh-conn-%s-%02x", now.UTC().Format(tstime.BasicDateTTime), randBytes(5)) - fwdHandler := &gliderssh.ForwardedTCPHandler{} streamLocalFwdHandler := &gliderssh.ForwardedUnixHandler{} c.Server = &gliderssh.Server{ Version: "Tailscale", @@ -520,8 +533,6 @@ func (srv *server) newConn() (*conn, error) { "direct-streamlocal@openssh.com": gliderssh.DirectStreamLocalHandler, }, RequestHandlers: map[string]gliderssh.RequestHandler{ - "tcpip-forward": fwdHandler.HandleSSHRequest, - "cancel-tcpip-forward": fwdHandler.HandleSSHRequest, "streamlocal-forward@openssh.com": streamLocalFwdHandler.HandleSSHRequest, "cancel-streamlocal-forward@openssh.com": streamLocalFwdHandler.HandleSSHRequest, }, @@ -530,6 +541,7 @@ func (srv *server) newConn() (*conn, error) { maps.Copy(ss.RequestHandlers, gliderssh.DefaultRequestHandlers) maps.Copy(ss.ChannelHandlers, gliderssh.DefaultChannelHandlers) maps.Copy(ss.SubsystemHandlers, gliderssh.DefaultSubsystemHandlers) + c.wireReverseForwarding(ss) keys, err := getHostKeys(srv.lb.TailscaleVarRoot(), srv.logf) if err != nil { return nil, err @@ -571,43 +583,33 @@ func (c *conn) mayForwardLocalPortTo(ctx gliderssh.Context, destinationHost stri // mayForwardLocalUnixTo is the server-side handler for // direct-streamlocal@openssh.com (SSH -L with Unix sockets). It returns a // connection to the specified Unix domain socket path if forwarding is -// permitted, or an error if not. +// permitted, or an error if not. On unix the dial goes through +// conn.fwdDialUnix. func (c *conn) mayForwardLocalUnixTo(ctx gliderssh.Context, socketPath string) (net.Conn, error) { if sshDisableForwarding() { return nil, gliderssh.ErrRejected } - if c.finalAction != nil && c.finalAction.AllowLocalPortForwarding { - metricLocalPortForward.Add(1) - cb := gliderssh.NewLocalUnixForwardingCallback(c.unixForwardingOptions()) - return cb(ctx, socketPath) + if c.finalAction == nil || !c.finalAction.AllowLocalPortForwarding { + return nil, gliderssh.ErrRejected } - return nil, gliderssh.ErrRejected + metricLocalPortForward.Add(1) + return c.fwdDialUnix(ctx, socketPath) } // mayReverseUnixForwardTo is the server-side handler for // streamlocal-forward@openssh.com (SSH -R with Unix sockets). It returns a -// listener for the specified Unix domain socket path if reverse forwarding is -// permitted, or an error if not. +// listener for the specified Unix domain socket path if reverse forwarding +// is permitted, or an error if not. On unix the listener comes from +// conn.fwdListenUnix. func (c *conn) mayReverseUnixForwardTo(ctx gliderssh.Context, socketPath string) (net.Listener, error) { if sshDisableForwarding() { return nil, gliderssh.ErrRejected } - if c.finalAction != nil && c.finalAction.AllowRemotePortForwarding { - metricRemotePortForward.Add(1) - cb := gliderssh.NewReverseUnixForwardingCallback(c.unixForwardingOptions()) - return cb(ctx, socketPath) - } - return nil, gliderssh.ErrRejected -} - -// unixForwardingOptions returns the Unix forwarding options scoped to the -// authenticated local user. Socket paths are restricted to the user's home -// directory, /tmp, and /run/user/. -func (c *conn) unixForwardingOptions() gliderssh.UnixForwardingOptions { - return gliderssh.UnixForwardingOptions{ - AllowedDirectories: gliderssh.UserSocketDirectories(c.localUser.HomeDir, c.localUser.Uid), - BindUnlink: true, + if c.finalAction == nil || !c.finalAction.AllowRemotePortForwarding { + return nil, gliderssh.ErrRejected } + metricRemotePortForward.Add(1) + return c.fwdListenUnix(ctx, socketPath) } // sshPolicy returns the SSHPolicy for current node. diff --git a/ssh/tailssh/tailssh_integration_exitcodes_test.go b/ssh/tailssh/tailssh_integration_exitcodes_test.go index 4485b1a98..dca5a36f7 100644 --- a/ssh/tailssh/tailssh_integration_exitcodes_test.go +++ b/ssh/tailssh/tailssh_integration_exitcodes_test.go @@ -330,6 +330,15 @@ func TestLocalUnixForwardingHalfClose(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { ul.Close() }) + // The server dials through a child bound to the session user's + // credentials. Make the root-created socket and directory reachable + // by testuser. + if err := os.Chmod(socketDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.Chmod(socketPath, 0o666); err != nil { + t.Fatal(err) + } // Delayed-response service: read everything, sleep, then write. const response = "delayed-response-after-client-closes-write" diff --git a/ssh/tailssh/tailssh_integration_test.go b/ssh/tailssh/tailssh_integration_test.go index e17177821..f68605de1 100644 --- a/ssh/tailssh/tailssh_integration_test.go +++ b/ssh/tailssh/tailssh_integration_test.go @@ -580,6 +580,16 @@ func TestLocalUnixForwarding(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { ul.Close() }) + // The server dials through a child bound to the session user's + // credentials. Make the root-created socket and its directory + // traversable and connectable by testuser, modeling a service socket + // the user is allowed to reach. + if err := os.Chmod(socketDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.Chmod(socketPath, 0o666); err != nil { + t.Fatal(err) + } // The service echoes back whatever it receives, like an API server would. go func() { @@ -667,6 +677,13 @@ func TestReverseUnixForwarding(t *testing.T) { } t.Cleanup(func() { os.RemoveAll(socketDir) }) remoteSocketPath := filepath.Join(socketDir, "reverse.sock") + // The server-side socket is created by a child bound to the + // session user's credentials, so the directory must be writable and + // traversable by testuser. The test process, which is root, then + // connects to the user-owned socket. + if err := os.Chmod(socketDir, 0o777); err != nil { + t.Fatal(err) + } ln, err := cl.ListenUnix(remoteSocketPath) if err != nil { @@ -674,10 +691,15 @@ func TestReverseUnixForwarding(t *testing.T) { } t.Cleanup(func() { ln.Close() }) - // Verify the socket file was created on the server side. - if _, err := os.Stat(remoteSocketPath); err != nil { + // Verify the socket file was created on the server side, owned by + // the session user and readable and writable only by them. + fi, err := os.Stat(remoteSocketPath) + if err != nil { t.Fatalf("reverse forwarded socket not created: %s", err) } + if got := fi.Mode().Perm(); got != 0o600 { + t.Errorf("reverse socket mode = %o; want 0600", got) + } // Accept a connection from the tunnel (client side) and write data. want := "hello from reverse tunnel"