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/<uid>. 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 <[email protected]>
This commit is contained in:
James Tucker authored and James Tucker committed 2026-10-25 20:08:58 -07:00
1 parent de16943cbf
commit eba00ab363
13 files changed
+2217 -110

No files matched your search

+37 -3
View File
@@ -19,6 +19,14 @@
// err <reason> 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
}
+536
View File
@@ -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/<uid>. 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
}
File diff suppressed because it is too large. Load diff
+120
View File
@@ -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/<uid>.
func (c *conn) unixForwardingOptions() gliderssh.UnixForwardingOptions {
return gliderssh.UnixForwardingOptions{
AllowedDirectories: gliderssh.UserSocketDirectories(c.localUser.HomeDir, c.localUser.Uid),
BindUnlink: true,
}
}
+43 -12
View File
@@ -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.
+13
View File
@@ -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 {
+17
View File
@@ -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.
+2
View File
@@ -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
+17 -44
View File
@@ -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)
}
+101 -22
View File
@@ -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)
}
}
}
+29 -27
View File
@@ -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) {
"[email protected]": gliderssh.DirectStreamLocalHandler,
},
RequestHandlers: map[string]gliderssh.RequestHandler{
"tcpip-forward": fwdHandler.HandleSSHRequest,
"cancel-tcpip-forward": fwdHandler.HandleSSHRequest,
"[email protected]": streamLocalFwdHandler.HandleSSHRequest,
"[email protected]": 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
// [email protected] (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
// [email protected] (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/<uid>.
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.
@@ -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"
+24 -2
View File
@@ -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"