diff --git a/ssh/tailssh/fwdchild.go b/ssh/tailssh/fwdchild.go index 32db277a0..a0dcb6ca6 100644 --- a/ssh/tailssh/fwdchild.go +++ b/ssh/tailssh/fwdchild.go @@ -7,16 +7,16 @@ // be-child ssh-fwd", one per dial/listen op. // // The child runs as the connection's bound identity, applied by the -// monitor as SysProcAttr.Credential. A listener child binds and returns -// its descriptor over an inherited socketpair as one status line, then -// exits. A dial child instead returns one end of a private socketpair +// monitor as SysProcAttr.Credential. A listener or TCP dial child returns +// its socket descriptor over an inherited socketpair as one status line, +// then exits. A Unix dial child instead returns one end of a private socketpair // and a lifetime pipe writer, and stays alive to relay bytes to the dialed // service as the bound user. Closing the lifetime pipe terminates the relay // independently of data-socket half-closes. // // The result protocol, from child to monitor over the socketpair, is one -// short newline-terminated line with one descriptor for a listener or two -// for a dial (data socket and lifetime pipe writer): +// short newline-terminated line with one descriptor for a listener or TCP +// dial, or two for a Unix dial (data socket and lifetime pipe writer): // // ok [payload] success, with the agent socket path or the // bound TCP address as the payload @@ -25,7 +25,7 @@ // // After a successful send the child holds its descriptor copy until the // monitor closes the result channel, its receipt acknowledgment. Listener -// children then exit; dial children keep relaying through the private +// and TCP dial children then exit; Unix dial children relay through the private // socketpair until the connection closes. 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 @@ -50,6 +50,7 @@ import ( "path/filepath" "runtime" "slices" + "strconv" "strings" "syscall" "time" @@ -100,7 +101,7 @@ func init() { // the child via argv. type fwdChildSpec struct { op string // "dial" or "listen" - net string // "unix" or "tcp" for listen. Dial is always unix + net string // "unix" or "tcp" addr string // socket path for unix, address for tcp. Empty for agent unlink bool // listen unix only: unlink-if-owned pre-step agent bool // listen only: create the agent-forwarding socket @@ -164,8 +165,8 @@ func fwdSpawnChild(m *monitor, spec fwdChildSpec) (*exec.Cmd, *net.UnixConn, err } // fwdReadResult reads the forwarding child's status line and result -// descriptors from the socketpair, bounded by the deadline. Dial replies -// carry a data socket and a lifetime pipe; listener replies carry one socket. +// descriptors from the socketpair, bounded by the deadline. Unix dial replies +// carry a data socket and lifetime pipe; other replies carry one socket. func fwdReadResult(c *net.UnixConn, deadline time.Time, wantFDs int) (ok bool, payload string, fds []int, err error) { if err := c.SetReadDeadline(deadline); err != nil { return false, "", nil, err @@ -230,7 +231,7 @@ func parseFwdArgs(args []string) (fwdArgs, error) { flags := flag.NewFlagSet("ssh-fwd", flag.ContinueOnError) flags.StringVar(&fa.op, "op", "", "the op to perform: dial or listen") - flags.StringVar(&fa.net, "net", "", "network: unix or tcp (dial is unix-only)") + flags.StringVar(&fa.net, "net", "", "network: unix or tcp") flags.StringVar(&fa.addr, "addr", "", "absolute socket path (unix) or address (tcp)") flags.StringVar(&unlink, "unlink", "", `listen unix only: pre-bind unlink policy, "if-owned"`) flags.BoolVar(&fa.agent, "agent", false, "listen only: create the agent-forwarding socket") @@ -246,11 +247,8 @@ func parseFwdArgs(args []string) (fwdArgs, error) { if fa.agent { return fa, errors.New("dial does not take --agent") } - if fa.net != "unix" { - return fa, fmt.Errorf("dial is unix-only, got --net=%q", fa.net) - } - if fa.addr == "" || !filepath.IsAbs(fa.addr) { - return fa, fmt.Errorf("dial: --addr must be an absolute unix socket path, got %q", fa.addr) + if err := validateFwdDial(fa.net, fa.addr); err != nil { + return fa, err } case "listen": switch { @@ -279,8 +277,36 @@ func parseFwdArgs(args []string) (fwdArgs, error) { return fa, nil } +// validateFwdDial validates the dial shape on both sides of the child spawn. +// TCP destinations may be hostnames or IP literals; resolution happens in the +// credentialed child, not in the privileged monitor. +func validateFwdDial(network, addr string) error { + switch network { + case "unix": + if !filepath.IsAbs(addr) { + return fmt.Errorf("dial: addr must be an absolute unix socket path, got %q", addr) + } + case "tcp": + // Only validate the host:port framing and numeric port here. + // net.DialTimeout in the credentialed child validates/resolves the + // host. Keep its hostname, scoped-IPv6 and empty-host semantics; + // do not resolve names in the privileged monitor. + _, port, err := net.SplitHostPort(addr) + if err != nil { + return fmt.Errorf("dial tcp: %w", err) + } + n, err := strconv.ParseUint(port, 10, 16) + if err != nil || n == 0 { + return fmt.Errorf("dial tcp: port %q must be between 1 and 65535", port) + } + default: + return fmt.Errorf("dial: unsupported network %q", network) + } + return nil +} + // beFwdChild is the entrypoint of the "tailscaled be-child ssh-fwd" -// subcommand. It is the born-unprivileged dial relay or listener child. +// subcommand. It is the born-unprivileged dialer, Unix relay or listener child. func beFwdChild(args []string) error { fa, err := parseFwdArgs(args) if err != nil { @@ -301,7 +327,7 @@ func beFwdChild(args []string) error { var relay *net.UnixConn var service *net.UnixConn var lifetimeRead, lifetimeWrite *os.File - if fa.op == "dial" { + if fa.op == "dial" && fa.net == "unix" { f, relay, service, err = fwdDialRelay(fa.addr) if err == nil { defer relay.Close() @@ -345,7 +371,7 @@ func beFwdChild(args []string) error { _, ackErr := c.Read(ack[:]) f.Close() if relay == nil { - return nil // listener children exit after the handoff + return nil // listener and TCP dial children exit after the handoff } lifetimeWrite.Close() c.Close() @@ -411,12 +437,26 @@ func fwdSendResult(c *net.UnixConn, line string, files ...*os.File) error { return err } -// fwdChildWork performs a listener op and returns its socket as an +// fwdChildWork performs a TCP dial or listener op and returns its socket as an // *os.File plus a short status payload. The caller sends the file's // descriptor to the monitor and then closes the file. The payload is the // agent socket path, or the bound TCP address. func fwdChildWork(fa fwdArgs) (*os.File, string, error) { switch { + case fa.op == "dial" && fa.net == "tcp": + // Resolve and create/connect the socket with the bound user's + // credentials. Passing the descriptor back does not change its + // kernel socket owner, including for UID-based firewall rules. + // Unlike Unix sockets, TCP has no per-message SCM_CREDENTIALS, + // so a persistent user-credential relay is unnecessary. + conn, err := net.DialTimeout("tcp", fa.addr, monFwdOpDeadline) + if err != nil { + return nil, "", err + } + defer conn.Close() + f, err := conn.(*net.TCPConn).File() + return f, "", err + case fa.op == "listen" && fa.agent: // Agent-forwarding socket. See fwdUmask and ListenAgent. The // dir's cleanup is the caller's. diff --git a/ssh/tailssh/fwdchild_test.go b/ssh/tailssh/fwdchild_test.go index 3ec81670d..d89ab221f 100644 --- a/ssh/tailssh/fwdchild_test.go +++ b/ssh/tailssh/fwdchild_test.go @@ -745,7 +745,8 @@ func zombieChildrenOf(ppid int) int { // shapes carry no identity keys on the wire. func TestFwdRequestsCarryNoIdentity(t *testing.T) { for _, f := range []rpcFrame{ - rpcDialReq(1, "/tmp/x.sock"), + rpcDialReq(1, "unix", "/tmp/x.sock"), + rpcDialReq(6, "tcp", "localhost:443"), rpcListenReq(2, "unix", "/tmp/x.sock", false, false), rpcListenReq(3, "unix", "/tmp/x.sock", true, false), rpcListenReq(4, "tcp", "127.0.0.1:0", false, false), @@ -763,14 +764,16 @@ func TestFwdRequestsCarryNoIdentity(t *testing.T) { } } - // The ops refuse unsupported shapes (dial is unix-only and absolute; - // listen net must be unix, tcp, or agent), and the channel stays - // healthy afterwards. + // The ops refuse unsupported networks and malformed addresses, and + // the channel stays healthy afterwards. mc := startFwdTestMonitor(t, os.Getuid(), os.Getgid(), testGroups(t)) ctx, cancel := testCtx() defer cancel() for _, f := range []rpcFrame{ - {Op: opDial, Net: "tcp", Addr: "127.0.0.1:1"}, + {Op: opDial, Net: "udp", Addr: "127.0.0.1:1"}, + {Op: opDial, Net: "tcp", Addr: "127.0.0.1:65536"}, + {Op: opDial, Net: "tcp", Addr: "localhost:http"}, + {Op: opDial, Net: "tcp", Addr: "missing-port"}, {Op: opDial, Net: "unix", Addr: "relative.sock"}, {Op: opDial, Net: "unix", Addr: "@/abstract"}, {Op: opListen, Net: "udp", Addr: "x"}, diff --git a/ssh/tailssh/fwdmonitor.go b/ssh/tailssh/fwdmonitor.go index 038a595be..4f899209c 100644 --- a/ssh/tailssh/fwdmonitor.go +++ b/ssh/tailssh/fwdmonitor.go @@ -7,6 +7,9 @@ // dialed and bound by one-shot children of the per-connection ssh-monitor // running with the authenticated local user's credentials. // +// - TCP -L/-D, direct-tcpip: policy stays in tailscaled, then name +// resolution and dialing run in a one-shot child as the bound user. +// The connected socket is handed back without changing its kernel owner. // - unix -L, direct-streamlocal: the lexical allowlist check stays in // tailscaled as coarse policy, then the dial and service-side payload // writes run as the user in a relay child. See conn.fwdAllowedSocketPath @@ -30,6 +33,7 @@ import ( "errors" "fmt" "io" + "math" "net" "os" "path/filepath" @@ -230,6 +234,44 @@ func (c *conn) fwdAllowedSocketPath(socketPath string) (string, error) { return "", fmt.Errorf("socket path %q is not in an allowed directory: %w", cleaned, gliderssh.ErrRejected) } +// fwdDirectTCPIPHandler serves both TCP -L and SOCKS -D forwards: both use +// RFC 4254 direct-tcpip channels. Policy is checked before spawning a monitor +// or dialer. The child resolves/dials using the local account selected during +// SSH authentication (c.localUser): its UID, GID and supplementary groups are +// fixed when the per-connection monitor is spawned. The forwarding request +// supplies no user identity and cannot change those credentials. +func (c *conn) fwdDirectTCPIPHandler(srv *gliderssh.Server, _ *gossh.ServerConn, newChan gossh.NewChannel, ctx gliderssh.Context) { + var d struct { + DestAddr string + DestPort uint32 + OriginAddr string + OriginPort uint32 + } + if err := gossh.Unmarshal(newChan.ExtraData(), &d); err != nil { + newChan.Reject(gossh.ConnectionFailed, "error parsing forward data: "+err.Error()) + return + } + if d.DestPort == 0 || d.DestPort > math.MaxUint16 { + newChan.Reject(gossh.ConnectionFailed, "destination port must be between 1 and 65535") + return + } + if srv.LocalPortForwardingCallback == nil || !srv.LocalPortForwardingCallback(ctx, d.DestAddr, d.DestPort) { + newChan.Reject(gossh.Prohibited, "port forwarding is disabled") + return + } + mc, err := c.fwdMonitor() + if err != nil { + newChan.Reject(gossh.ConnectionFailed, err.Error()) + return + } + dconn, err := mc.DialTCP(ctx, net.JoinHostPort(d.DestAddr, strconv.FormatUint(uint64(d.DestPort), 10))) + if err != nil { + newChan.Reject(gossh.ConnectionFailed, err.Error()) + return + } + fwdAcceptAndBicopy(ctx, newChan, dconn) +} + // fwdDirectStreamLocalHandler keeps channel lifetime separate from data EOF. // gliderssh's generic forwarding loop uses the connection context, which // does not end when just this SSH channel closes. The request stream closes @@ -261,6 +303,13 @@ func fwdDirectStreamLocalHandler(srv *gliderssh.Server, _ *gossh.ServerConn, new } return } + fwdAcceptAndBicopy(ctx, newChan, dconn) +} + +// fwdAcceptAndBicopy owns dconn, accepting the channel and copying data until +// completion or closure. Channel EOF permits a response; full channel closure +// stops waiting for the service while allowing buffered client payload to drain. +func fwdAcceptAndBicopy(ctx context.Context, newChan gossh.NewChannel, dconn net.Conn) { ch, reqs, err := newChan.Accept() if err != nil { dconn.Close() @@ -545,11 +594,11 @@ func fwdHalfCloseWrite(c io.ReadWriteCloser) { } } -// wireReverseForwarding installs the conn's reverse TCP forwarding -// request handlers. On unix they are fwdTCPHandler's, binding through -// the monitor. It also installs the local Unix handler that ends relay -// children on SSH channel closure independently of connection closure. -func (c *conn) wireReverseForwarding(ss *gliderssh.Server) { +// wireForwarding installs the conn's direct forwarding and reverse TCP +// handlers. Socket creation goes through the credential-bound monitor children; +// direct forwarding also handles channel closure independently of the connection. +func (c *conn) wireForwarding(ss *gliderssh.Server) { + ss.ChannelHandlers["direct-tcpip"] = c.fwdDirectTCPIPHandler ss.ChannelHandlers["direct-streamlocal@openssh.com"] = fwdDirectStreamLocalHandler h := &fwdTCPHandler{conn: c} ss.RequestHandlers["tcpip-forward"] = h.HandleSSHRequest diff --git a/ssh/tailssh/fwdplan9.go b/ssh/tailssh/fwdplan9.go index acb300b41..9c6a211a2 100644 --- a/ssh/tailssh/fwdplan9.go +++ b/ssh/tailssh/fwdplan9.go @@ -99,10 +99,10 @@ func removeAgentForwardingDir(dir string, lu *userMeta, logf logger.Logf) { // closeFwdMonitor is a no-op on plan9 because there is no monitor. func (c *conn) closeFwdMonitor() {} -// wireReverseForwarding installs plan9's reverse TCP forwarding +// wireForwarding 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) { +func (c *conn) wireForwarding(ss *gliderssh.Server) { ss.ReversePortForwardingCallback = c.mayReversePortForwardTo fwdHandler := &gliderssh.ForwardedTCPHandler{} ss.RequestHandlers["tcpip-forward"] = fwdHandler.HandleSSHRequest diff --git a/ssh/tailssh/fwdrelay_linux_test.go b/ssh/tailssh/fwdrelay_linux_test.go index c5852b770..3e0e3c16c 100644 --- a/ssh/tailssh/fwdrelay_linux_test.go +++ b/ssh/tailssh/fwdrelay_linux_test.go @@ -55,7 +55,7 @@ func TestFwdDialRelayCloseReapsChild(t *testing.T) { } else { // Model the descriptor cleanup of a reply whose caller has // abandoned it: no connection wrapper is ever constructed. - _, fds, err := mc.call(ctx, rpcDialReq(0, path)) + _, fds, err := mc.call(ctx, rpcDialReq(0, "unix", path)) if err != nil { t.Fatal(err) } diff --git a/ssh/tailssh/fwdtcp_linux_test.go b/ssh/tailssh/fwdtcp_linux_test.go new file mode 100644 index 000000000..65289f8c6 --- /dev/null +++ b/ssh/tailssh/fwdtcp_linux_test.go @@ -0,0 +1,200 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build linux && !android + +package tailssh + +import ( + "encoding/binary" + "fmt" + "io" + "net" + "net/netip" + "os" + "strconv" + "strings" + "testing" + "time" + + "tailscale.com/tstest" +) + +// TestFwdTCPFullStackSocketOwner checks the UID Linux associates with the +// outgoing socket, as used by UID-based firewall rules. TCP has no Unix-style +// per-message credentials; inspect the client half of the exact connection. +func TestFwdTCPFullStackSocketOwner(t *testing.T) { + if os.Getuid() != 0 { + t.Skip("requires root to distinguish the daemon from the mapped user") + } + client, lu := newFwdTCPTestClient(t, true) + boundUID, err := strconv.Atoi(lu.Uid) + if err != nil || boundUID == os.Getuid() { + t.Fatalf("test requires a distinct bound UID: %q, %v", lu.Uid, err) + } + for _, network := range []string{"tcp4", "tcp6"} { + t.Run(network, func(t *testing.T) { + addr := "127.0.0.1:0" + if network == "tcp6" { + addr = "[::1]:0" + } + ln, err := net.Listen(network, addr) + if err != nil { + if network == "tcp6" { + t.Skipf("IPv6 unavailable: %v", err) + } + t.Fatal(err) + } + defer ln.Close() + ln.(*net.TCPListener).SetDeadline(time.Now().Add(10 * time.Second)) + + // A direct dial from this process is a control for the UID + // observation, independent of the SSH forwarding code. + direct, err := net.Dial(network, ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer direct.Close() + control, err := ln.Accept() + if err != nil { + t.Fatal(err) + } + defer control.Close() + uid, _, err := tcpPeerSocketOwner(control) + if err != nil || uid != os.Getuid() { + t.Fatalf("direct socket UID = %d, err %v; want %d", uid, err, os.Getuid()) + } + direct.Close() + control.Close() + + forward, err := client.Dial("tcp", ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer forward.Close() + service, err := ln.Accept() + if err != nil { + t.Fatal(err) + } + defer service.Close() + uid, inode, err := tcpPeerSocketOwner(service) + if err != nil || uid != boundUID || inode == "0" { + t.Errorf("forwarded socket UID = %d, inode %q, err %v; want mapped UID %d and a live socket (daemon UID %d)", uid, inode, err, boundUID, os.Getuid()) + } + forward.Close() + // Keep the service open and silent. Closing only this SSH + // channel must release the daemon's socket, not just half-close + // it. An orphaned TCP socket has inode 0 in /proc/net/tcp*. + if err := tstest.WaitFor(5*time.Second, func() error { + _, inode, err := tcpPeerSocketOwner(service) + if os.IsNotExist(err) || err == nil && inode == "0" { + return nil + } + return fmt.Errorf("forwarding socket still held: inode %q, err %v", inode, err) + }); err != nil { + t.Error(err) + } + if _, _, err := client.SendRequest("keepalive@openssh.com", true, nil); err != nil { + t.Fatalf("SSH transport after channel close: %v", err) + } + }) + } +} + +// tcpPeerSocketOwner finds the peer's outgoing socket by its exact local and +// remote endpoints. It is only used with loopback listeners in this process's +// network namespace. The inode distinguishes an open socket from an orphan. +func tcpPeerSocketOwner(service net.Conn) (uid int, inode string, err error) { + local := service.RemoteAddr().(*net.TCPAddr).AddrPort() + remote := service.LocalAddr().(*net.TCPAddr).AddrPort() + path := "/proc/net/tcp" + if local.Addr().Is6() { + path += "6" + } + encode := func(ap netip.AddrPort) string { + var ip strings.Builder + b := ap.Addr().AsSlice() + for i := 0; i < len(b); i += 4 { + fmt.Fprintf(&ip, "%08X", binary.NativeEndian.Uint32(b[i:i+4])) + } + return fmt.Sprintf("%s:%04X", ip.String(), ap.Port()) + } + data, err := os.ReadFile(path) + if err != nil { + return 0, "", err + } + for line := range strings.SplitSeq(string(data), "\n") { + fields := strings.Fields(line) + if len(fields) > 9 && fields[1] == encode(local) && fields[2] == encode(remote) { + uid, err := strconv.Atoi(fields[7]) + return uid, fields[9], err + } + } + return 0, "", os.ErrNotExist +} + +// TestFwdTCPDialChildExits verifies that TCP does not retain a relay process: +// the credentialed child exits and is reaped while the handed-off socket is +// still usable for bidirectional data and half-close. +func TestFwdTCPDialChildExits(t *testing.T) { + uid, gid, groups := fwdBoundIdentity(t) + mc := startFwdTestMonitor(t, uid, gid, groups) + ln, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer ln.Close() + ln.(*net.TCPListener).SetDeadline(time.Now().Add(10 * time.Second)) + ctx, cancel := testCtx() + defer cancel() + client, err := mc.DialTCP(ctx, ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer client.Close() + service, err := ln.Accept() + if err != nil { + t.Fatal(err) + } + defer service.Close() + childrenPath := fmt.Sprintf("/proc/%d/task/%d/children", mc.Pid(), mc.Pid()) + if err := tstest.WaitFor(5*time.Second, func() error { + b, err := os.ReadFile(childrenPath) + if err != nil { + return err + } + if len(strings.Fields(string(b))) != 0 { + return fmt.Errorf("TCP dial child still present: %s", b) + } + return nil + }); err != nil { + t.Fatal(err) + } + gotUID, inode, err := tcpPeerSocketOwner(service) + if err != nil || gotUID != uid || inode == "0" { + t.Fatalf("socket after child exit: UID %d, inode %q, err %v; want UID %d", gotUID, inode, err, uid) + } + service.SetDeadline(time.Now().Add(5 * time.Second)) + client.SetDeadline(time.Now().Add(5 * time.Second)) + done := make(chan error, 1) + go func() { + _, err := io.Copy(service, service) + service.Close() + done <- err + }() + if _, err := io.WriteString(client, "after child exit"); err != nil { + t.Fatal(err) + } + if err := client.CloseWrite(); err != nil { + t.Fatal(err) + } + if b, err := io.ReadAll(client); err != nil || string(b) != "after child exit" { + t.Fatalf("echo after child exit = %q, %v", b, err) + } + if err := <-done; err != nil { + t.Fatal(err) + } + if err := mc.Ping(ctx); err != nil { + t.Fatal(err) + } +} diff --git a/ssh/tailssh/fwdtcp_test.go b/ssh/tailssh/fwdtcp_test.go new file mode 100644 index 000000000..48967c359 --- /dev/null +++ b/ssh/tailssh/fwdtcp_test.go @@ -0,0 +1,328 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build (linux && !android) || (darwin && !ios) || freebsd || openbsd + +package tailssh + +import ( + "errors" + "io" + "math" + "net" + "net/netip" + "strconv" + "strings" + "testing" + "time" + + gliderssh "github.com/tailscale/gliderssh" + gossh "golang.org/x/crypto/ssh" + "golang.org/x/sys/unix" + "tailscale.com/envknob" + "tailscale.com/net/memnet" + "tailscale.com/tailcfg" + testssh "tailscale.com/tempfork/sshtest/ssh" + "tailscale.com/tstest" +) + +func newFwdTCPTestClient(t *testing.T, allow bool) (*testssh.Client, *userMeta) { + t.Helper() + lu := fwdTestIdentity(t) + exe := makeExecutableReachable(t) + t.Setenv("TS_TEST_SSH_FWD_PREFIX", strings.Join(testFwdPrefix, " ")) + tstest.Replace(t, &monitorSpawnPrefix, testMonitorPrefix) + s := &server{ + logf: tstest.WhileTestRunningLogger(t), tailscaledPath: exe, + lb: &localState{ + sshEnabled: true, varRoot: t.TempDir(), + matchingRule: &tailcfg.SSHRule{ + SSHUsers: map[string]string{"alice": lu.Username}, + Action: &tailcfg.SSHAction{Accept: true, AllowLocalPortForwarding: allow}, + Principals: []*tailcfg.SSHPrincipal{{Any: true}}, + }, + }, + } + sc, dc := memnet.NewTCPConn(netip.MustParseAddrPort("100.100.100.101:2231"), netip.MustParseAddrPort("100.100.100.102:22"), 1024) + if err := sc.SetDeadline(time.Now().Add(30 * time.Second)); err != nil { + t.Fatal(err) + } + handleDone := make(chan error, 1) + go func() { handleDone <- s.HandleSSHConn(dc) }() + t.Cleanup(func() { + sc.Close() + dc.Close() + s.Shutdown() + select { + case err := <-handleDone: + if err != nil { + t.Errorf("HandleSSHConn: %v", err) + } + case <-time.After(10 * time.Second): + t.Error("SSH handler did not finish") + } + }) + cl, chans, reqs, err := testssh.NewClientConn(sc, sc.RemoteAddr().String(), &testssh.ClientConfig{ + User: "alice", HostKeyCallback: testssh.InsecureIgnoreHostKey(), + }) + if err != nil { + t.Fatal(err) + } + client := testssh.NewClient(cl, chans, reqs) + t.Cleanup(func() { client.Close() }) + return client, lu +} + +// Both fixed TCP -L forwards and SOCKS -D requests arrive as direct-tcpip +// channels. In particular, SOCKS domain-name destinations must be resolved +// in the dialer child, so exercise a hostname as well as IPv4 and IPv6. +func TestFwdTCPFullStackHalfClose(t *testing.T) { + client, _ := newFwdTCPTestClient(t, true) + for _, kind := range []string{"ipv4", "ipv6", "hostname"} { + for _, serviceFirst := range []bool{false, true} { + name := kind + "/client-half-close" + if serviceFirst { + name = kind + "/service-half-close" + } + t.Run(name, func(t *testing.T) { + network, addr := "tcp4", "127.0.0.1:0" + if kind == "ipv6" { + network, addr = "tcp6", "[::1]:0" + } + ln, err := net.Listen(network, addr) + if err != nil { + if kind == "ipv6" { + t.Skipf("IPv6 unavailable: %v", err) + } + t.Fatal(err) + } + defer ln.Close() + ln.(*net.TCPListener).SetDeadline(time.Now().Add(10 * time.Second)) + host, port, err := net.SplitHostPort(ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + if kind == "hostname" { + host = "localhost" + } + portNum, err := strconv.Atoi(port) + if err != nil { + t.Fatal(err) + } + ch, reqs, err := client.OpenChannel("direct-tcpip", tcpForwardPayload(host, uint32(portNum))) + if err != nil { + t.Fatal(err) + } + defer ch.Close() + go testssh.DiscardRequests(reqs) + service, err := ln.(*net.TCPListener).AcceptTCP() + if err != nil { + t.Fatal(err) + } + defer service.Close() + service.SetDeadline(time.Now().Add(10 * time.Second)) + var first, second interface { + io.ReadWriteCloser + CloseWrite() error + } = ch, service + if serviceFirst { + first, second = second, first + } + if _, err := io.WriteString(first, "request"); err != nil { + t.Fatal(err) + } + if err := first.CloseWrite(); err != nil { + t.Fatal(err) + } + if b, err := io.ReadAll(second); err != nil || string(b) != "request" { + t.Fatalf("request = %q, %v", b, err) + } + if _, err := io.WriteString(second, "response"); err != nil { + t.Fatal(err) + } + if err := second.CloseWrite(); err != nil { + t.Fatal(err) + } + if b, err := io.ReadAll(first); err != nil || string(b) != "response" { + t.Fatalf("response after half-close = %q, %v", b, err) + } + }) + } + } +} + +func tcpForwardPayload(host string, port uint32) []byte { + return testssh.Marshal(&struct { + DestAddr string + DestPort uint32 + OriginAddr string + OriginPort uint32 + }{host, port, "127.0.0.1", 12345}) +} + +func TestFwdTCPDenied(t *testing.T) { + for _, mode := range []string{"policy", "disabled"} { + t.Run(mode, func(t *testing.T) { + if mode == "disabled" { + envknob.SetenvForTest(t, "TS_SSH_DISABLE_FORWARDING", "true") + } + client, _ := newFwdTCPTestClient(t, mode != "policy") + ln, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer ln.Close() + forward, err := client.Dial("tcp", ln.Addr().String()) + if err == nil { + forward.Close() + t.Fatal("forwarding unexpectedly allowed") + } + var openErr *testssh.OpenChannelError + if !errors.As(err, &openErr) || openErr.Reason != testssh.Prohibited { + t.Fatalf("forwarding error = %v; want Prohibited", err) + } + ln.(*net.TCPListener).SetDeadline(time.Now().Add(100 * time.Millisecond)) + if c, err := ln.Accept(); err == nil { + c.Close() + t.Fatal("denied forward still dialed the service") + } else if ne, ok := err.(net.Error); !ok || !ne.Timeout() { + t.Fatal(err) + } + }) + } +} + +func TestFwdTCPDialFailure(t *testing.T) { + client, _ := newFwdTCPTestClient(t, true) + // Bind without listening, reserving an endpoint that refuses connections + // without racing another process's reuse of a closed listener's port. + fd, err := unix.Socket(unix.AF_INET, unix.SOCK_STREAM, 0) + if err != nil { + t.Fatal(err) + } + defer unix.Close(fd) + unix.CloseOnExec(fd) + if err := unix.Bind(fd, &unix.SockaddrInet4{Addr: [4]byte{127, 0, 0, 1}}); err != nil { + t.Fatal(err) + } + sa, err := unix.Getsockname(fd) + if err != nil { + t.Fatal(err) + } + port := uint32(sa.(*unix.SockaddrInet4).Port) + for _, payload := range [][]byte{ + {1}, + tcpForwardPayload("127.0.0.1", 0), + tcpForwardPayload("127.0.0.1", 65536), + tcpForwardPayload("127.0.0.1", math.MaxUint32), + tcpForwardPayload("127.0.0.1", port), + } { + ch, _, err := client.OpenChannel("direct-tcpip", payload) + if err == nil { + ch.Close() + t.Fatal("invalid or refused dial unexpectedly succeeded") + } + var openErr *testssh.OpenChannelError + if !errors.As(err, &openErr) || openErr.Reason != testssh.ConnectionFailed { + t.Fatalf("dial error = %v; want ConnectionFailed", err) + } + } + // A failed dial must not tear down the shared monitor or SSH connection. + ln, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer ln.Close() + forward, err := client.Dial("tcp", ln.Addr().String()) + if err != nil { + t.Fatalf("dial after failures: %v", err) + } + defer forward.Close() + ln.(*net.TCPListener).SetDeadline(time.Now().Add(5 * time.Second)) + service, err := ln.Accept() + if err != nil { + t.Fatal(err) + } + service.Close() +} + +// TestFwdTCPPortRange checks the SSH wire range before policy evaluation or +// child creation. Valid endpoints reach the policy callback, which denies them +// here so no actual destination needs to be listening on boundary ports. +func TestFwdTCPPortRange(t *testing.T) { + for _, port := range []uint32{0, 1, math.MaxUint16, math.MaxUint16 + 1, math.MaxUint32} { + t.Run(strconv.FormatUint(uint64(port), 10), func(t *testing.T) { + valid := port >= 1 && port <= math.MaxUint16 + policyCalled := false + srv := &gliderssh.Server{ + LocalPortForwardingCallback: func(_ gliderssh.Context, _ string, gotPort uint32) bool { + policyCalled = true + if gotPort != port { + t.Errorf("policy port = %d; want %d", gotPort, port) + } + return false + }, + } + ch := &tcpPortTestChannel{t: t, payload: tcpForwardPayload("localhost", port)} + c := new(conn) + c.fwdDirectTCPIPHandler(srv, nil, ch, nil) + wantReason := gossh.ConnectionFailed + if valid { + wantReason = gossh.Prohibited + } + if !ch.rejected || ch.reason != wantReason || policyCalled != valid { + t.Fatalf("rejected=%v reason=%v policyCalled=%v; want reason=%v policyCalled=%v", ch.rejected, ch.reason, policyCalled, wantReason, valid) + } + if c.fwdMonitorIfAny() != nil { + t.Fatal("rejected request spawned a monitor") + } + }) + } +} + +type tcpPortTestChannel struct { + t *testing.T + payload []byte + rejected bool + reason gossh.RejectionReason +} + +func (c *tcpPortTestChannel) ChannelType() string { return "direct-tcpip" } +func (c *tcpPortTestChannel) ExtraData() []byte { return c.payload } +func (c *tcpPortTestChannel) Accept() (gossh.Channel, <-chan *gossh.Request, error) { + c.t.Fatal("unexpected channel acceptance") + return nil, nil, errors.New("unexpected channel acceptance") +} +func (c *tcpPortTestChannel) Reject(reason gossh.RejectionReason, _ string) error { + c.rejected, c.reason = true, reason + return nil +} + +func TestParseFwdArgsTCPDial(t *testing.T) { + for _, tt := range []struct { + addr string + ok bool + }{ + {"127.0.0.1:443", true}, + {"[::1]:443", true}, + {"[fe80::1%testzone]:443", true}, // scope validation belongs to the child dialer + {"localhost:443", true}, + {"unresolved.example.invalid:443", true}, // no DNS lookup during shape validation + {":1", true}, // retain net.Dial's empty-host behavior + {"localhost:65535", true}, + {":0", false}, + {"", false}, + {"localhost", false}, + {"localhost:http", false}, + {"localhost:65536", false}, + {"localhost:-1", false}, + {"::1:443", false}, + } { + t.Run(tt.addr, func(t *testing.T) { + _, err := parseFwdArgs([]string{"--op=dial", "--net=tcp", "--addr=" + tt.addr, "--fd=3"}) + if (err == nil) != tt.ok { + t.Fatalf("parse TCP dial %q: %v; want success=%v", tt.addr, err, tt.ok) + } + }) + } +} diff --git a/ssh/tailssh/monitor.go b/ssh/tailssh/monitor.go index 70b426311..71f081e2e 100644 --- a/ssh/tailssh/monitor.go +++ b/ssh/tailssh/monitor.go @@ -12,7 +12,7 @@ // children are the incubator in incubator.go, spawned with the // monitor's credentials because the incubator needs root to exec // login and su and to register the login session. Forwarding children -// in fwdchild.go are dial relays and one-shot bind workers, spawned with the +// in fwdchild.go are Unix dial relays and one-shot TCP dial/bind workers, spawned with the // connection user's credentials. // // The connection's identity, the uid, gid, and groups of its @@ -62,7 +62,7 @@ const ( // Every child leads its own group, so pgid equals pid. A oneshot // child, a dialer or listener, reports its outcome in its op's reply, // and its exit is reaped silently by the sweep after its SIGCHLD. -// A dialer stays alive to relay bytes after reporting its outcome. +// A Unix dialer stays alive to relay bytes after reporting its outcome. type monChild struct { pgid int // the child's process group. Equal to its pid. id int64 // exec request ID, or zero for a forwarding child @@ -517,21 +517,15 @@ func killGroup(pgid int, sig unix.Signal) error { return unix.Kill(-pgid, sig) } -// handleDial serves the dial op. A relay child dials the unix socket -// with the connection's bound identity, as documented in fwdchild.go. -// The reply relays a socketpair descriptor and a lifetime pipe writer to -// tailscaled; the child relays payload as the bound user until the pipe -// closes or both data directions finish. +// handleDial serves the dial op with the connection's bound identity. +// Unix dials return a private data socket and lifetime pipe for a relay child; +// TCP dials return the connected socket and the child exits after handoff. func (m *monitor) handleDial(f rpcFrame) { - if f.Net != "unix" { - m.reply(rpcErrReply(f.ID, opDial, fmt.Errorf("dial: network %q not supported; dial is unix-only", f.Net))) + if err := validateFwdDial(f.Net, f.Addr); err != nil { + m.reply(rpcErrReply(f.ID, opDial, err)) return } - if f.Addr == "" || !filepath.IsAbs(f.Addr) { - m.reply(rpcErrReply(f.ID, opDial, errors.New("dial: addr must be an absolute unix socket path"))) - return - } - m.fwdOp(f.ID, opDial, fwdChildSpec{op: "dial", net: "unix", addr: f.Addr}, func(string) rpcFrame { + m.fwdOp(f.ID, opDial, fwdChildSpec{op: "dial", net: f.Net, addr: f.Addr}, func(string) rpcFrame { return rpcOKReply(f.ID, opDial) }) } @@ -619,7 +613,7 @@ func (m *monitor) fwdOp(id int64, op string, spec fwdChildSpec, reply func(paylo child := &monChild{pgid: cmd.Process.Pid, oneshot: true} m.children[cmd.Process.Pid] = child wantFDs := 1 - if op == opDial { + if op == opDial && spec.net == "unix" { wantFDs = 2 // data socket and lifetime pipe writer } ok, payload, fds, rerr := fwdReadResult(result, start.Add(monFwdOpDeadline), wantFDs) @@ -635,8 +629,8 @@ func (m *monitor) fwdOp(id int64, op string, spec fwdChildSpec, reply func(paylo m.reply(rpcErrReply(id, op, errors.New(payload))) return } - // Listener children exit after the descriptor handoff; dial children - // keep relaying until the connection closes. The sweep silently reaps + // Listener and TCP dial children exit after the handoff; Unix dial + // children relay until the connection closes. The sweep silently reaps // each child after its SIGCHLD. m.replyFD(reply(payload), fds...) } diff --git a/ssh/tailssh/monitor_client.go b/ssh/tailssh/monitor_client.go index 5a6973886..55de1b99a 100644 --- a/ssh/tailssh/monitor_client.go +++ b/ssh/tailssh/monitor_client.go @@ -316,7 +316,7 @@ func (mc *monitorClient) Signal(ctx context.Context, child monitorProcess, sig s // are acknowledged to the monitor on receipt, releasing its held copies. // See the monitor_rpc.go header. func (mc *monitorClient) Dial(ctx context.Context, addr string) (*monitorDialConn, error) { - _, fds, err := mc.call(ctx, rpcDialReq(0, addr)) + _, fds, err := mc.call(ctx, rpcDialReq(0, "unix", addr)) if err != nil { return nil, err } @@ -333,6 +333,32 @@ func (mc *monitorClient) Dial(ctx context.Context, addr string) (*monitorDialCon return &monitorDialConn{UnixConn: uc, lifetime: lifetime}, nil } +// DialTCP resolves and dials addr through a one-shot child running with the +// connection's bound identity. The kernel socket owner is preserved when the +// connected TCP socket is handed back to tailscaled. +func (mc *monitorClient) DialTCP(ctx context.Context, addr string) (*net.TCPConn, error) { + _, fds, err := mc.call(ctx, rpcDialReq(0, "tcp", addr)) + if err != nil { + return nil, err + } + if len(fds) != 1 { + closeFds(fds) + return nil, fmt.Errorf("ssh-monitor: TCP dial reply carried %d fds, want 1", len(fds)) + } + f := os.NewFile(uintptr(fds[0]), "ssh-fwd-tcp") + defer f.Close() + nc, err := net.FileConn(f) + if err != nil { + return nil, err + } + tc, ok := nc.(*net.TCPConn) + if !ok { + nc.Close() + return nil, fmt.Errorf("ssh-monitor: TCP dial returned %T", nc) + } + return tc, nil +} + // monitorDialConn preserves UnixConn's half-close methods, but a full Close // also ends the relay even if the service remains open and silent. Discarding // an unclaimed RPC reply closes the lifetime fd too, without needing a wrapper. diff --git a/ssh/tailssh/monitor_rpc.go b/ssh/tailssh/monitor_rpc.go index c5435ab3a..b3881fa3a 100644 --- a/ssh/tailssh/monitor_rpc.go +++ b/ssh/tailssh/monitor_rpc.go @@ -52,7 +52,7 @@ import ( // Monitor RPC operations. const ( - opDial = "dial" // request {net:"unix", addr}. reply {ok} + data socket and lifetime pipe writer + opDial = "dial" // request {net:"unix"|"tcp", addr}. reply {ok} + socket (and lifetime pipe writer for unix) opListen = "listen" // request {net:"unix"|"tcp", addr, unlink?, agent?}. reply {ok, path} + listener fd opExec = "exec" // request {argv, env, dir?, ctty?, envfd?, fds:0-4} + SCM_RIGHTS fds. reply {ok, pid, childID} opSignal = "signal" // request {pid, childID, sig}. reply {ok} @@ -103,7 +103,7 @@ type rpcFrame struct { Op string `json:"op"` // dial and listen requests. - Net string `json:"net,omitempty"` // dial: always "unix". listen: "unix" or "tcp" + Net string `json:"net,omitempty"` // dial and listen: "unix" or "tcp" Addr string `json:"addr,omitempty"` // target address to dial or bind Unlink bool `json:"unlink,omitzero"` Agent bool `json:"agent,omitzero"` // listen: create the agent-forwarding socket @@ -142,8 +142,8 @@ func rpcPingReq(id int64) rpcFrame { return rpcFrame{ID: id, Op: opPing} } -func rpcDialReq(id int64, addr string) rpcFrame { - return rpcFrame{ID: id, Op: opDial, Net: "unix", Addr: addr} +func rpcDialReq(id int64, network, addr string) rpcFrame { + return rpcFrame{ID: id, Op: opDial, Net: network, Addr: addr} } func rpcListenReq(id int64, network, addr string, unlink, agent bool) rpcFrame { @@ -186,8 +186,8 @@ func rpcFdAckReq(replyID int64) rpcFrame { // maxFdsForOp reports the maximum number of SCM_RIGHTS descriptors a // frame of op may carry in either direction. Exec carries child stdio. -// Dial replies carry a data socket and lifetime pipe writer; listen replies -// carry the bound socket. +// Unix dial replies carry a data socket and lifetime pipe writer; TCP dial +// and listen replies carry one socket. func maxFdsForOp(op string) int { switch op { case opExec: diff --git a/ssh/tailssh/monitor_rpc_test.go b/ssh/tailssh/monitor_rpc_test.go index 98782e704..9f33ebf09 100644 --- a/ssh/tailssh/monitor_rpc_test.go +++ b/ssh/tailssh/monitor_rpc_test.go @@ -109,7 +109,7 @@ func TestMonitorRPCFdRoundTrip(t *testing.T) { client, server := rpcTestPair(t) peer, passed := fdPair(t) - if err := client.writeFrame(rpcDialReq(7, "/run/user/1000/test.sock"), passed); err != nil { + if err := client.writeFrame(rpcDialReq(7, "unix", "/run/user/1000/test.sock"), passed); err != nil { t.Fatal(err) } unix.Close(passed) // per sendFds, the sender may close after the write @@ -458,7 +458,7 @@ func TestMonitorRPCLineCapAndNUL(t *testing.T) { client, server := rpcTestPair(t) // Sender side: oversized frames are refused. - if err := client.writeFrame(rpcDialReq(1, strings.Repeat("x", rpcMaxLine))); err == nil { + if err := client.writeFrame(rpcDialReq(1, "unix", strings.Repeat("x", rpcMaxLine))); err == nil { t.Fatal("oversized write accepted") } @@ -601,7 +601,7 @@ func TestMonitorRPCMultiplex(t *testing.T) { mu.Lock() var err error if i%5 == 0 { - err = client.writeFrame(rpcDialReq(int64(i+1), "/tmp/monitor-rpc-test.sock")) + err = client.writeFrame(rpcDialReq(int64(i+1), "unix", "/tmp/monitor-rpc-test.sock")) } else { err = client.writeFrame(rpcPingReq(int64(i + 1))) } diff --git a/ssh/tailssh/tailssh.go b/ssh/tailssh/tailssh.go index 7f56bbedc..5706c6d88 100644 --- a/ssh/tailssh/tailssh.go +++ b/ssh/tailssh/tailssh.go @@ -251,10 +251,10 @@ func (srv *server) OnPolicyChange() { // channels concurrently. At which point any of the following can be called // in any order. // - c.handleSessionPostSSHAuth -// - c.mayForwardLocalPortTo followed by gliderssh.DirectTCPIPHandler +// - c.mayForwardLocalPortTo followed by a credentialed TCP dial (gliderssh on plan9) // - c.mayForwardLocalUnixTo, the unix -L dial // - c.mayReverseUnixForwardTo, the unix -R bind -// - c.wireReverseForwarding's "tcpip-forward" handlers, the TCP -R bind +// - c.wireForwarding's "tcpip-forward" handlers, the TCP -R bind type conn struct { *gliderssh.Server srv *server @@ -623,7 +623,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) + c.wireForwarding(ss) keys, err := getHostKeys(srv.lb.TailscaleVarRoot(), srv.logf) if err != nil { return nil, err diff --git a/ssh/tailssh/tailssh_policy_test.go b/ssh/tailssh/tailssh_policy_test.go index 0a68787ac..2190fc2c7 100644 --- a/ssh/tailssh/tailssh_policy_test.go +++ b/ssh/tailssh/tailssh_policy_test.go @@ -247,6 +247,11 @@ func TestSSHRevokeMidSessionClosesConn(t *testing.T) { // established forward. A pure extension, false to true, leaves the conn // alive. func TestSSHNarrowingClosesForwardOnlyConn(t *testing.T) { + // TCP -L dials now use the credentialed monitor child, like -R binds. + exe := makeExecutableReachable(t) + t.Setenv("TS_TEST_SSH_FWD_PREFIX", strings.Join(testFwdPrefix, " ")) + tstest.Replace(t, &monitorSpawnPrefix, testMonitorPrefix) + // A local TCP service to -L forward to. svc, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { @@ -277,6 +282,7 @@ func TestSSHNarrowingClosesForwardOnlyConn(t *testing.T) { rule: newPolicyRule(allow, lu), } s, client, _ := dialPolicyConn(t, p) + s.tailscaledPath = exe // Establish a live -L forward with no session channel anywhere. fwd, err := client.Dial("tcp", svc.Addr().String()) @@ -296,7 +302,7 @@ func TestSSHNarrowingClosesForwardOnlyConn(t *testing.T) { p.setRule(newPolicyRule(&tailcfg.SSHAction{Accept: true}, lu)) s.OnPolicyChange() - // The conn closes. The established forward dies and new sessions fail. + // Both the established forward and its SSH transport close. fwdErr := make(chan error, 1) go func() { _, err := fwd.Read(got) @@ -310,9 +316,18 @@ func TestSSHNarrowingClosesForwardOnlyConn(t *testing.T) { case <-time.After(10 * time.Second): t.Fatal("established forward not torn down after narrowing") } - eventually(t, 10*time.Second, "connection not closed after narrowing", func() bool { - return sessionFails(client) - }) + // Wait for transport shutdown rather than racing NewSession against + // the test client's mux teardown (which can strand a channel-open wait). + clientDone := make(chan error, 1) + go func() { clientDone <- client.Wait() }() + select { + case err := <-clientDone: + if err == nil { + t.Fatal("client Wait returned nil after policy revocation") + } + case <-time.After(10 * time.Second): + t.Fatal("connection not closed after narrowing") + } } // TestSSHRevokeClosesReverseForwardListener pins the forwarding-only