diff --git a/ipn/ipnlocal/serve.go b/ipn/ipnlocal/serve.go index 41180739f..2093d7594 100644 --- a/ipn/ipnlocal/serve.go +++ b/ipn/ipnlocal/serve.go @@ -80,8 +80,11 @@ const ( // current etag of a resource. var ErrETagMismatch = errors.New("etag mismatch") -// ErrProxyToTailscaledSocket is returned when attempting to proxy -// to the tailscaled socket itself, which would create a loop. +// ErrProxyToTailscaledSocket is returned when attempting to proxy to the +// tailscaled socket itself. The LocalAPI authorizes a unix-socket caller by +// the peer credentials of the dialing process, which would be tailscaled +// running as root, so such a proxy would hand a remote client a +// root-authorized LocalAPI. var ErrProxyToTailscaledSocket = errors.New("cannot proxy to tailscaled socket") var serveHTTPContextKey ctxkey.Key[*serveHTTPContext] @@ -699,27 +702,20 @@ func (b *LocalBackend) tcpHandlerForServeTCP(tcph ipn.TCPPortHandlerView, dport return func(conn net.Conn) error { defer conn.Close() conn = b.meteredConnForService(conn, forVIPService) - // Never forward to tailscaled's own socket: the local API - // authorizes a unix-socket caller by the peer credentials of the - // dialing process, which here is tailscaled itself, so a forward - // would hand a remote peer a root-authorized local API. - socketPath, isUnix := strings.CutPrefix(backDst, "unix:") - if isUnix && b.isTailscaledSocket(socketPath) { - b.logf("localbackend: refusing TCP proxy on port %v (from %v) to the tailscaled socket %q", dport, srcAddr, socketPath) - return ErrProxyToTailscaledSocket - } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) var backConn net.Conn var err error - if isUnix { - var d net.Dialer - backConn, err = d.DialContext(ctx, "unix", socketPath) + if socketPath, isUnix := strings.CutPrefix(backDst, "unix:"); isUnix { + backConn, err = b.dialServeUnixSocket(ctx, socketPath) } else { backConn, err = b.dialer.SystemDial(ctx, "tcp", backDst) } cancel() if err != nil { - b.logf("localbackend: failed to TCP proxy port %v (from %v) to %s: %v", dport, srcAddr, backDst, err) + // dialServeUnixSocket already logged a refusal; don't double-log. + if !errors.Is(err, ErrProxyToTailscaledSocket) { + b.logf("localbackend: failed to TCP proxy port %v (from %v) to %s: %v", dport, srcAddr, backDst, err) + } return nil } defer backConn.Close() @@ -1033,6 +1029,49 @@ func (rp *reverseProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) { p.ServeHTTP(w, r) } +// dialServeUnixSocket dials a unix-socket serve/funnel backend. It returns +// ErrProxyToTailscaledSocket if the backend is tailscaled's own socket, +// which would give the caller a root-authorized LocalAPI. +// +// The configured path can be replaced by anyone who can write to its +// directory, so the socket is re-checked on every dial, not only at +// config time. dialServeUnixSocketSafe avoids re-resolving the path +// where the platform allows it. On the remaining dials, +// refuseIfConnectedToTailscaledSocket re-checks the connected peer. +func (b *LocalBackend) dialServeUnixSocket(ctx context.Context, socketPath string) (net.Conn, error) { + if b.isTailscaledSocket(socketPath) { + b.logf("serve: refusing to proxy to the tailscaled socket %q", socketPath) + return nil, ErrProxyToTailscaledSocket + } + conn, err := b.dialServeUnixSocketSafe(ctx, socketPath) + if err != nil { + return nil, err + } + if err := b.refuseIfConnectedToTailscaledSocket(conn); err != nil { + conn.Close() + return nil, err + } + return conn, nil +} + +// refuseIfConnectedToTailscaledSocket returns ErrProxyToTailscaledSocket +// if conn is a unix connection to the tailscaled socket. The peer address +// is the path the listening socket was bound to, not the path that was +// dialed, so the check still sees the tailscaled socket through a symlink +// swapped in before the dial. This check is best-effort: connections +// that have no determinable peer name are allowed. +func (b *LocalBackend) refuseIfConnectedToTailscaledSocket(conn net.Conn) error { + ua, ok := conn.RemoteAddr().(*net.UnixAddr) + if !ok || ua.Name == "" { + return nil + } + if ua.Name == b.sys.SocketPath || b.isTailscaledSocket(ua.Name) { + b.logf("serve: refusing connected unix backend peer %q: it is the tailscaled socket", ua.Name) + return ErrProxyToTailscaledSocket + } + return nil +} + // getTransport returns the Transport used for regular (non-GRPC) requests // to the backend. The Transport gets created lazily, at most once. func (rp *reverseProxy) getTransport() *http.Transport { @@ -1042,8 +1081,7 @@ func (rp *reverseProxy) getTransport() *http.Transport { dial := rp.lb.dialer.SystemDial if rp.socketPath != "" { dial = func(ctx context.Context, _, _ string) (net.Conn, error) { - var d net.Dialer - return d.DialContext(ctx, "unix", rp.socketPath) + return rp.lb.dialServeUnixSocket(ctx, rp.socketPath) } } @@ -1073,8 +1111,7 @@ func (rp *reverseProxy) getH2CTransport() http.RoundTripper { Protocols: &p, DialTLSContext: func(ctx context.Context, network string, addr string) (net.Conn, error) { if rp.socketPath != "" { - var d net.Dialer - return d.DialContext(ctx, "unix", rp.socketPath) + return rp.lb.dialServeUnixSocket(ctx, rp.socketPath) } return rp.lb.dialer.SystemDial(ctx, "tcp", rp.url.Host) }, diff --git a/ipn/ipnlocal/serve_test.go b/ipn/ipnlocal/serve_test.go index ee7599c62..74735effb 100644 --- a/ipn/ipnlocal/serve_test.go +++ b/ipn/ipnlocal/serve_test.go @@ -2301,3 +2301,38 @@ func TestSetServeConfigRejectsTailscaledSocket(t *testing.T) { t.Fatal("setServeConfigLocked accepted a forward to the tailscaled socket; want it refused") } } + +// TestReverseProxyRechecksTailscaledSocketPerDial verifies that a unix +// backend that becomes a symlink to the tailscaled socket after the +// handler was built is refused at dial time. +func TestReverseProxyRechecksTailscaledSocketPerDial(t *testing.T) { + b := newTestBackend(t) + sock := mkTempSocket(t) + b.sys.SocketPath = sock + benign := mkTempSocket(t) + + // Benign at config time, so the handler is built. + h, err := b.proxyHandlerForBackend("unix:" + benign) + if err != nil { + t.Fatalf("proxyHandlerForBackend(benign) = %v; want handler", err) + } + rp, ok := h.(*reverseProxy) + if !ok { + t.Fatalf("handler is %T; want *reverseProxy", h) + } + if _, err := rp.lb.dialServeUnixSocket(t.Context(), rp.socketPath); errors.Is(err, ErrProxyToTailscaledSocket) { + t.Fatalf("dial to the benign path was refused as the tailscaled socket") + } + + // The path is swapped for a symlink to the tailscaled socket after the + // handler exists; the next dial must catch it. + if err := os.Remove(benign); err != nil { + t.Fatal(err) + } + if err := os.Symlink(sock, benign); err != nil { + t.Fatal(err) + } + if _, err := rp.lb.dialServeUnixSocket(t.Context(), rp.socketPath); !errors.Is(err, ErrProxyToTailscaledSocket) { + t.Fatalf("dial after the symlink swap = %v; want ErrProxyToTailscaledSocket", err) + } +} diff --git a/ipn/ipnlocal/serve_unix_linux.go b/ipn/ipnlocal/serve_unix_linux.go new file mode 100644 index 000000000..bba2ae7dc --- /dev/null +++ b/ipn/ipnlocal/serve_unix_linux.go @@ -0,0 +1,101 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build linux && !ts_omit_serve + +package ipnlocal + +import ( + "context" + "net" + "path/filepath" + "strconv" + + "golang.org/x/sys/unix" +) + +// dialServeUnixSocketSafe dials socketPath. Where the platform allows +// it, it connects to a pinned descriptor instead of the path, so that +// swapping the path cannot retarget the connect. It returns +// ErrProxyToTailscaledSocket if the dialed socket is tailscaled's own. +// When no descriptor can be pinned, it dials the path directly. +func (b *LocalBackend) dialServeUnixSocketSafe(ctx context.Context, socketPath string) (net.Conn, error) { + if fd, ok := pinUnixSocketPath(socketPath); ok { + defer unix.Close(fd) + + // Check the inode held by the pin, which is the inode the + // connect below uses. + if b.isTailscaledSocketFd(fd) { + b.logf("serve: refusing to proxy to the tailscaled socket %q", socketPath) + return nil, ErrProxyToTailscaledSocket + } + conn, err := dialPinnedUnixSocket(ctx, fd) + if err == nil { + return conn, nil + } + // No usable /proc, or the pinned socket is gone. The peer is + // re-checked by the caller. + b.logf("serve: dialing %q by path: connecting through the pinned descriptor failed: %v", socketPath, err) + } + var d net.Dialer + return d.DialContext(ctx, "unix", socketPath) +} + +// pinUnixSocketPath returns an O_PATH descriptor referring to the file +// that socketPath resolves to, or ok=false if the kernel or the path do +// not support it (openat2(2), Linux 5.6 and newer). The resolution never +// follows magic links, and is restricted to the socket's parent directory +// when possible. +func pinUnixSocketPath(socketPath string) (fd int, ok bool) { + if dir, base := filepath.Split(filepath.Clean(socketPath)); dir != "" && base != "." && base != ".." && base != "/" { + if dirFD, err := unix.Open(dir, unix.O_PATH|unix.O_DIRECTORY|unix.O_CLOEXEC, 0); err == nil { + defer unix.Close(dirFD) + if fd, err := unix.Openat2(dirFD, base, &unix.OpenHow{ + Flags: unix.O_PATH | unix.O_CLOEXEC, + Resolve: unix.RESOLVE_BENEATH | + unix.RESOLVE_NO_MAGICLINKS, + }); err == nil { + return fd, true + } + } + } + fd, err := unix.Openat2(unix.AT_FDCWD, socketPath, &unix.OpenHow{ + Flags: unix.O_PATH | unix.O_CLOEXEC, + Resolve: unix.RESOLVE_NO_MAGICLINKS, + }) + if err != nil { + return -1, false + } + return fd, true +} + +// dialPinnedUnixSocket connects to the unix listener referred to by the +// O_PATH descriptor fd, via its /proc/self/fd name, so that the connect +// uses the pinned file and not the socket path. +func dialPinnedUnixSocket(ctx context.Context, fd int) (net.Conn, error) { + var d net.Dialer + return d.DialContext(ctx, "unix", "/proc/self/fd/"+strconv.Itoa(fd)) +} + +// isTailscaledSocketFd reports whether fd and the tailscaled socket +// (b.sys.SocketPath) refer to the same file, compared by device and inode. +// tailscaled's socket path is stat'ed on each call, so the directory holding +// it must not be writable by the attacker for this to be meaningful. +// +// st_dev and st_ino are filesystem-provided, and FUSE and some network +// filesystems can report zero or duplicate values. A match made that +// way still refuses the dial, so such values need no special handling. +func (b *LocalBackend) isTailscaledSocketFd(fd int) bool { + socketPath := b.sys.SocketPath + if socketPath == "" { + return false + } + var self, pinned unix.Stat_t + if err := unix.Stat(socketPath, &self); err != nil { + return false + } + if err := unix.Fstat(fd, &pinned); err != nil { + return false + } + return self.Dev == pinned.Dev && self.Ino == pinned.Ino +} diff --git a/ipn/ipnlocal/serve_unix_linux_test.go b/ipn/ipnlocal/serve_unix_linux_test.go new file mode 100644 index 000000000..e226256ea --- /dev/null +++ b/ipn/ipnlocal/serve_unix_linux_test.go @@ -0,0 +1,181 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build linux && !ts_omit_serve + +package ipnlocal + +import ( + "bytes" + "context" + "io" + "os" + "path/filepath" + "strconv" + "syscall" + "testing" + + "golang.org/x/sys/unix" +) + +// openat2Supported reports whether the kernel supports openat2(2) +// (Linux 5.6 and newer). +func openat2Supported() bool { + fd, err := unix.Openat2(unix.AT_FDCWD, "/", &unix.OpenHow{Flags: unix.O_PATH | unix.O_CLOEXEC}) + if err == nil { + unix.Close(fd) + return true + } + return false +} + +// TestPinUnixSocketPathResistsSymlinkSwap checks that replacing the dial +// path with a symlink after pinning does not change the pinned descriptor, +// and that a later pin of the swapped path refers to the tailscaled socket. +func TestPinUnixSocketPathResistsSymlinkSwap(t *testing.T) { + if !openat2Supported() { + t.Skip("kernel does not support openat2(2); the dial falls back to the pre/post checks") + } + + dir := unixSocketTestDir(t) + tsSock := filepath.Join(dir, "tailscaled.sock") + mustListenUnix(t, tsSock) + backend := filepath.Join(dir, "backend.sock") + serveUnixEchoListener(t, backend) + + b := newTestBackend(t) + b.sys.SocketPath = tsSock + + // Backend behind a sibling symlink. + alias := filepath.Join(dir, "alias.sock") + if err := os.Symlink("backend.sock", alias); err != nil { + t.Fatal(err) + } + + fd, ok := pinUnixSocketPath(alias) + if !ok { + t.Fatalf("pinUnixSocketPath(%q) did not pin", alias) + } + defer unix.Close(fd) + + if b.isTailscaledSocketFd(fd) { + t.Fatal("pin of the benign alias matches the tailscaled socket") + } + + // Replace the path with a symlink to the tailscaled socket after the pin. + if err := os.Remove(alias); err != nil { + t.Fatal(err) + } + if err := os.Symlink("tailscaled.sock", alias); err != nil { + t.Fatal(err) + } + + // The pinned descriptor is unchanged... + if b.isTailscaledSocketFd(fd) { + t.Fatal("pin followed the swap onto the tailscaled socket") + } + // ...and the connect through it reaches the benign backend, not the + // socket the path now leads to. + c, err := dialPinnedUnixSocket(context.Background(), fd) + if err != nil { + t.Fatalf("dial through the pinned descriptor: %v", err) + } + defer c.Close() + msg := []byte("hello backend") + if _, err := c.Write(msg); err != nil { + t.Fatal(err) + } + got := make([]byte, len(msg)) + if _, err := io.ReadFull(c, got); err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, msg) { + t.Fatalf("echo through pin = %q; want %q", got, msg) + } + + // A new pin of the swapped path is the tailscaled socket. + fd, ok = pinUnixSocketPath(alias) + if !ok { + t.Fatalf("pinUnixSocketPath(%q) on the swapped path did not pin", alias) + } + defer unix.Close(fd) + if !b.isTailscaledSocketFd(fd) { + t.Fatal("pin of the swapped alias is not the tailscaled socket") + } +} + +// TestPinUnixSocketPathAbsoluteSymlinkBackend checks that a backend behind +// an absolute symlink, which RESOLVE_BENEATH cannot resolve, is still +// pinned and dialable. +func TestPinUnixSocketPathAbsoluteSymlinkBackend(t *testing.T) { + if !openat2Supported() { + t.Skip("kernel does not support openat2(2); the dial falls back to the pre/post checks") + } + + dir := unixSocketTestDir(t) + backend := filepath.Join(dir, "backend.sock") + serveUnixEchoListener(t, backend) + + alias := filepath.Join(dir, "alias.sock") + if err := os.Symlink(backend, alias); err != nil { + t.Fatal(err) + } + + fd, ok := pinUnixSocketPath(alias) + if !ok { + t.Fatalf("pinUnixSocketPath(%q) did not pin", alias) + } + defer unix.Close(fd) + + c, err := dialPinnedUnixSocket(context.Background(), fd) + if err != nil { + t.Fatalf("dial through the pinned descriptor: %v", err) + } + defer c.Close() + msg := []byte("hello backend") + if _, err := c.Write(msg); err != nil { + t.Fatal(err) + } + got := make([]byte, len(msg)) + if _, err := io.ReadFull(c, got); err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, msg) { + t.Fatalf("echo through pin = %q; want %q", got, msg) + } +} + +// TestPinUnixSocketPathRefusesMagicLinks checks that a path that is a magic +// link (here, /proc/self/fd of the listener) is not pinned. +func TestPinUnixSocketPathRefusesMagicLinks(t *testing.T) { + if !openat2Supported() { + t.Skip("kernel does not support openat2(2); the dial falls back to the pre/post checks") + } + + dir := unixSocketTestDir(t) + tsSock := filepath.Join(dir, "tailscaled.sock") + ln := mustListenUnix(t, tsSock) + + sc, ok := ln.(syscall.Conn) + if !ok { + t.Fatalf("%T does not expose its descriptor", ln) + } + rc, err := sc.SyscallConn() + if err != nil { + t.Fatal(err) + } + var lnFD int + if err := rc.Control(func(fd uintptr) { lnFD = int(fd) }); err != nil { + t.Fatal(err) + } + + magic := filepath.Join(dir, "magic.sock") + if err := os.Symlink("/proc/self/fd/"+strconv.Itoa(lnFD), magic); err != nil { + t.Fatal(err) + } + + if fd, ok := pinUnixSocketPath(magic); ok { + unix.Close(fd) + t.Fatal("pinUnixSocketPath pinned through a magic link; want it refused") + } +} diff --git a/ipn/ipnlocal/serve_unix_other.go b/ipn/ipnlocal/serve_unix_other.go new file mode 100644 index 000000000..ffce7d097 --- /dev/null +++ b/ipn/ipnlocal/serve_unix_other.go @@ -0,0 +1,19 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build !linux && !ts_omit_serve + +package ipnlocal + +import ( + "context" + "net" +) + +// dialServeUnixSocketSafe dials socketPath directly. This platform has no +// openat2(2) equivalent, so swapping the path can still retarget the +// connect. The caller re-checks the connected peer. +func (b *LocalBackend) dialServeUnixSocketSafe(ctx context.Context, socketPath string) (net.Conn, error) { + var d net.Dialer + return d.DialContext(ctx, "unix", socketPath) +} diff --git a/ipn/ipnlocal/serve_unix_test.go b/ipn/ipnlocal/serve_unix_test.go index d2db63ff0..ded6caf7a 100644 --- a/ipn/ipnlocal/serve_unix_test.go +++ b/ipn/ipnlocal/serve_unix_test.go @@ -1,11 +1,13 @@ // Copyright (c) Tailscale Inc & contributors // SPDX-License-Identifier: BSD-3-Clause -//go:build unix +//go:build unix && !ts_omit_serve package ipnlocal import ( + "bytes" + "context" "errors" "fmt" "io" @@ -320,3 +322,135 @@ func TestTCPForwardUnixSocket(t *testing.T) { t.Fatal("handler did not finish in time") } } + +// unixSocketTestDir returns a directory for creating unix sockets, on a +// path short enough for sockaddr_un's sun_path limit. +func unixSocketTestDir(t *testing.T) string { + t.Helper() + dir, err := os.MkdirTemp("/tmp", "ts-serve-unix-*") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + return dir +} + +// mustListenUnix binds a unix listener at path, removing any existing file +// there first (mkTempSocket leaves a regular file behind). +func mustListenUnix(t *testing.T, path string) net.Listener { + t.Helper() + if err := os.Remove(path); err != nil && !os.IsNotExist(err) { + t.Fatal(err) + } + ln, err := net.Listen("unix", path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close(); os.Remove(path) }) + return ln +} + +// serveUnixEchoListener binds an echoing unix listener at path. +func serveUnixEchoListener(t *testing.T, path string) { + t.Helper() + ln := mustListenUnix(t, path) + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + go func() { + defer c.Close() + io.Copy(c, c) + }() + } + }() +} + +// TestRefuseIfConnectedToTailscaledSocket verifies the post-dial peer +// check: the peer of a unix connection is named by the path its listener +// was bound to, not the path dialed, so a connection to the tailscaled +// socket is refused, including one made through a symlink +func TestRefuseIfConnectedToTailscaledSocket(t *testing.T) { + dir := unixSocketTestDir(t) + tsSock := filepath.Join(dir, "tailscaled.sock") + mustListenUnix(t, tsSock) + + b := newTestBackend(t) + b.sys.SocketPath = tsSock + + // Skip if this platform does not name path-bound peers. + c, err := net.Dial("unix", tsSock) + if err != nil { + t.Fatal(err) + } + defer c.Close() + ua, ok := c.RemoteAddr().(*net.UnixAddr) + if !ok || ua.Name == "" { + t.Skipf("platform does not name unix socket peers (RemoteAddr = %v)", c.RemoteAddr()) + } + + if err := b.refuseIfConnectedToTailscaledSocket(c); !errors.Is(err, ErrProxyToTailscaledSocket) { + t.Fatalf("refuseIfConnectedToTailscaledSocket(tailscaled peer) = %v; want ErrProxyToTailscaledSocket", err) + } + + // A connection through a symlink still names the bound path. + alias := filepath.Join(dir, "alias.sock") + if err := os.Symlink(tsSock, alias); err != nil { + t.Fatal(err) + } + c, err = net.Dial("unix", alias) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if err := b.refuseIfConnectedToTailscaledSocket(c); !errors.Is(err, ErrProxyToTailscaledSocket) { + t.Fatalf("refuseIfConnectedToTailscaledSocket(symlinked tailscaled peer) = %v; want ErrProxyToTailscaledSocket", err) + } + + // A connection to any other socket is left alone. + benign := filepath.Join(dir, "benign.sock") + mustListenUnix(t, benign) + c, err = net.Dial("unix", benign) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if err := b.refuseIfConnectedToTailscaledSocket(c); err != nil { + t.Fatalf("refuseIfConnectedToTailscaledSocket(benign peer) = %v; want nil", err) + } +} + +// TestDialServeUnixSocketServesBenignBackend dials a benign unix backend +// end to end through dialServeUnixSocket and checks that traffic flows. +func TestDialServeUnixSocketServesBenignBackend(t *testing.T) { + dir := unixSocketTestDir(t) + // The backend is behind a symlink, as a serve config may reference it. + backend := filepath.Join(dir, "backend.sock") + serveUnixEchoListener(t, backend) + alias := filepath.Join(dir, "alias.sock") + if err := os.Symlink(backend, alias); err != nil { + t.Fatal(err) + } + + b := newTestBackend(t) + + conn, err := b.dialServeUnixSocket(context.Background(), alias) + if err != nil { + t.Fatalf("dialServeUnixSocket(%q) = %v; want connection", alias, err) + } + defer conn.Close() + + msg := []byte("hello backend") + if _, err := conn.Write(msg); err != nil { + t.Fatal(err) + } + got := make([]byte, len(msg)) + if _, err := io.ReadFull(conn, got); err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, msg) { + t.Fatalf("echo = %q; want %q", got, msg) + } +}