From 1d9101decd899553345f8fb53579dfac1b352083 Mon Sep 17 00:00:00 2001 From: Erik Karulf Date: Sat, 28 Nov 2026 22:48:07 -0500 Subject: [PATCH] Remove OS TUN mode and host-route management --- DESIGN.md | 96 +-------------- PROTOCOL.md | 4 +- README.md | 25 ++-- cmd/qcat/main.go | 55 +-------- go.mod | 2 +- internal/transport/renew_test.go | 12 +- internal/transport/transport_test.go | 166 ++------------------------ internal/tunnel/tunnel.go | 110 ----------------- third_party/tailcat/QUANTUMCAT.md | 13 +- third_party/tailcat/admission_test.go | 62 ++++------ third_party/tailcat/quantumcat.go | 20 +--- third_party/tailcat/tailcat.go | 59 +-------- 12 files changed, 69 insertions(+), 555 deletions(-) delete mode 100644 internal/tunnel/tunnel.go diff --git a/DESIGN.md b/DESIGN.md index f742fd1..68e5c18 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1526,97 +1526,18 @@ Reject trailing unexpected bytes. --- -# 40. VPN modes +# 40. Userspace transport -Implement in phases. - -## Phase 1: Tailcat-compatible transport - -Support: - -```bash -qcat serve -qcat forward -qcat socks -``` - -This proves: - -* PQ handshake -* DERP bootstrap -* WireGuard PSK integration -* NAT traversal -* authentication -* Secure Enclave bridge - -before adding system routing. - -## Phase 2: point-to-point TUN - -Add: - -```bash -qcat up outpost -``` - -Result: - -```text -client server - -100.100.x.2/32 100.100.x.1/32 - │ │ - TUN TUN - │ │ - └────── WireGuard ──────────┘ -``` - -Use a private ULA IPv6 prefix or another explicitly configured range rather than colliding with real Tailscale addressing. - -Prefer IPv6 internally because point-to-point address management is simpler. - -Example: - -```text -fd7a:7163:6174::/48 -``` - -but choose the final prefix deliberately before release. +Quantumcat uses Tailcat’s userspace network stack for TCP and UDP services, +SSH, Mosh, and SOCKS5. Applications reach a published service through a +local forward, proxy, or SSH ProxyCommand. --- # 41. Routing -Initial `qcat up` should only install a host route to the remote Quantumcat peer. - -Example: - -```text -qcat up outpost -``` - -creates: - -```text -fdxx::1 -> qcat tunnel -``` - -Do not initially implement: - -```text -0.0.0.0/0 -::/0 -LAN subnet routing -DNS interception -``` - -Later: - -```bash -qcat up outpost --route 10.0.0.0/24 -``` - -can enable subnet routing. +Peer IPv6 addresses in `fd7a:7163:6174::/48` belong to the userspace network +stack. The operating system keeps its existing interfaces and routes. --- @@ -1637,7 +1558,6 @@ qcat serve qcat connect qcat forward qcat socks -qcat up qcat down qcat status qcat debug @@ -1653,10 +1573,6 @@ qcat identity init --name macbook qcat peer add outpost outpost.qpeer ``` -```bash -qcat up outpost -``` - ```bash qcat forward outpost 2222:localhost:22 ``` diff --git a/PROTOCOL.md b/PROTOCOL.md index 48107f4..01870fa 100644 --- a/PROTOCOL.md +++ b/PROTOCOL.md @@ -140,8 +140,8 @@ the transcript hash to identify the session. Type 4 is an authenticated acknowledgement, replacing the design's optional Error message. This handles lost finishes without premature client peer installation. Repeated finishes resend the acknowledgement without reinstalling a peer. -Acceptance is committed only after transport and any TUN route installation -succeed. Installation failure erases the pending keys and acknowledgement state; +Acceptance is committed only after transport installation +succeeds. Installation failure erases the pending keys and acknowledgement state; repeated finishes cannot turn a failed installation into a successful handshake. The server installs the peer after ClientFinish verification; the client waits diff --git a/README.md b/README.md index 8a03eac..5052c64 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ QuantumCat (`qcat`) combines WireGuard, Tailscale's networking stack, and DERP r - ML-DSA-87 device authentication - Fresh ML-KEM-1024 exchange for each connection's WireGuard PSK - Secure Enclave-backed identities on supported Macs -- TCP, UDP, SSH, Mosh, SOCKS5, and IPv6 TUN modes +- SSH, Mosh, SOCKS5, and TCP/UDP forwarding - macOS, Linux, and FreeBSD builds > [!WARNING] @@ -227,9 +227,8 @@ Set-ID invocations (different real/effective user or group IDs) cannot start a helper. Ordinary root invocations, including `sudo`, ignore both environment overrides and disable the shared-directory exception. Root will not run a helper from a normal user-owned Homebrew keg, even if the helper file itself is root-owned. -For privileged TUN use with Secure Enclave, install `qcat` and its helper into a -separate root-owned, non-group/other-writable installation rather than changing -ownership of Homebrew's prefix. Identity and peer-store symlink and permission +For a root-run service, install the helper in a root-owned installation with +write access restricted to root. Identity and peer-store symlink and permission checks are unchanged. Secure Enclave long-lived private keys remain non-exportable. Helper-path checks @@ -288,19 +287,11 @@ These run unprivileged for forwarding mode and do not expose public TCP/UDP list The repository contains ready-to-adapt examples under [`deploy/`](deploy/). -## IP mode +## Migrating from OS TUN mode -QuantumCat can also create an OS TUN interface and assign private IPv6 host routes between authenticated peers: - -```sh -# Server -sudo qcat --config /etc/qcat serve --tun --export /tmp/outpost.qpeer - -# Client -sudo qcat --config /path/to/client-config up outpost -``` - -IP mode installs peer host routes only. It does not install a default route, subnet route, or DNS configuration. +`qcat serve --tun` and `qcat up` have been removed. For SSH, publish port 22 with `qcat serve --tcp 22=127.0.0.1:22` +and use `qcat connect PEER 22` as the SSH ProxyCommand. For other services, +use TCP/UDP forwarding or SOCKS5. These modes reuse existing pairings. ## Status and shutdown @@ -333,7 +324,7 @@ automatically. To stamp a tag into a local build, set `VERSION`: make build VERSION=v0.1.0 ``` -Use `--verbose` on `serve`, `forward`, `socks`, `connect`, `up`, or `mosh` to +Use `--verbose` on `serve`, `forward`, `socks`, `connect`, or `mosh` to write transport diagnostics, including `portmapper:` messages, to stderr. Place it before positional arguments, for example `qcat serve --verbose --tcp 22=127.0.0.1:22` or diff --git a/cmd/qcat/main.go b/cmd/qcat/main.go index d38dc91..d97369e 100644 --- a/cmd/qcat/main.go +++ b/cmd/qcat/main.go @@ -23,12 +23,10 @@ import ( "github.com/ekarulf/quantumcat/internal/protocol" "github.com/ekarulf/quantumcat/internal/proxy" "github.com/ekarulf/quantumcat/internal/transport" - "github.com/ekarulf/quantumcat/internal/tunnel" "github.com/ekarulf/quantumcat/internal/version" "github.com/tailscale/tailcat" _ "tailscale.com/feature/condregister/portmapper" "tailscale.com/tailcfg" - "tailscale.com/types/key" "tailscale.com/types/logger" "tailscale.com/wgengine/filter" ) @@ -47,8 +45,6 @@ qcat [--config DIR] socks [--listen 127.0.0.1:1080] PEER qcat [--config DIR] connect PEER PORT qcat [--config DIR] mosh [--ssh-host HOST] [--server-port PORT] [--tunnel-port PORT] [--local-port 0] [--mosh-server PATH] PEER [-- COMMAND...] -qcat [--config DIR] up PEER -qcat [--config DIR] serve --tun [--export FILE.qpeer] qcat [--config DIR] status qcat [--config DIR] down [PEER|serve] qcat debug @@ -56,7 +52,7 @@ qcat version Pair identity show output out of band; serve --export includes public reachability. Flags for each command precede positional arguments. Ctrl-C closes the tunnel. -Use --verbose on serve, forward, socks, connect, up, or mosh for transport logs on stderr. +Use --verbose on serve, forward, socks, connect, or mosh for transport logs on stderr. ` // help prefixes the usage text with the running build, so a bug report that @@ -121,7 +117,7 @@ func run(ctx context.Context, args []string) error { return serve(ctx, s, args[1:]) case "mosh": return mosh(ctx, s, args[1:]) - case "forward", "socks", "connect", "up": + case "forward", "socks", "connect": return client(ctx, s, args[0], args[1:]) case "status": if len(args) != 1 { @@ -241,7 +237,6 @@ func serve(ctx context.Context, s config.Store, args []string) error { region := f.Int("region", 0, "DERP region ID") dm := f.String("derp-map", "", "DERP map URL") export := f.String("export", "", "new public .qpeer file") - tunMode := f.Bool("tun", false, "use an OS TUN with authenticated peer host routes") if err := f.Parse(args); err != nil { return err } @@ -281,12 +276,9 @@ func serve(ctx context.Context, s config.Store, args []string) error { } allowed[target] = true } - if len(allowed) == 0 && len(udpTargets) == 0 && !*tunMode { + if len(allowed) == 0 && len(udpTargets) == 0 { return errors.New("specify at least one --tcp, --udp or --allow-target") } - if *tunMode && (len(allowed) > 0 || len(udpTargets) > 0) { - return errors.New("--tun cannot be combined with forwarding services") - } i, _, meta, close, err := s.Identity(ctx) if err != nil { return err @@ -317,19 +309,6 @@ func serve(ctx context.Context, s config.Store, args []string) error { } } }) - if *tunMode { - tun, err := tunnel.Open() - if err != nil { - return err - } - defer tun.Close() - if err = tun.Configure(tailcat.NodeAddress(meta.Node.Public())); err != nil { - return err - } - server.TUN = tun.Device - server.OnTunnelPeer = func(k key.NodePublic, add bool) error { return tun.Peer(tailcat.NodeAddress(k), add) } - fmt.Fprintln(os.Stderr, "TUN", tun.Name, tailcat.NodeAddress(meta.Node.Public())) - } server.RegionID = tailcfg.DERPRegionID(*region) server.DERPMapURL = *dm server.Logf = transportLogf(*verbose) @@ -457,21 +436,6 @@ func client(ctx context.Context, s config.Store, command string, args []string) } defer c.Close() c.Logf = transportLogf(*verbose) - var tun *tunnel.Tunnel - if command == "up" { - if len(args) != 1 { - return errors.New("up requires PEER") - } - tun, err = tunnel.Open() - if err != nil { - return err - } - defer tun.Close() - c.TUN = tun.Device - if err = tun.Configure(tailcat.NodeAddress(c.PublicKey())); err != nil { - return err - } - } if _, err = c.Ping(ctx); err != nil { return err } @@ -503,19 +467,6 @@ func client(ctx context.Context, s config.Store, command string, args []string) if *udp { return forwardUDP(ctx, c, udpListen, udpPort, *udpIdle) } - if command == "up" { - ci, err := tailcat.ParseAddr(p.Endpoint) - if err != nil { - return err - } - addr := tailcat.NodeAddress(ci.ServerPublic.NodePublic) - if err = tun.Peer(addr, true); err != nil { - return err - } - fmt.Fprintln(os.Stderr, "TUN", tun.Name, "local", tailcat.NodeAddress(c.PublicKey()), "remote", addr) - <-ctx.Done() - return nil - } if command == "connect" { if len(args) != 2 { return errors.New("connect requires PEER PORT") diff --git a/go.mod b/go.mod index 6c818aa..93f8086 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,6 @@ go 1.27.4 require ( github.com/tailscale/tailcat v0.7.1-0.20261105151022-e00cdde6ff78 - github.com/tailscale/wireguard-go v0.0.0-20260928213353-e61b6b78110b go4.org/mem v0.0.0-20240501181205-ae6ca9944745 tailscale.com v1.105.0-pre.0.20261013225543-fb79793d99f5 ) @@ -40,6 +39,7 @@ require ( github.com/tailscale/hujson v0.0.0-20260727124030-b80ff77dac4f // indirect github.com/tailscale/peercred v0.0.0-20250107143737-35a0c7bd7edc // indirect github.com/tailscale/web-client-prebuilt v0.0.0-20260917222731-e0ed2d0d0fea // indirect + github.com/tailscale/wireguard-go v0.0.0-20260928213353-e61b6b78110b // indirect github.com/x448/float16 v0.8.4 // indirect go4.org/netipx v0.0.0-20260823151212-3075585bcbeb // indirect golang.org/x/crypto v0.57.0 // indirect diff --git a/internal/transport/renew_test.go b/internal/transport/renew_test.go index 0328714..58d066a 100644 --- a/internal/transport/renew_test.go +++ b/internal/transport/renew_test.go @@ -140,13 +140,7 @@ func TestTCPStreamSurvivesRenewalAndLostAcknowledgement(t *testing.T) { } } } - var routeAdds, commits atomic.Int32 - server.OnTunnelPeer = func(_ key.NodePublic, add bool) error { - if add { - routeAdds.Add(1) - } - return nil - } + var commits atomic.Int32 var droppedAck, freshPSK atomic.Bool var previous tailcat.PresharedKey // Accessed only by serialized bootstrap worker. original := server.Bootstrap @@ -253,8 +247,8 @@ func TestTCPStreamSurvivesRenewalAndLostAcknowledgement(t *testing.T) { if commits.Load() < 3 || !droppedAck.Load() || !freshPSK.Load() { t.Fatalf("renewal scenarios missing: commits=%d ackLoss=%v freshPSK=%v", commits.Load(), droppedAck.Load(), freshPSK.Load()) } - if routeAdds.Load() != 1 || c.PublicKey() != node || conn.LocalAddr().String() != addr { - t.Fatal("renewal recreated transport identity or route") + if c.PublicKey() != node || conn.LocalAddr().String() != addr { + t.Fatal("renewal changed the transport identity or local address") } newHandshake := false for _, peer := range c.Status().Peer { diff --git a/internal/transport/transport_test.go b/internal/transport/transport_test.go index 38f18fb..e7d3c60 100644 --- a/internal/transport/transport_test.go +++ b/internal/transport/transport_test.go @@ -3,13 +3,10 @@ package transport import ( "bytes" "context" - "encoding/binary" - "errors" "io" "net" "net/http/httptest" "os" - "sync" "sync/atomic" "testing" "time" @@ -17,7 +14,6 @@ import ( "github.com/ekarulf/quantumcat/internal/crypto/provider/software" "github.com/ekarulf/quantumcat/internal/protocol" "github.com/tailscale/tailcat" - "github.com/tailscale/wireguard-go/tun" "tailscale.com/derp/derpserver" "tailscale.com/envknob" "tailscale.com/net/netcheck" @@ -36,7 +32,7 @@ func TestMain(m *testing.M) { os.Exit(m.Run()) } -func TestInstallationFailureNeverAcknowledged(t *testing.T) { +func TestRejectedAdmissionNeverAcknowledged(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second) defer cancel() relay := derpserver.New(key.NewNode(), t.Logf) @@ -53,10 +49,10 @@ func TestInstallationFailureNeverAcknowledged(t *testing.T) { Name: "test", RegionID: 1, HostName: "127.0.0.1", IPv4: "127.0.0.1", IPv6: "none", DERPPort: httpRelay.Listener.Addr().(*net.TCPAddr).Port, STUNPort: stun.Port, STUNTestIP: "127.0.0.1", InsecureForTests: true, }}} - var installs, finishes atomic.Int32 - server.OnTunnelPeer = func(key.NodePublic, bool) error { - installs.Add(1) - return errors.New("simulated route installation failure") + var admissions, finishes atomic.Int32 + server.AllowClient = func(key.NodePublic) bool { + admissions.Add(1) + return false } original := server.Bootstrap server.Bootstrap = func(src key.NodePublic, packet []byte) ([]byte, *tailcat.AuthenticatedPeer) { @@ -76,13 +72,13 @@ func TestInstallationFailureNeverAcknowledged(t *testing.T) { } defer client.Close() if _, err = client.Ping(ctx); err == nil { - t.Fatal("acknowledged failed installation") + t.Fatal("acknowledged rejected admission") } - if installs.Load() != 1 || finishes.Load() < 2 { - t.Fatalf("failure/retry path not exercised: installs=%d finishes=%d", installs.Load(), finishes.Load()) + if admissions.Load() != 1 || finishes.Load() < 2 { + t.Fatalf("failure/retry path not exercised: admissions=%d finishes=%d", admissions.Load(), finishes.Load()) } if len(server.Status().Peer) != 0 { - t.Fatal("failed installation retained peer state") + t.Fatal("rejected admission retained peer state") } } func TestTunnelAuthenticationLossAndRevocation(t *testing.T) { @@ -210,7 +206,7 @@ func TestTunnelAuthenticationLossAndRevocation(t *testing.T) { } // TestDisconnectAuthenticatedClient covers the upstream disconnect API with -// Quantumcat's bootstrap, per-peer PSK, and real-TUN route callbacks. +// Quantumcat's bootstrap and per-peer PSK. func TestDisconnectAuthenticatedClient(t *testing.T) { ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second) defer cancel() @@ -231,15 +227,6 @@ func TestDisconnectAuthenticatedClient(t *testing.T) { var allow atomic.Bool allow.Store(true) server.AllowClient = func(key.NodePublic) bool { return allow.Load() } - var adds, removes atomic.Int32 - server.OnTunnelPeer = func(_ key.NodePublic, add bool) error { - if add { - adds.Add(1) - } else { - removes.Add(1) - } - return nil - } if err := server.Start(); err != nil { t.Fatal(err) } @@ -252,9 +239,6 @@ func TestDisconnectAuthenticatedClient(t *testing.T) { if _, err := client.Ping(ctx); err != nil { t.Fatal(err) } - if adds.Load() != 1 { - t.Fatal("authenticated peer route was not installed") - } allow.Store(false) if !server.DisconnectClient(client.PublicKey()) { t.Fatal("authenticated client was not disconnected") @@ -262,9 +246,6 @@ func TestDisconnectAuthenticatedClient(t *testing.T) { if server.DisconnectClient(client.PublicKey()) { t.Fatal("disconnected client remained installed") } - if removes.Load() != 1 { - t.Fatal("authenticated peer route was not removed exactly once") - } if len(server.Status().Peer) != 0 { t.Fatal("disconnected client remained in the network map") } @@ -278,132 +259,7 @@ func TestDisconnectAuthenticatedClient(t *testing.T) { if err := client.Renew(renewalCtx); err == nil { t.Fatal("disconnected client renewed despite rejected admission") } - if len(server.Status().Peer) != 0 || adds.Load() != 1 { + if len(server.Status().Peer) != 0 { t.Fatal("rejected renewal reinstalled disconnected peer") } } - -// memoryTUN exercises the real WireGuard device's TUN packet path without -// changing the test host's routes or requiring root. -type memoryTUN struct { - in, out chan []byte - done chan struct{} - events chan tun.Event - once sync.Once -} - -func newMemoryTUN() *memoryTUN { - return &memoryTUN{in: make(chan []byte, 16), out: make(chan []byte, 16), done: make(chan struct{}), events: make(chan tun.Event)} -} -func (t *memoryTUN) File() *os.File { return nil } -func (t *memoryTUN) Name() (string, error) { return "memory", nil } -func (t *memoryTUN) MTU() (int, error) { return 1280, nil } -func (t *memoryTUN) BatchSize() int { return 1 } -func (t *memoryTUN) Events() <-chan tun.Event { return t.events } -func (t *memoryTUN) Close() error { t.once.Do(func() { close(t.done); close(t.events) }); return nil } -func (t *memoryTUN) Read(slab []byte, packets []tun.ReadPacket) (int, error) { - select { - case <-t.done: - return 0, io.EOF - case p := <-t.in: - if len(packets) == 0 || len(slab) < len(p)+2*tun.ReadPacketSpacing { - return 0, tun.ErrTooManySegments - } - offset := tun.ReadPacketSpacing - packets[0] = tun.ReadPacket{Offset: offset, Size: copy(slab[offset:], p)} - return 1, nil - } -} -func (t *memoryTUN) Write(bufs [][]byte, offset int) (int, error) { - for _, b := range bufs { - select { - case <-t.done: - return 0, io.EOF - case t.out <- append([]byte(nil), b[offset:]...): - } - } - return len(bufs), nil -} -func TestIPModeHostPackets(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) - defer cancel() - relay := derpserver.New(key.NewNode(), t.Logf) - httpRelay := httptest.NewTLSServer(derpserver.Handler(relay)) - defer httpRelay.Close() - defer relay.Close() - stun, closeSTUN := stuntest.ServeWithPacketListener(t, nettype.Std{}) - defer closeSTUN() - si, _ := software.Generate() - ci, _ := software.Generate() - sp, _ := si.PublicKey(ctx) - cp, _ := ci.PublicKey(ctx) - server := Server(si, sp, key.NewNode(), func(yield func(protocol.PeerID, []byte) bool) { yield(protocol.ID(cp), cp) }) - server.Region = &tailcfg.DERPRegion{RegionID: 1, RegionCode: "test", Nodes: []*tailcfg.DERPNode{{Name: "test", RegionID: 1, HostName: "127.0.0.1", IPv4: "127.0.0.1", IPv6: "none", DERPPort: httpRelay.Listener.Addr().(*net.TCPAddr).Port, STUNPort: stun.Port, STUNTestIP: "127.0.0.1", InsecureForTests: true}}} - st := newMemoryTUN() - server.TUN = st - server.Logf = t.Logf - if err := server.Start(); err != nil { - t.Fatal(err) - } - defer server.Close() - c, err := Client(ci, software.NewKEM, sp, server.TailcatAddr()) - if err != nil { - t.Fatal(err) - } - defer c.Close() - ct := newMemoryTUN() - c.TUN = ct - c.Logf = t.Logf - startupCtx, stopStartup := context.WithTimeout(ctx, 45*time.Second) - _, err = c.Ping(startupCtx) - stopStartup() - if err != nil { - t.Fatalf("IP-mode bootstrap: %v", err) - } - packetCtx, stopPackets := context.WithTimeout(ctx, 20*time.Second) - defer stopPackets() - local := tailcat.NodeAddress(c.PublicKey()).As16() - remote := tailcat.NodeAddress(server.Key.Public()).As16() - // IPv6 + UDP. The memory device tests packet transport, not an OS UDP stack. - packet := make([]byte, 52) - packet[0] = 0x60 - binary.BigEndian.PutUint16(packet[4:6], 12) - packet[6] = 17 - packet[7] = 64 - copy(packet[8:24], local[:]) - copy(packet[24:40], remote[:]) - binary.BigEndian.PutUint16(packet[40:42], 40000) - binary.BigEndian.PutUint16(packet[42:44], 9000) - binary.BigEndian.PutUint16(packet[44:46], 12) - copy(packet[48:], "qcat") - // IPv6 UDP pseudoheader checksum. - sum := uint32(12 + 17) - for j := 8; j < 40; j += 2 { - sum += uint32(binary.BigEndian.Uint16(packet[j : j+2])) - } - for j := 40; j < len(packet); j += 2 { - sum += uint32(binary.BigEndian.Uint16(packet[j : j+2])) - } - for sum > 65535 { - sum = (sum & 65535) + (sum >> 16) - } - binary.BigEndian.PutUint16(packet[46:48], ^uint16(sum)) - ticker := time.NewTicker(100 * time.Millisecond) - defer ticker.Stop() - for { - select { - case <-packetCtx.Done(): - t.Fatalf("TUN packet did not traverse authenticated WireGuard after bootstrap: %v", packetCtx.Err()) - case <-ticker.C: - select { - case ct.in <- packet: - case <-packetCtx.Done(): - t.Fatalf("TUN injection blocked: %v", packetCtx.Err()) - } - case got := <-st.out: - if bytes.Equal(got, packet) { - return - } - } - } -} diff --git a/internal/tunnel/tunnel.go b/internal/tunnel/tunnel.go deleted file mode 100644 index e6dd370..0000000 --- a/internal/tunnel/tunnel.go +++ /dev/null @@ -1,110 +0,0 @@ -// Package tunnel manages a single OS TUN and explicit IPv6 host routes. -// It never installs default, subnet, or DNS routes. -package tunnel - -import ( - "context" - "errors" - "fmt" - "net/netip" - "os/exec" - "runtime" - "sync" - "time" - - "github.com/tailscale/wireguard-go/tun" -) - -type Tunnel struct { - Device tun.Device - Name string - mu sync.Mutex - routes map[netip.Addr]bool -} - -func Open() (*Tunnel, error) { - name := "qcat%d" - if runtime.GOOS == "darwin" { - name = "utun" - } - if runtime.GOOS != "darwin" && runtime.GOOS != "linux" { - return nil, errors.New("TUN mode requires macOS or Linux") - } - d, err := tun.CreateTUN(name, 1280) - if err != nil { - return nil, fmt.Errorf("create TUN (requires network administration privileges): %w", err) - } - actual, err := d.Name() - if err != nil { - d.Close() - return nil, err - } - return &Tunnel{Device: d, Name: actual, routes: make(map[netip.Addr]bool)}, nil -} -func command(name string, args ...string) error { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - out, err := exec.CommandContext(ctx, name, args...).CombinedOutput() - if err != nil { - return fmt.Errorf("%s: %w: %s", name, err, out) - } - return nil -} -func (t *Tunnel) Configure(local netip.Addr) error { - if !local.Is6() || !local.IsPrivate() { - return errors.New("TUN requires a private IPv6 address") - } - if runtime.GOOS == "darwin" { - return command("/sbin/ifconfig", t.Name, "inet6", local.String(), "prefixlen", "128", "up") - } - if err := command("/sbin/ip", "-6", "addr", "add", local.String()+"/128", "dev", t.Name); err != nil { - return err - } - return command("/sbin/ip", "link", "set", "dev", t.Name, "up") -} -func (t *Tunnel) Peer(addr netip.Addr, add bool) error { - t.mu.Lock() - defer t.mu.Unlock() - if !addr.Is6() || !addr.IsPrivate() { - return errors.New("only private IPv6 host routes are supported") - } - if t.routes[addr] == add { - return nil - } - verb := "delete" - if add { - verb = "add" - } - var err error - if runtime.GOOS == "darwin" { - err = command("/sbin/route", "-n", verb, "-inet6", addr.String(), "-interface", t.Name) - } else { - err = command("/sbin/ip", "-6", "route", verb, addr.String()+"/128", "dev", t.Name) - } - if err == nil { - if add { - t.routes[addr] = true - } else { - delete(t.routes, addr) - } - } - return err -} -func (t *Tunnel) Close() error { - t.mu.Lock() - routes := make([]netip.Addr, 0, len(t.routes)) - for addr := range t.routes { - routes = append(routes, addr) - } - t.mu.Unlock() - var errs []error - for _, addr := range routes { - if err := t.Peer(addr, false); err != nil { - errs = append(errs, err) - } - } - if err := t.Device.Close(); err != nil { - errs = append(errs, err) - } - return errors.Join(errs...) -} diff --git a/third_party/tailcat/QUANTUMCAT.md b/third_party/tailcat/QUANTUMCAT.md index 9962cbf..ea5bb08 100644 --- a/third_party/tailcat/QUANTUMCAT.md +++ b/third_party/tailcat/QUANTUMCAT.md @@ -13,13 +13,11 @@ Nix, release CLI, or optional-feature build-tag configuration. Quantumcat modifications add a bounded DERP bootstrap callback, disable Meow authorization when that callback is configured, gate client WireGuard peer configuration until authentication, and support per-client PSKs. Additional -hooks expire/revoke peers, expose local status, and support a real TUN with -host-only peer filtering. Addresses use fd7a:7163:6174::/48. Review these +hooks expire/revoke peers and expose local status. Addresses use fd7a:7163:6174::/48. Review these changes against the pinned upstream commit when updating. Authenticated installation now reports success/failure to the bootstrap layer -before acknowledgements are sent. Failed installs roll back peer/network-map -state and invalidate protocol acceptance retry state. +before acknowledgements are sent. Rejected admissions invalidate protocol acceptance retry state. Client.RefreshNetwork rebinds outer sockets and refreshes path discovery without replacing the device or application sockets. Client.Probe checks encrypted TSMP @@ -31,15 +29,14 @@ keys and sockets. Client.Renew schedules a fresh WireGuard handshake after installing the acknowledged PSK; it does not recreate the device or netstack. The upstream AllowClient hook also gates authenticated peer installation. -DisconnectClient clears authentication, PSK, and validity state, synchronizes -the WireGuard device, and removes real-TUN peer routes through OnTunnelPeer. +DisconnectClient clears authentication, PSK, and validity state and synchronizes +the WireGuard device. The local module manifest is tidied for the retained networking subset. Authenticated admission hooks run off the bootstrap worker with one pending decision per key and at most 64 pending decisions. Expiry and renewal continue while a hook is blocked; shutdown rejects pending installs without waiting for -the hooks. Install, disconnect, eviction, and expiry serialize peer state and -route callbacks so a removed peer cannot acquire a late route. +the hooks. Install, disconnect, eviction, and expiry serialize changes to peer state. Legacy admissions retain their per-key slot until the hook returns, and reject stale approval after disconnect or shutdown. A fresh retry consults the policy again after the cancelled hook has finished. diff --git a/third_party/tailcat/admission_test.go b/third_party/tailcat/admission_test.go index bdaa7c1..9f6afe5 100644 --- a/third_party/tailcat/admission_test.go +++ b/third_party/tailcat/admission_test.go @@ -250,7 +250,6 @@ func TestBootstrapAdmissionDoesNotBlockWorker(t *testing.T) { ok bool } installed := make(chan installation, 16) - removed := make(chan key.NodePublic, 16) var valid atomic.Bool valid.Store(true) disco := key.NewDisco().Public() @@ -261,12 +260,6 @@ func TestBootstrapAdmissionDoesNotBlockWorker(t *testing.T) { Installed: func(ok bool) { installed <- installation{src, ok} }, } } - s.OnTunnelPeer = func(k key.NodePublic, add bool) error { - if !add { - removed <- k - } - return nil - } if err := s.Start(); err != nil { t.Fatal(err) } @@ -283,8 +276,18 @@ func TestBootstrapAdmissionDoesNotBlockWorker(t *testing.T) { t.Fatalf("fast client renewal = %+v", got) } valid.Store(false) - if got := awaitBootstrapEvent(t, removed); got != fast { - t.Fatalf("expired peer = %v; want fast client", got) + deadline := time.Now().Add(5 * time.Second) + for { + s.lb.mu.Lock() + _, present := s.lb.clients[fast] + s.lb.mu.Unlock() + if !present { + break + } + if time.Now().After(deadline) { + t.Fatal("expired peer remained installed while admission was blocked") + } + time.Sleep(20 * time.Millisecond) } // Close must finish without waiting for an uncooperative AllowClient. closed := make(chan struct{}) @@ -305,34 +308,25 @@ func TestBootstrapAdmissionDoesNotBlockWorker(t *testing.T) { } } -func TestBootstrapDisconnectOrdersRouteCallbacks(t *testing.T) { +func TestBootstrapDisconnectOrdersInstallation(t *testing.T) { s := newBootstrapTestServer(t) client := key.NewNode().Public() adding := make(chan struct{}) release := make(chan struct{}) var releaseOnce sync.Once t.Cleanup(func() { releaseOnce.Do(func() { close(release) }) }) - var route atomic.Bool - callbacks := make(chan bool, 4) installed := make(chan bool, 4) s.Bootstrap = func(key.NodePublic, []byte) ([]byte, *AuthenticatedPeer) { return nil, &AuthenticatedPeer{ Identity: [32]byte{1}, Disco: key.NewDisco().Public(), PSK: NewPresharedKey(), - Valid: func() bool { return true }, Installed: func(ok bool) { installed <- ok }, + Valid: func() bool { return true }, + Installed: func(ok bool) { + close(adding) + <-release + installed <- ok + }, } } - s.OnTunnelPeer = func(k key.NodePublic, add bool) error { - if k != client { - t.Errorf("route callback for unexpected peer %v", k) - } - if add { - close(adding) - <-release // Disconnect runs while the route is not installed yet. - } - route.Store(add) - callbacks <- add - return nil - } if err := s.Start(); err != nil { t.Fatal(err) } @@ -344,22 +338,16 @@ func TestBootstrapDisconnectOrdersRouteCallbacks(t *testing.T) { awaitBootstrapEvent(t, disconnecting) select { case result := <-disconnected: - t.Fatalf("disconnect finished before route installation: %v", result) + t.Fatalf("disconnect finished before installation completed: %v", result) case <-time.After(100 * time.Millisecond): } releaseOnce.Do(func() { close(release) }) if !awaitBootstrapEvent(t, installed) { - t.Fatal("route installation failed") + t.Fatal("peer installation failed") } if !awaitBootstrapEvent(t, disconnected) { t.Fatal("installed client was not disconnected") } - if !awaitBootstrapEvent(t, callbacks) || awaitBootstrapEvent(t, callbacks) { - t.Fatal("route callbacks were not ordered add, remove") - } - if route.Load() { - t.Fatal("disconnected client's route remained installed") - } s.lb.mu.Lock() defer s.lb.mu.Unlock() if len(s.lb.clients) != 0 || len(s.lb.peerPSKs) != 0 || len(s.lb.peerValid) != 0 || len(s.lb.peerOwners) != 0 || len(s.lb.peerInstalled) != 0 { @@ -385,18 +373,16 @@ func TestBootstrapDisconnectCancelsPendingAdmission(t *testing.T) { Valid: func() bool { return true }, Installed: func(ok bool) { installed <- ok }, } } - var routes atomic.Int32 - s.OnTunnelPeer = func(key.NodePublic, bool) error { routes.Add(1); return nil } if err := s.Start(); err != nil { t.Fatal(err) } s.lb.onDERPRecv(1, client, []byte("QCATtest")) - if awaitBootstrapEvent(t, installed) || routes.Load() != 0 { - t.Fatal("cancelled admission installed a peer route") + if awaitBootstrapEvent(t, installed) { + t.Fatal("cancelled admission installed a peer") } // Once the cancelled hook has returned, a fresh admission can proceed. s.lb.onDERPRecv(1, client, []byte("QCATtest")) - if !awaitBootstrapEvent(t, installed) || routes.Load() != 1 || calls.Load() != 2 { + if !awaitBootstrapEvent(t, installed) || calls.Load() != 2 { t.Fatal("fresh admission did not install exactly once") } } diff --git a/third_party/tailcat/quantumcat.go b/third_party/tailcat/quantumcat.go index 3f8b0c5..5e7cad7 100644 --- a/third_party/tailcat/quantumcat.go +++ b/third_party/tailcat/quantumcat.go @@ -3,7 +3,6 @@ package tailcat import ( "context" "errors" - "net/netip" "time" "tailscale.com/ipn/ipnstate" @@ -74,9 +73,6 @@ func (c *Client) Status() *ipnstate.Status { return c.lb.Status() } -// NodeAddress returns the host address in Quantumcat's private ULA prefix. -func NodeAddress(k key.NodePublic) netip.Addr { return tcAddrForKey(k) } - // AuthenticatedPeer is returned only after the caller verifies mutual key confirmation. type AuthenticatedPeer struct { // Identity binds renewals of an existing node to the original PQ identity. @@ -143,9 +139,7 @@ func (j *bootstrapAdmission) finish(installed bool) { } // completeBootstrapLocked commits an admission or renewal on the shared -// bootstrap worker. peerLifecycleMu remains held through route installation, -// the installation callback, and acknowledgement, so disconnect cannot remove -// a route before a pending installation adds it. +// bootstrap worker. The caller holds peerLifecycleMu through acknowledgement. func (b *locoBackend) completeBootstrapLocked(j *bootstrapAdmission) { select { case <-b.bootstrapDone: @@ -184,11 +178,6 @@ func (b *locoBackend) completeBootstrapLocked(j *bootstrapAdmission) { if owned >= maxSessionsPerIdentity { b.mu.Unlock() b.removeAuthenticatedPeer(oldest) - if b.tunnelPeer != nil { - if err := b.tunnelPeer(oldest, false); err != nil { - b.logf("removing evicted tunnel peer: %v", err) - } - } b.mu.Lock() } if len(b.peerPSKs) >= 4096 { @@ -202,13 +191,6 @@ func (b *locoBackend) completeBootstrapLocked(j *bootstrapAdmission) { b.peerInstalled[j.src] = time.Now() b.addClientLocked(j.src, peer.Disco) b.mu.Unlock() - if b.tunnelPeer != nil { - if err := b.tunnelPeer(j.src, true); err != nil { - b.removeAuthenticatedPeer(j.src) - j.finish(false) - return - } - } } j.finish(true) } diff --git a/third_party/tailcat/tailcat.go b/third_party/tailcat/tailcat.go index a4f9044..62119e5 100644 --- a/third_party/tailcat/tailcat.go +++ b/third_party/tailcat/tailcat.go @@ -62,7 +62,6 @@ import ( "github.com/fxamacker/cbor/v2" "github.com/tailscale/wireguard-go/device" - "github.com/tailscale/wireguard-go/tun" go4mem "go4.org/mem" "go4.org/netipx" "gvisor.dev/gvisor/pkg/tcpip/adapters/gonet" @@ -331,14 +330,12 @@ func NewPrivateKey() *PrivateKey { // but there's no controlclient involved, because there's // no control plane. type locoBackend struct { - // peerLifecycleMu orders complete installations, including route callbacks, - // against disconnection, eviction, and expiry. Admission hooks never hold it. + // peerLifecycleMu serializes installation, disconnection, eviction, and expiry. + // Admission hooks never hold it. peerLifecycleMu sync.Mutex admissions map[key.NodePublic]*bootstrapAdmission // guarded by peerLifecycleMu bootstrapStopped chan struct{} bootstrapClose func() - tunDevice tun.Device - tunnelPeer func(key.NodePublic, bool) error peerValid map[key.NodePublic]func() bool peerOwners map[key.NodePublic][32]byte peerInstalled map[key.NodePublic]time.Time @@ -466,12 +463,6 @@ func (b *locoBackend) Close() error { type Server struct { BootstrapCleanup func() BootstrapClose func() - // TUN enables IP mode. OnTunnelPeer installs/removes only an authenticated - // peer's host route. It must be set together with TUN. - // Route callbacks are serialized with peer installation and disconnection; - // they must not synchronously call DisconnectClient or Close. - TUN tun.Device - OnTunnelPeer func(key.NodePublic, bool) error // Bootstrap replaces legacy Meow authorization when non-nil. // The callback runs on a bounded, serialized worker. Bootstrap func(key.NodePublic, []byte) ([]byte, *AuthenticatedPeer) @@ -738,8 +729,6 @@ func (s *Server) startLocked(ctx context.Context) error { lb.isServer = true lb.bootstrapClose = s.BootstrapClose - lb.tunDevice = s.TUN - lb.tunnelPeer = s.OnTunnelPeer if s.Bootstrap != nil { lb.authenticated = true lb.peerPSKs = make(map[key.NodePublic]PresharedKey) @@ -810,9 +799,6 @@ func (s *Server) startLocked(ctx context.Context) error { lb.mu.Unlock() for _, k := range removed { lb.sys.Engine.Get().SyncDevicePeer(k) - if lb.tunnelPeer != nil { - lb.tunnelPeer(k, false) - } } lb.peerLifecycleMu.Unlock() continue @@ -929,10 +915,6 @@ func (s *Server) startLocked(ctx context.Context) error { } ns.ProcessLocalIPs = true ns.ProcessSubnets = true - if s.TUN != nil { - ns.ProcessLocalIPs = false - ns.ProcessSubnets = false - } ns.GetTCPHandlerForFlow = func(src, dst netip.AddrPort) (handler func(net.Conn), intercept bool) { if dst.Addr() == lb.addr { if ln := s.listenerForPort("tcp", dst.Port()); ln != nil { @@ -1045,18 +1027,6 @@ func appendListenerPorts(ranges []filter.PortRange, m map[uint16]*listener) []fi // s.listenerMu must be held. func (s *Server) buildFilterLocked() *filter.Filter { lb := s.lb - if s.TUN != nil { - local := new(netipx.IPSetBuilder) - local.AddPrefix(lb.addrPrefix) - set, _ := local.IPSet() - rules := []filter.Match{{ - IPProto: views.SliceOf([]ipproto.Proto{ipproto.TCP, ipproto.UDP, ipproto.ICMPv6}), - Srcs: []netip.Prefix{netip.MustParsePrefix("fd7a:7163:6174::/48")}, - Dsts: []filter.NetPortRange{{Net: lb.addrPrefix, Ports: allPorts}}, - }} - return filter.New(rules, nil, set, tailcatULASet(), nil, lb.logf) - } - selfPorts := []filter.PortRange{allPorts} if s.ServedTCPPorts != nil { selfPorts = appendListenerPorts(slices.Clone(s.ServedTCPPorts), s.tcpListeners) @@ -1258,13 +1228,7 @@ func (s *Server) DisconnectClient(k key.NodePublic) bool { if job := s.lb.admissions[k]; job != nil { job.cancelled = true } - removed := s.lb.removeAuthenticatedPeer(k) - if removed && s.lb.tunnelPeer != nil { - if err := s.lb.tunnelPeer(k, false); err != nil { - s.lb.logf("removing disconnected tunnel peer: %v", err) - } - } - return removed + return s.lb.removeAuthenticatedPeer(k) } // TailcatAddr returns the tailcat address that clients use to connect to this @@ -1724,9 +1688,6 @@ func (b *locoBackend) peerConfig(k key.NodePublic) (_ wgcfg.PeerConfig, ok bool) // We're the client; the server is our only peer and may send // from any address (it can act as an exit node). if k == b.serverPub { - if b.tunDevice != nil { - return withPSK([]netip.Prefix{pfxOf(tcAddrForKey(k))}), true - } return withPSK([]netip.Prefix{pfxOf(tcAddrForKey(k)), allIPv6}), true } return wgcfg.PeerConfig{}, false @@ -2098,8 +2059,8 @@ func (b *locoBackend) setNetworkMapLocked() { b.sys.Netstack.Get().UpdateNetstackIPs(nm) } -// removeAuthenticatedPeer rolls back all networking state after a failed install. -// The caller must hold peerLifecycleMu through any accompanying route removal. +// removeAuthenticatedPeer removes the peer from the network map and WireGuard. +// The caller must hold peerLifecycleMu. func (b *locoBackend) removeAuthenticatedPeer(k key.NodePublic) bool { b.mu.Lock() _, removed := b.clients[k] @@ -2179,7 +2140,6 @@ func newNetstack(logf logger.Logf, sys *tsd.System) (*netstack.Impl, error) { func createEngine(logf logger.Logf, lb *locoBackend) (err error) { sys := &lb.sys conf := wgengine.Config{ - Tun: lb.tunDevice, ListenPort: 0, NetMon: sys.NetMon.Get(), Dialer: sys.Dialer.Get(), @@ -2219,7 +2179,6 @@ func createEngine(logf logger.Logf, lb *locoBackend) (err error) { // and is useful to test connectivity first or to measure the relay // round-trip time. type Client struct { - TUN tun.Device Bootstrap func(context.Context, func([]byte) error, <-chan []byte) (PresharedKey, error) bootstrapInbox chan []byte // Server is the tailcat address identifying the server to connect to. @@ -2303,7 +2262,6 @@ func (c *Client) initLocked() error { return errors.New("legacy tailcat address lacks a separate disco key; generate a new address with an updated tailcat server") } lb := newLocoBackend(c.nodeKeyLocked(), ci.PresharedKey) - lb.tunDevice = c.TUN if c.Bootstrap != nil { lb.authenticated = true lb.presharedKey = PresharedKey{} @@ -2377,9 +2335,6 @@ func (c *Client) initLocked() error { return fmt.Errorf("newNetstack: %w", err) } ns.ProcessLocalIPs = true // required to even reply to TCP SYNs client sends out - if c.TUN != nil { - ns.ProcessLocalIPs = false - } ns.GetTCPHandlerForFlow = func(src, dst netip.AddrPort) (handler func(net.Conn), intercept bool) { return nil, true // don't accept any incoming connections to client } @@ -2395,10 +2350,6 @@ func (c *Client) initLocked() error { localNets.AddPrefix(lb.addrPrefix) local, _ := localNets.IPSet() e.SetFilter(filter.New(nil, nil, local, tailcatULASet(), nil, logf)) - if c.TUN != nil { - rules := []filter.Match{{IPProto: views.SliceOf([]ipproto.Proto{ipproto.TCP, ipproto.UDP, ipproto.ICMPv6}), Srcs: []netip.Prefix{pfxOf(tcAddrForKey(lb.serverPub))}, Dsts: []filter.NetPortRange{{Net: lb.addrPrefix, Ports: allPorts}}}} - e.SetFilter(filter.New(rules, nil, local, tailcatULASet(), nil, logf)) - } dialer.UseNetstackForIP = func(ip netip.Addr) bool { _, ok := lb.peerByIP(ip) return ok