Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,14 @@ $ tailcat forward tcXXXXXXXXX 18080:8080 3306

A local port of 0 asks the operating system for a free port; each listener prints its address once it's listening.

On Unix-like systems, a mapping with a non-numeric first component listens
on that local Unix socket path and forwards to the remote port. For example:

```sh
$ tailcat forward tcXXXXXXXXX /tmp/server.sock:80
$ tailcat forward tcXXXXXXXXX ./project/server.sock:80
```

To forward local ports to assets on the network reachable by an exit-node server, run the server in exit-node mode and specify each remote IP address and port in the mapping:

```sh
Expand Down Expand Up @@ -208,7 +216,7 @@ $ tailcat serve 80
$ tailcat browse tcXXXXXXXXX
```

This is an alias for `tailcat forward --open-browser <tc-addr> 0:80`: it opens `http://127.0.0.1:<port>/` in a web browser once the local listener is ready, then blocks, forwarding connections, until interrupted. The `--open-browser` flag works with any single `forward` port mapping.
This is an alias for `tailcat forward --open-browser <tc-addr> 0:80`: it opens `http://127.0.0.1:<port>/` in a web browser once the local listener is ready, then blocks, forwarding connections, until interrupted. The `--open-browser` flag works with any single TCP `forward` port mapping.

### Public-key-authenticated SSH server

Expand Down
61 changes: 50 additions & 11 deletions cmd/tailcat/forward.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,23 +23,25 @@ import (
func forwardCommand(parent *ff.FlagSet) *ff.Command {
fs := ff.NewFlagSet("forward").SetParent(parent)
bind := fs.StringLong("bind", "127.0.0.1", "listen address; used as the local address when a mapping only specifies a port")
openBrowser := fs.BoolLong("open-browser", "open a web browser to the local listener once it's listening; requires exactly one port mapping")
openBrowser := fs.BoolLong("open-browser", "open a web browser to the local listener once it's listening; requires exactly one TCP port mapping")
return &ff.Command{
Name: "forward",
Usage: "tailcat forward [flags] <tc-addr> <[local:]remote-port|local-port:remote-ip:remote-port> [<...> ...]",
ShortHelp: "forward local TCP ports to a tailcat server",
LongHelp: `Listen on local TCP ports and forward connections to a tailcat server.
Usage: "tailcat forward [flags] <tc-addr> <[local:]remote-port|local-port:remote-ip:remote-port|socket-path:remote-port> [<...> ...]",
ShortHelp: "forward local TCP ports or Unix sockets to a tailcat server",
LongHelp: `Listen on local TCP ports or Unix sockets and forward connections to a tailcat server.

A mapping with one port uses the same local and remote port. A mapping with
local:remote uses different local and remote ports. A local port of 0 asks
the operating system for a free port; each listener prints its address once
it's listening. A mapping with a remote IP address and port requires the
server to be running as an exit node. For example:
server to be running as an exit node. A mapping whose first component is not
a number uses a local Unix socket path and remote port. For example:

tailcat forward <tc-addr> 8080
tailcat forward --bind=0.0.0.0 <tc-addr> 18080:8080
tailcat forward <tc-addr> 0:8080
tailcat forward <tc-addr> 13306:192.168.1.10:3306`,
tailcat forward <tc-addr> 13306:192.168.1.10:3306
tailcat forward <tc-addr> /tmp/server.sock:80`,
Flags: fs,
Exec: func(ctx context.Context, args []string) error {
var onListen func(net.Listener)
Expand All @@ -55,9 +57,10 @@ server to be running as an exit node. For example:
}

type forwardSpec struct {
listenAddr string
target netip.AddrPort
port uint16
listenNetwork string
listenAddr string
target netip.AddrPort
port uint16
}

func (s forwardSpec) remoteTarget() string {
Expand Down Expand Up @@ -104,7 +107,13 @@ func runForward(ctx context.Context, logf logger.Logf, bind string, args []strin
}
return usagef("mapping %q is invalid: %v", spec, err)
}
ln, err := net.Listen("tcp", mapping.listenAddr)
if onListen != nil && mapping.listenNetwork != "tcp" {
for _, ln := range listeners {
ln.Close()
}
return usagef("--open-browser requires a TCP port mapping")
}
ln, err := net.Listen(mapping.listenNetwork, mapping.listenAddr)
if err != nil {
for _, old := range listeners {
old.Close()
Expand Down Expand Up @@ -163,6 +172,21 @@ func forwardListener(ctx context.Context, logf logger.Logf, cl *tailcat.Client,

func parseForwardSpec(bind, spec string) (forwardSpec, error) {
local, target, hasColon := strings.Cut(spec, ":")
if !isDecimal(local) {
colon := strings.LastIndex(spec, ":")
if colon <= 0 {
return forwardSpec{}, fmt.Errorf("Unix socket mapping %q must include a remote port", spec)
}
remotePort, err := parseForwardPort(spec[colon+1:])
if err != nil {
return forwardSpec{}, fmt.Errorf("remote port: %w", err)
}
return forwardSpec{
listenNetwork: "unix",
listenAddr: spec[:colon],
port: remotePort,
}, nil
}
if !hasColon {
target = local
}
Expand All @@ -174,7 +198,10 @@ func parseForwardSpec(bind, spec string) (forwardSpec, error) {
return forwardSpec{}, fmt.Errorf("local port: %w", err)
}
}
mapping := forwardSpec{listenAddr: net.JoinHostPort(bind, strconv.Itoa(int(localPort)))}
mapping := forwardSpec{
listenNetwork: "tcp",
listenAddr: net.JoinHostPort(bind, strconv.Itoa(int(localPort))),
}
if !hasColon {
mapping.port, err = parseForwardPort(target)
if err != nil {
Expand All @@ -195,6 +222,18 @@ func parseForwardSpec(bind, spec string) (forwardSpec, error) {
return mapping, nil
}

func isDecimal(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if r < '0' || r > '9' {
return false
}
}
return true
}

func parseForwardPort(s string) (uint16, error) {
p, err := strconv.ParseUint(s, 10, 16)
if err != nil || p == 0 {
Expand Down
102 changes: 86 additions & 16 deletions cmd/tailcat/forward_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,28 +10,38 @@ import (
"os"
"path/filepath"
"regexp"
"runtime"
"strconv"
"testing"
"time"
)

func TestParseForwardSpec(t *testing.T) {
for _, tt := range []struct {
spec, wantAddr string
wantPort uint16
wantTarget string
wantErr bool
spec, wantNetwork, wantAddr string
wantPort uint16
wantTarget string
wantErr bool
}{
{"8080", "127.0.0.1:8080", 8080, "", false},
{"18080:8080", "127.0.0.1:18080", 8080, "", false},
{"1:65535", "127.0.0.1:1", 65535, "", false},
{"0", "", 0, "", true},
{"0:8080", "127.0.0.1:0", 8080, "", false},
{"13306:192.168.1.10:3306", "127.0.0.1:13306", 0, "192.168.1.10:3306", false},
{"13306:[2001:db8::10]:3306", "127.0.0.1:13306", 0, "[2001:db8::10]:3306", false},
{"8080:0", "", 0, "", true},
{"8080:bad", "", 0, "", true},
{"8080:192.168.1.10:bad", "", 0, "", true},
{"8080", "tcp", "127.0.0.1:8080", 8080, "", false},
{"18080:8080", "tcp", "127.0.0.1:18080", 8080, "", false},
{"1:65535", "tcp", "127.0.0.1:1", 65535, "", false},
{"0", "", "", 0, "", true},
{"0:8080", "tcp", "127.0.0.1:0", 8080, "", false},
{"13306:192.168.1.10:3306", "tcp", "127.0.0.1:13306", 0, "192.168.1.10:3306", false},
{"13306:[2001:db8::10]:3306", "tcp", "127.0.0.1:13306", 0, "[2001:db8::10]:3306", false},
{"/tmp/server.sock:80", "unix", "/tmp/server.sock", 80, "", false},
{"/tmp/socket:with-colon.sock:80", "unix", "/tmp/socket:with-colon.sock", 80, "", false},
{"./project/server.sock:80", "unix", "./project/server.sock", 80, "", false},
{"../run/server.sock:80", "unix", "../run/server.sock", 80, "", false},
{"project/server.sock:80", "unix", "project/server.sock", 80, "", false},
{".server.sock:80", "unix", ".server.sock", 80, "", false},
{"8080:0", "", "", 0, "", true},
{"8080:bad", "", "", 0, "", true},
{"8080:192.168.1.10:bad", "", "", 0, "", true},
{"99999:80", "", "", 0, "", true},
{"project/server.sock:bad", "", "", 0, "", true},
{"project/server.sock", "", "", 0, "", true},
} {
t.Run(tt.spec, func(t *testing.T) {
got, err := parseForwardSpec("127.0.0.1", tt.spec)
Expand All @@ -45,13 +55,73 @@ func TestParseForwardSpec(t *testing.T) {
if got.target.IsValid() {
wantTarget = got.target.String()
}
if err != nil || got.listenAddr != tt.wantAddr || got.port != tt.wantPort || wantTarget != tt.wantTarget {
t.Fatalf("parseForwardSpec(%q) = %#v, %v; want address %q, port %d, target %q", tt.spec, got, err, tt.wantAddr, tt.wantPort, tt.wantTarget)
if err != nil || got.listenNetwork != tt.wantNetwork || got.listenAddr != tt.wantAddr || got.port != tt.wantPort || wantTarget != tt.wantTarget {
t.Fatalf("parseForwardSpec(%q) = %#v, %v; want network %q, address %q, port %d, target %q", tt.spec, got, err, tt.wantNetwork, tt.wantAddr, tt.wantPort, tt.wantTarget)
}
})
}
}

func TestForwardUnixSocketEndToEnd(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Unix sockets are not supported by this test on Windows")
}
t.Parallel()
e := newTestEnv(t)
remotePort := startEchoListener(t)

_, tailcatAddr, serverStderr := e.startServer("--verbose", "serve", strconv.Itoa(int(remotePort)))
socketPath := filepath.Join(t.TempDir(), "server.sock")
forward := e.cmd("--verbose", "--key=new", "--derpmap-url="+e.derpMapURL, "forward", tailcatAddr, fmt.Sprintf("%s:%d", socketPath, remotePort))
stderrPath := filepath.Join(t.TempDir(), "forward-unix.stderr")
stderrFile, err := os.Create(stderrPath)
if err != nil {
t.Fatal(err)
}
defer stderrFile.Close()
forward.Stderr = stderrFile
if err := forward.Start(); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = forward.Process.Kill()
_ = forward.Wait()
})
forwardStderr := func() string {
b, _ := os.ReadFile(stderrPath)
return string(b)
}

deadline := time.Now().Add(30 * time.Second)
for {
if _, err := os.Stat(socketPath); err == nil {
break
}
if time.Now().After(deadline) {
t.Fatalf("forward never created Unix socket; stderr:\n%s\nserver stderr:\n%s", forwardStderr(), serverStderr)
}
time.Sleep(100 * time.Millisecond)
}

conn, err := net.Dial("unix", socketPath)
if err != nil {
t.Fatal(err)
}
defer conn.Close()

const payload = "forwarded through a Unix socket"
if _, err := conn.Write([]byte(payload)); err != nil {
t.Fatal(err)
}
got := make([]byte, len(payload))
if _, err := conn.Read(got); err != nil {
t.Fatalf("read: %v\nforward stderr:\n%s\nserver stderr:\n%s", err, forwardStderr(), serverStderr)
}
if string(got) != payload {
t.Errorf("got %q; want %q", got, payload)
}
}

func TestForwardEndToEnd(t *testing.T) {
t.Parallel()
e := newTestEnv(t)
Expand Down
4 changes: 2 additions & 2 deletions cmd/tailcat/tailcat.go
Original file line number Diff line number Diff line change
Expand Up @@ -373,9 +373,9 @@ Client mode, list the files a server offers:

tailcat ls [-l] <tc-addr>[:path]

Client mode, forward local TCP ports to a tailcat server:
Client mode, forward local TCP ports or Unix sockets to a tailcat server:

tailcat forward [--bind=<addr>] <tc-addr> <[local:]remote> ...
tailcat forward [--bind=<addr>] <tc-addr> <mapping> ...

Client mode, run an ephemeral SOCKS5 proxy and pass its address
as 'all_proxy' environment variable to a child process. Destination
Expand Down