diff --git a/ssh/tailssh/connmonitor_windows.go b/ssh/tailssh/connmonitor_windows.go index 246055d9c..5c273dbdf 100644 --- a/ssh/tailssh/connmonitor_windows.go +++ b/ssh/tailssh/connmonitor_windows.go @@ -3,12 +3,87 @@ package tailssh -// connMonitorState is the Windows stand-in for the Unix process monitor's -// per-connection state. Windows has no monitor: sessions run under the -// target user's token directly (see process_windows.go), so there is -// nothing to track and nothing to close. -type connMonitorState struct{} +import ( + "errors" + "fmt" + "sync" -func (connMonitorState) close() {} + "tailscale.com/util/winutil" + "tailscale.com/util/winutil/s4u" +) + +// connMonitorState holds the Windows per-connection forwarding state. +// +// Windows has no monitor process like the unix platforms: session +// processes run under the target user's token directly (see +// process_windows.go), and forwarded sockets are dialed and bound by +// this tailscaled while impersonating the connection's user. The only +// per-connection resource is the S4U session used for that impersonation, +// created lazily on the first forward and closed at connection teardown. +// +// When tailscaled is not LocalSystem it already runs as the target user, +// so no impersonation session is needed and sess stays nil. +type connMonitorState struct { + mu sync.Mutex + closed bool + sess *s4u.Session // nil until the first forward as LocalSystem +} + +// close closes the impersonation session, if any, and refuses later +// forwards. It is called once at connection teardown. +func (s *connMonitorState) close() { + s.mu.Lock() + defer s.mu.Unlock() + s.closed = true + if s.sess != nil { + s.sess.Close() + s.sess = nil + } +} func (c *conn) closeConnMonitor() { c.monitor.close() } + +// fwdImpersonate runs fn with the connection user's Windows identity in +// effect, so that a forwarded socket's dial or bind is attributed to that +// user rather than to LocalSystem. As LocalSystem it impersonates the user +// through a lazily-created S4U session; otherwise this tailscaled already +// runs as the user and fn runs directly. +// +// Only the socket creation, connect, and bind inside fn need to run under +// the user. Later reads and writes on the returned connection may run +// unimpersonated, as they do with the unix monitor's children. +func (c *conn) fwdImpersonate(fn func()) error { + sess, err := c.fwdSession() + if err != nil { + return err + } + if sess == nil { + fn() + return nil + } + return sess.Do(fn) +} + +// fwdSession returns the connection's impersonation session, creating it on +// first use, or nil when tailscaled already runs as the target user. +func (c *conn) fwdSession() (*s4u.Session, error) { + if !winutil.IsCurrentProcessLocalSystem() { + // tailscaled is already the target user; see canSwitchToLocalUser. + return nil, nil + } + c.monitor.mu.Lock() + defer c.monitor.mu.Unlock() + if c.monitor.closed { + return nil, errors.New("ssh: connection is closing") + } + if c.monitor.sess != nil { + return c.monitor.sess, nil + } + lu := c.localUser + sess, err := s4u.Login(c.logf, s4uSourceName, &lu.User, s4u.CapImpersonateOnly) + if err != nil { + return nil, fmt.Errorf("ssh: S4U login to forward as %q: %w", lu.Username, err) + } + c.monitor.sess = sess + return sess, nil +} diff --git a/ssh/tailssh/fwd_windows.go b/ssh/tailssh/fwd_windows.go index 6ed567f9f..c1175d50f 100644 --- a/ssh/tailssh/fwd_windows.go +++ b/ssh/tailssh/fwd_windows.go @@ -1,38 +1,60 @@ // Copyright (c) Tailscale Inc & contributors // SPDX-License-Identifier: BSD-3-Clause -// The Windows forwarding seam. Windows has no process monitor: TCP -// forwarding is done by tailscaled itself with gliderssh's handlers, as on -// plan9. Unix socket forwarding and agent forwarding are not offered. The -// per-user socket directories the Unix rules allow don't exist on Windows, -// and OpenSSH for Windows's ssh-agent listens on a named pipe rather than -// an SSH_AUTH_SOCK socket, so there is nothing a forwarded socket could -// plug into. +// The Windows forwarding seam. +// +// Windows has no per-connection monitor process. Instead tailssh dials and +// binds forwarded TCP sockets itself, impersonating the connection's user +// for the socket, connect, and bind operations through conn.fwdImpersonate +// (see connmonitor_windows.go). That gives those sockets the user's +// identity for Windows Filtering Platform rules, as the unix monitor's +// user-credential children do, without a separate process. The socket's +// owning process is still tailscaled, so a connection-to-PID lookup names +// tailscaled; impersonation changes the identity the firewall authorizes, +// not process ownership. +// +// Unix socket forwarding and agent forwarding are not offered: +// +// - Unix socket forwarding (ssh -L/-R to an AF_UNIX path): the per-user +// socket directories the unix rules allow do not exist on Windows. +// - Agent forwarding: the socket and its SSH_AUTH_SOCK convention are +// Unix-only. OpenSSH for Windows forwards the agent over a named pipe +// instead, which gliderssh does not model. Supporting it would need a +// named-pipe agent listener and is left for later; see fwdListenAgent. package tailssh import ( + "context" "errors" + "math" "net" + "strconv" + "sync" gliderssh "github.com/tailscale/gliderssh" + gossh "golang.org/x/crypto/ssh" + "tailscale.com/types/logger" ) var errUnixForwardingUnsupported = errors.New("Unix socket forwarding is not supported on Windows") -// fwdDialUnix is the unix -L path. It is refused on Windows. +// fwdDialUnix is the unix -L path (direct-streamlocal). It is refused on +// Windows; see the file comment. func (c *conn) fwdDialUnix(ctx gliderssh.Context, socketPath string) (net.Conn, error) { return nil, errUnixForwardingUnsupported } -// fwdListenUnix is the unix -R path. It is refused on Windows. +// fwdListenUnix is the unix -R path (streamlocal-forward). It is refused on +// Windows; see the file comment. func (c *conn) fwdListenUnix(ctx gliderssh.Context, socketPath string) (net.Listener, error) { return nil, errUnixForwardingUnsupported } -// fwdListenAgent would return the agent-forwarding listener. Agent -// forwarding is not supported on Windows; see the file comment. +// fwdListenAgent would return the agent-forwarding listener and socket +// path. Agent forwarding is not supported on Windows; see the file +// comment for what adding it would take. func (c *conn) fwdListenAgent(ctx gliderssh.Context, lu *userMeta) (net.Listener, string, error) { return nil, "", errors.New("agent forwarding is not supported on Windows") } @@ -41,12 +63,175 @@ func (c *conn) fwdListenAgent(ctx gliderssh.Context, lu *userMeta) (net.Listener // agent forwarding directory. func removeAgentForwardingDir(dir string, lu *userMeta, logf logger.Logf) {} -// wireForwarding installs the reverse TCP forwarding handlers: gliderssh's -// ForwardedTCPHandler plus the mayReversePortForwardTo policy callback, -// as on plan9. +// wireForwarding installs the Windows direct and reverse TCP forwarding +// handlers. Both dial and bind as the connection's user through +// conn.fwdImpersonate. Unlike plan9, Windows does not use gliderssh's +// default handlers, which would dial and bind as LocalSystem. func (c *conn) wireForwarding(ss *gliderssh.Server) { - ss.ReversePortForwardingCallback = c.mayReversePortForwardTo - fwdHandler := &gliderssh.ForwardedTCPHandler{} - ss.RequestHandlers["tcpip-forward"] = fwdHandler.HandleSSHRequest - ss.RequestHandlers["cancel-tcpip-forward"] = fwdHandler.HandleSSHRequest + ss.ChannelHandlers["direct-tcpip"] = c.fwdDirectTCPIPHandler + h := &winFwdTCPHandler{conn: c} + ss.RequestHandlers["tcpip-forward"] = h.HandleSSHRequest + ss.RequestHandlers["cancel-tcpip-forward"] = h.HandleSSHRequest +} + +// fwdDirectTCPIPHandler serves TCP -L and SOCKS -D forwards, both +// direct-tcpip channels. Policy is checked before the dial, and the dial +// runs as the connection's user. The forwarding request supplies no user +// identity and cannot change the credentials chosen at authentication. +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 + } + dest := net.JoinHostPort(d.DestAddr, strconv.FormatUint(uint64(d.DestPort), 10)) + var dconn net.Conn + var dialErr error + if err := c.fwdImpersonate(func() { + var dialer net.Dialer + dconn, dialErr = dialer.DialContext(ctx, "tcp", dest) + }); err != nil { + newChan.Reject(gossh.ConnectionFailed, err.Error()) + return + } + if dialErr != nil { + newChan.Reject(gossh.ConnectionFailed, dialErr.Error()) + return + } + fwdAcceptAndBicopy(ctx, newChan, dconn) +} + +// winFwdTCPHandler serves "tcpip-forward" and "cancel-tcpip-forward" (TCP +// -R). The bind runs as the connection's user, so a port the user may not +// bind fails by Windows' own check rather than succeeding as LocalSystem. +// Bind addresses are loopback-only unless TS_SSH_FORWARD_GATEWAY_PORTS is +// set. It mirrors the unix fwdTCPHandler without the monitor. +type winFwdTCPHandler struct { + conn *conn + + mu sync.Mutex + forwards map[string]net.Listener +} + +// HandleSSHRequest serves tcpip-forward and cancel-tcpip-forward. +func (h *winFwdTCPHandler) 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") + } + listenAddr := net.JoinHostPort(bindAddr, strconv.Itoa(int(reqPayload.BindPort))) + var ln net.Listener + var lnErr error + if err := h.conn.fwdImpersonate(func() { + var lc net.ListenConfig + ln, lnErr = lc.Listen(ctx, "tcp", listenAddr) + }); err != nil { + h.conn.logf("ssh: reverse port forward: %v", err) + return false, []byte{} + } + if lnErr != nil { + h.conn.logf("ssh: reverse port forward bind %s:%d: %v", reqPayload.BindAddr, reqPayload.BindPort, lnErr) + 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() + // Close this listener when the SSH connection ends. Stop watching the + // connection when the accept loop exits, including on cancellation of + // this forward while the connection remains open. + stop := context.AfterFunc(ctx, func() { ln.Close() }) + go func() { + defer stop() + 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 + } } diff --git a/ssh/tailssh/fwdchild.go b/ssh/tailssh/fwdchild.go index a2100feee..aa5634f66 100644 --- a/ssh/tailssh/fwdchild.go +++ b/ssh/tailssh/fwdchild.go @@ -68,10 +68,6 @@ const fwdUmask = 0o177 // does not acknowledge receipt. const fwdResultAckWait = 30 * time.Second -// fwdRelayCloseDrainTimeout bounds delivery of queued client payload after a -// full close. A service that stops reading must not retain the relay forever. -const fwdRelayCloseDrainTimeout = 5 * 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; diff --git a/ssh/tailssh/fwdmonitor.go b/ssh/tailssh/fwdmonitor.go index 2a968f7c3..f83d21854 100644 --- a/ssh/tailssh/fwdmonitor.go +++ b/ssh/tailssh/fwdmonitor.go @@ -32,7 +32,6 @@ import ( "context" "errors" "fmt" - "io" "math" "net" "os" @@ -41,21 +40,15 @@ import ( "strings" "sync" "syscall" - "time" "golang.org/x/sys/unix" - "tailscale.com/envknob" "tailscale.com/types/logger" gliderssh "github.com/tailscale/gliderssh" gossh "golang.org/x/crypto/ssh" ) -// sshForwardGatewayPorts permits reverse TCP forwards to bind -// non-loopback addresses. It is the equivalent of sshd's GatewayPorts. -var sshForwardGatewayPorts = envknob.RegisterBool("TS_SSH_FORWARD_GATEWAY_PORTS") - // 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. @@ -166,26 +159,6 @@ func fwdDirectStreamLocalHandler(srv *gliderssh.Server, _ *gossh.ServerConn, new 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() - return - } - go func() { - gossh.DiscardRequests(reqs) - // CHANNEL_CLOSE ends service output, but the channel may still - // have buffered client payload to drain. Bound that final write - // rather than canceling both copy directions and losing the data. - dconn.SetWriteDeadline(time.Now().Add(fwdRelayCloseDrainTimeout)) - dconn.SetReadDeadline(time.Now()) - }() - fwdBicopy(ctx, ch, dconn) -} - // fwdDialUnix is the unix -L path (direct-streamlocal): dial socketPath // through a child with the local user's credentials. The child retains the // service socket and relays payload bytes over the returned socketpair end. @@ -252,51 +225,6 @@ type fwdTCPHandler struct { 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) { @@ -406,50 +334,6 @@ func (h *fwdTCPHandler) HandleSSHRequest(ctx gliderssh.Context, _ *gliderssh.Ser } } -// 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() - } -} - // 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. diff --git a/ssh/tailssh/fwdshared.go b/ssh/tailssh/fwdshared.go new file mode 100644 index 000000000..99188b97d --- /dev/null +++ b/ssh/tailssh/fwdshared.go @@ -0,0 +1,142 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build (linux && !android) || (darwin && !ios) || freebsd || openbsd || windows + +// The forwarding helpers shared by the platforms whose tailssh dials and +// binds forwarded TCP sockets itself, rather than through gliderssh's +// default handlers: the unix monitor platforms and Windows. plan9 keeps +// gliderssh's handlers and does not build this file. These helpers are +// identity-independent; the per-platform files decide whose credentials +// the dial or bind runs under. + +package tailssh + +import ( + "context" + "io" + "net" + "sync" + "time" + + gossh "golang.org/x/crypto/ssh" + + "tailscale.com/envknob" +) + +// sshForwardGatewayPorts permits reverse TCP forwards to bind +// non-loopback addresses. It is the equivalent of sshd's GatewayPorts. +var sshForwardGatewayPorts = envknob.RegisterBool("TS_SSH_FORWARD_GATEWAY_PORTS") + +// fwdRelayCloseDrainTimeout bounds delivery of queued client payload after a +// full close. A service that stops reading must not retain the relay forever. +const fwdRelayCloseDrainTimeout = 5 * time.Second + +// 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 +} + +// 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() + return + } + go func() { + gossh.DiscardRequests(reqs) + // CHANNEL_CLOSE ends service output, but the channel may still + // have buffered client payload to drain. Bound that final write + // rather than canceling both copy directions and losing the data. + dconn.SetWriteDeadline(time.Now().Add(fwdRelayCloseDrainTimeout)) + dconn.SetReadDeadline(time.Now()) + }() + fwdBicopy(ctx, ch, dconn) +} + +// 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() + } +}