ipn/ipnlocal,cmd/tailscale/cli: support unix socket targets for TCP serve
Allow `tailscale serve --tcp <port> unix:/path/to/socket` and `tailscale serve --tls-terminated-tcp <port> unix:/path/to/socket` to forward TCP connections to a Unix domain socket. Previously only host:port targets were supported for TCP serve mode. Updates #20161 Signed-off-by: ayanamist <ayanamist@gmail.com>
This commit is contained in:
@@ -92,11 +92,16 @@ type Target struct {
|
||||
|
||||
// If Protocol is ProtoFile, then Destination is a file path.
|
||||
// If Protocol is ProtoTUN, then Destination is empty.
|
||||
// If Protocol is ProtoHTTP, ProtoHTTPS, ProtoHTTPSInsecure, ProtoTCP, or
|
||||
// ProtoTLSTerminatedTCP and Destination starts with "unix:", it is a Unix
|
||||
// socket path (e.g. "unix:/var/run/app.sock" or "unix:relative.sock").
|
||||
// Otherwise, it is a host.
|
||||
Destination string
|
||||
|
||||
// If Protocol is not ProtoFile or ProtoTUN, then DestinationPorts is the
|
||||
// set of ports on which to connect to the host referred to by Destination.
|
||||
// For unix socket targets (Destination starting with "unix:"),
|
||||
// DestinationPorts is unused and left at the zero value.
|
||||
DestinationPorts tailcfg.PortRange
|
||||
}
|
||||
|
||||
@@ -133,13 +138,22 @@ func (t *Target) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
|
||||
t.Destination = target
|
||||
t.DestinationPorts = tailcfg.PortRange{}
|
||||
case ProtoHTTP, ProtoHTTPS, ProtoHTTPSInsecure, ProtoTCP, ProtoTLSTerminatedTCP:
|
||||
host, portRange, err := tailcfg.ParseHostPortRange(rest)
|
||||
if err != nil {
|
||||
return err
|
||||
if unixPath, ok := strings.CutPrefix(rest, "unix:"); ok {
|
||||
if unixPath == "" {
|
||||
return errors.New("unix socket path cannot be empty")
|
||||
}
|
||||
t.Protocol = ServiceProtocol(proto)
|
||||
t.Destination = rest
|
||||
t.DestinationPorts = tailcfg.PortRange{}
|
||||
} else {
|
||||
host, portRange, err := tailcfg.ParseHostPortRange(rest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t.Protocol = ServiceProtocol(proto)
|
||||
t.Destination = host
|
||||
t.DestinationPorts = portRange
|
||||
}
|
||||
t.Protocol = ServiceProtocol(proto)
|
||||
t.Destination = host
|
||||
t.DestinationPorts = portRange
|
||||
default:
|
||||
return errors.New("unsupported protocol")
|
||||
}
|
||||
@@ -155,7 +169,12 @@ func (t *Target) MarshalText() ([]byte, error) {
|
||||
case ProtoTUN:
|
||||
out = "TUN"
|
||||
case ProtoHTTP, ProtoHTTPS, ProtoHTTPSInsecure, ProtoTCP, ProtoTLSTerminatedTCP:
|
||||
out = fmt.Sprintf("%s://%s", t.Protocol, net.JoinHostPort(t.Destination, t.DestinationPorts.String()))
|
||||
if strings.HasPrefix(t.Destination, "unix:") {
|
||||
// Unix socket: serialize as e.g. "tcp://unix:/path/to/sock"
|
||||
out = fmt.Sprintf("%s://%s", t.Protocol, t.Destination)
|
||||
} else {
|
||||
out = fmt.Sprintf("%s://%s", t.Protocol, net.JoinHostPort(t.Destination, t.DestinationPorts.String()))
|
||||
}
|
||||
default:
|
||||
return nil, errors.New("unsupported protocol")
|
||||
}
|
||||
@@ -261,8 +280,19 @@ func loadConfigV0(json []byte, forService string) (*ServicesConfigFile, error) {
|
||||
}
|
||||
foundTUN = true
|
||||
} else {
|
||||
if ppr.Ports.Last-ppr.Ports.First != target.DestinationPorts.Last-target.DestinationPorts.First {
|
||||
return nil, fmt.Errorf("service %q: source and destination port ranges must be of equal size", svcName.String())
|
||||
// Unix socket targets (Destination starting with "unix:" on an
|
||||
// HTTP/HTTPS/HTTPSInsecure/TCP/TLSTerminatedTCP inbound protocol)
|
||||
// don't have a destination port range; skip the equality check.
|
||||
isUnixSocket := strings.HasPrefix(target.Destination, "unix:") &&
|
||||
(target.Protocol == ProtoHTTP ||
|
||||
target.Protocol == ProtoHTTPS ||
|
||||
target.Protocol == ProtoHTTPSInsecure ||
|
||||
target.Protocol == ProtoTCP ||
|
||||
target.Protocol == ProtoTLSTerminatedTCP)
|
||||
if !isUnixSocket {
|
||||
if ppr.Ports.Last-ppr.Ports.First != target.DestinationPorts.Last-target.DestinationPorts.First {
|
||||
return nil, fmt.Errorf("service %q: source and destination port ranges must be of equal size", svcName.String())
|
||||
}
|
||||
}
|
||||
foundNonTUN = true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
// Copyright (c) Tailscale Inc & contributors
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
|
||||
//go:build !ts_omit_serve
|
||||
|
||||
package conffile
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"tailscale.com/tailcfg"
|
||||
)
|
||||
|
||||
func TestTargetUnixSocketRoundtrip(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
serialized string
|
||||
want Target
|
||||
}{
|
||||
{
|
||||
name: "tcp_unix_socket",
|
||||
serialized: "tcp://unix:/var/run/app.sock",
|
||||
want: Target{
|
||||
Protocol: ProtoTCP,
|
||||
Destination: "unix:/var/run/app.sock",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "tls_terminated_tcp_unix_socket",
|
||||
serialized: "tls-terminated-tcp://unix:/var/run/app.sock",
|
||||
want: Target{
|
||||
Protocol: ProtoTLSTerminatedTCP,
|
||||
Destination: "unix:/var/run/app.sock",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "tcp_unix_socket_relative",
|
||||
serialized: "tcp://unix:relative.sock",
|
||||
want: Target{
|
||||
Protocol: ProtoTCP,
|
||||
Destination: "unix:relative.sock",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "http_unix_socket",
|
||||
serialized: "http://unix:/var/run/app.sock",
|
||||
want: Target{
|
||||
Protocol: ProtoHTTP,
|
||||
Destination: "unix:/var/run/app.sock",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "https_unix_socket",
|
||||
serialized: "https://unix:/var/run/app.sock",
|
||||
want: Target{
|
||||
Protocol: ProtoHTTPS,
|
||||
Destination: "unix:/var/run/app.sock",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "https_insecure_unix_socket",
|
||||
serialized: "https+insecure://unix:/var/run/app.sock",
|
||||
want: Target{
|
||||
Protocol: ProtoHTTPSInsecure,
|
||||
Destination: "unix:/var/run/app.sock",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "http_unix_socket_relative",
|
||||
serialized: "http://unix:relative.sock",
|
||||
want: Target{
|
||||
Protocol: ProtoHTTP,
|
||||
Destination: "unix:relative.sock",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "tcp_host_port",
|
||||
serialized: "tcp://localhost:5432",
|
||||
want: Target{
|
||||
Protocol: ProtoTCP,
|
||||
Destination: "localhost",
|
||||
DestinationPorts: tailcfg.PortRange{First: 5432, Last: 5432},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Test unmarshal
|
||||
var got Target
|
||||
if err := got.UnmarshalJSON([]byte(`"` + tt.serialized + `"`)); err != nil {
|
||||
t.Fatalf("UnmarshalJSON(%q) failed: %v", tt.serialized, err)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Errorf("UnmarshalJSON(%q) = %+v, want %+v", tt.serialized, got, tt.want)
|
||||
}
|
||||
|
||||
// Test marshal roundtrip
|
||||
marshaled, err := tt.want.MarshalText()
|
||||
if err != nil {
|
||||
t.Fatalf("MarshalText() failed: %v", err)
|
||||
}
|
||||
if string(marshaled) != tt.serialized {
|
||||
t.Errorf("MarshalText() = %q, want %q", marshaled, tt.serialized)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -823,7 +823,10 @@ func (v TCPPortHandlerView) HTTPS() bool { return v.ж.HTTPS }
|
||||
// It is mutually exclusive with TCPForward.
|
||||
func (v TCPPortHandlerView) HTTP() bool { return v.ж.HTTP }
|
||||
|
||||
// TCPForward is the IP:port to forward TCP connections to.
|
||||
// TCPForward is the address to forward TCP connections to.
|
||||
// It is either a host:port (e.g. "127.0.0.1:3128", "localhost:5432")
|
||||
// or a Unix socket path prefixed with "unix:"
|
||||
// (e.g. "unix:/var/run/app.sock" or "unix:relative.sock").
|
||||
// Whether or not TLS is terminated by tailscaled depends on
|
||||
// TerminateTLS.
|
||||
//
|
||||
|
||||
+15
-2
@@ -673,7 +673,14 @@ func (b *LocalBackend) tcpHandlerForServeTCP(tcph ipn.TCPPortHandlerView, dport
|
||||
defer conn.Close()
|
||||
conn = b.meteredConnForService(conn, forVIPService)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
backConn, err := b.dialer.SystemDial(ctx, "tcp", backDst)
|
||||
var backConn net.Conn
|
||||
var err error
|
||||
if socketPath, ok := strings.CutPrefix(backDst, "unix:"); ok {
|
||||
var d net.Dialer
|
||||
backConn, err = d.DialContext(ctx, "unix", 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)
|
||||
@@ -714,7 +721,13 @@ func (b *LocalBackend) tcpHandlerForServeTCP(tcph ipn.TCPPortHandlerView, dport
|
||||
func (b *LocalBackend) forwardTCPWithProxyProtocol(conn, backConn net.Conn, proxyProtoVer int, srcAddr netip.AddrPort, dport uint16, backDst string) error {
|
||||
var proxyHeader []byte
|
||||
if proxyProtoVer > 0 {
|
||||
backAddr := backConn.RemoteAddr().(*net.TCPAddr)
|
||||
// PROXY protocol requires a valid TCP destination address.
|
||||
// For Unix socket backends, RemoteAddr is *net.UnixAddr;
|
||||
// the CLI rejects this combination, but guard here as well.
|
||||
backAddr, ok := backConn.RemoteAddr().(*net.TCPAddr)
|
||||
if !ok {
|
||||
return fmt.Errorf("PROXY protocol is not supported with non-TCP backend %s", backDst)
|
||||
}
|
||||
|
||||
// We always want to format the PROXY protocol header based on
|
||||
// the IPv4 or IPv6-ness of the client. The SourceAddr and
|
||||
|
||||
@@ -12,12 +12,14 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"tailscale.com/ipn"
|
||||
"tailscale.com/tstest"
|
||||
)
|
||||
|
||||
@@ -238,3 +240,83 @@ func TestServeBlocksTailscaledSocket(t *testing.T) {
|
||||
t.Error("expected valid handler for legitimate socket")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTCPForwardUnixSocket(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
|
||||
socketPath := filepath.Join(tmpDir, "backend.sock")
|
||||
|
||||
// Create a Unix socket echo server
|
||||
listener, err := net.Listen("unix", socketPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create unix socket listener: %v", err)
|
||||
}
|
||||
defer listener.Close()
|
||||
|
||||
go func() {
|
||||
for {
|
||||
conn, err := listener.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
defer conn.Close()
|
||||
io.Copy(conn, conn) // echo
|
||||
}()
|
||||
}
|
||||
}()
|
||||
|
||||
// Set up a LocalBackend with a ServeConfig that forwards TCP port 3128 to the unix socket
|
||||
b := newTestBackend(t)
|
||||
b.logf = tstest.WhileTestRunningLogger(t)
|
||||
|
||||
conf := &ipn.ServeConfig{
|
||||
TCP: map[uint16]*ipn.TCPPortHandler{
|
||||
3128: {TCPForward: "unix:" + socketPath},
|
||||
},
|
||||
}
|
||||
if err := b.SetServeConfig(conf, ""); err != nil {
|
||||
t.Fatal("setting serve config:", err)
|
||||
}
|
||||
|
||||
// Get the handler from tcpHandlerForServe
|
||||
srcAddr := netip.MustParseAddrPort("100.100.100.1:12345")
|
||||
handler := b.tcpHandlerForServe(3128, srcAddr, nil)
|
||||
if handler == nil {
|
||||
t.Fatal("tcpHandlerForServe returned nil handler")
|
||||
}
|
||||
|
||||
// Create a pipe to simulate an incoming connection
|
||||
clientConn, serverConn := net.Pipe()
|
||||
defer clientConn.Close()
|
||||
|
||||
// Run the handler in a goroutine
|
||||
handlerDone := make(chan error, 1)
|
||||
go func() {
|
||||
handlerDone <- handler(serverConn)
|
||||
}()
|
||||
|
||||
// Write data through the "client" side and read the echo back
|
||||
testData := []byte("hello via tcpHandlerForServe")
|
||||
if _, err := clientConn.Write(testData); err != nil {
|
||||
t.Fatalf("write failed: %v", err)
|
||||
}
|
||||
buf := make([]byte, len(testData))
|
||||
if _, err := io.ReadFull(clientConn, buf); err != nil {
|
||||
t.Fatalf("read failed: %v", err)
|
||||
}
|
||||
if string(buf) != string(testData) {
|
||||
t.Fatalf("echo mismatch: got %q, want %q", buf, testData)
|
||||
}
|
||||
|
||||
// Close client side, handler should finish
|
||||
clientConn.Close()
|
||||
select {
|
||||
case err := <-handlerDone:
|
||||
if err != nil {
|
||||
t.Fatalf("handler returned unexpected error: %v", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("handler did not finish in time")
|
||||
}
|
||||
}
|
||||
|
||||
+13
-9
@@ -139,7 +139,10 @@ type TCPPortHandler struct {
|
||||
// It is mutually exclusive with TCPForward.
|
||||
HTTP bool `json:",omitempty"`
|
||||
|
||||
// TCPForward is the IP:port to forward TCP connections to.
|
||||
// TCPForward is the address to forward TCP connections to.
|
||||
// It is either a host:port (e.g. "127.0.0.1:3128", "localhost:5432")
|
||||
// or a Unix socket path prefixed with "unix:"
|
||||
// (e.g. "unix:/var/run/app.sock" or "unix:relative.sock").
|
||||
// Whether or not TLS is terminated by tailscaled depends on
|
||||
// TerminateTLS.
|
||||
//
|
||||
@@ -462,10 +465,10 @@ func (sc *ServeConfig) SetWebHandler(handler *HTTPHandler, host string, port uin
|
||||
}
|
||||
}
|
||||
|
||||
// SetTCPForwarding sets the fwdAddr (IP:port form) to which to forward
|
||||
// connections from the given port. If terminateTLS is true, TLS connections
|
||||
// are terminated with only the given host name permitted before passing them
|
||||
// to the fwdAddr.
|
||||
// SetTCPForwarding sets the fwdAddr to which to forward connections from the
|
||||
// given port. fwdAddr is either an IP:port or "unix:/path/to/socket".
|
||||
// If terminateTLS is true, TLS connections are terminated with only the given
|
||||
// host name permitted before passing them to the fwdAddr.
|
||||
//
|
||||
// If proxyProtocol is non-zero, the corresponding PROXY protocol version
|
||||
// header is sent before forwarding the connection.
|
||||
@@ -483,10 +486,11 @@ func (sc *ServeConfig) SetTCPForwarding(port uint16, fwdAddr string, terminateTL
|
||||
}
|
||||
}
|
||||
|
||||
// SetTCPForwardingForService sets the fwdAddr (IP:port form) to which to
|
||||
// forward connections from the given port on the service. If terminateTLS
|
||||
// is true, TLS connections are terminated, with only the FQDN that corresponds
|
||||
// to the given service being permitted, before passing them to the fwdAddr.
|
||||
// SetTCPForwardingForService sets the fwdAddr to which to forward connections
|
||||
// from the given port on the service. fwdAddr is either a host:port or
|
||||
// "unix:/path" (absolute or relative). If terminateTLS is true, TLS connections
|
||||
// are terminated, with only the FQDN that corresponds to the given service
|
||||
// being permitted, before passing them to the fwdAddr.
|
||||
func (sc *ServeConfig) SetTCPForwardingForService(port uint16, fwdAddr string, terminateTLS bool, svcName tailcfg.ServiceName, proxyProtocol int, magicDNSSuffix string) {
|
||||
if sc == nil {
|
||||
sc = new(ServeConfig)
|
||||
|
||||
@@ -42,6 +42,14 @@ func TestExpandProxyTargetValueUnix(t *testing.T) {
|
||||
want: "unix:./myservice.sock",
|
||||
skipOnWindows: true,
|
||||
},
|
||||
{
|
||||
name: "unix-socket-bare-relative-path",
|
||||
target: "unix:myservice.sock",
|
||||
supportedSchemes: []string{"http", "https", "unix"},
|
||||
defaultScheme: "http",
|
||||
want: "unix:myservice.sock",
|
||||
skipOnWindows: true,
|
||||
},
|
||||
{
|
||||
name: "unix-socket-empty-path",
|
||||
target: "unix:",
|
||||
@@ -56,6 +64,21 @@ func TestExpandProxyTargetValueUnix(t *testing.T) {
|
||||
defaultScheme: "http",
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "unix-socket-tcp-supported",
|
||||
target: "unix:/var/run/app.sock",
|
||||
supportedSchemes: []string{"tcp", "unix"},
|
||||
defaultScheme: "tcp",
|
||||
want: "unix:/var/run/app.sock",
|
||||
skipOnWindows: true,
|
||||
},
|
||||
{
|
||||
name: "unix-socket-tcp-not-supported",
|
||||
target: "unix:/var/run/app.sock",
|
||||
supportedSchemes: []string{"tcp"},
|
||||
defaultScheme: "tcp",
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
|
||||
Reference in New Issue
Block a user