From 68ca66b799fd95d266fa13b8ab18ecc5a1cbaddc Mon Sep 17 00:00:00 2001 From: cnupy <38653063+cnupy@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:42:46 +0200 Subject: [PATCH] tailcat: give each Client a fresh disco key A client's disco key was derived from its node key, so a client process that restarted with the same key file came back with the same disco key. The server's onMeow returned early for a known client, so the server's magicsock kept the old process's direct UDP path. Its WireGuard handshake response went to that dead port, and the new client only got through on the handshake retry, about 5 s later. Clients now use a fresh disco key per Client. The server still derives its disco key from its node key, since that key is part of its address. When a known client sends a meow with a new disco key, onMeow updates the key in the netmap, so magicsock drops the old path and replies go through DERP until the new direct path is found. TestClientRestartSameKey restarts a client twice with the same node key after it has a direct path. Each time it hands the new process's meow to the server before the client goes on the network (MeowForTest) and checks that the server stops using the old address, then dials. Handing over the meow first keeps the test from depending on how fast the new client advertises its endpoints, which hid the bug on Linux. Fixes #199 Signed-off-by: cnupy <38653063+cnupy@users.noreply.github.com> --- export_test.go | 14 ++++++ tailcat.go | 58 ++++++++++++++++------- tailcat_test.go | 122 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 176 insertions(+), 18 deletions(-) diff --git a/export_test.go b/export_test.go index 7a3ab3bc5..d3c1a2381 100644 --- a/export_test.go +++ b/export_test.go @@ -31,6 +31,20 @@ func WaitForDERPForTest(t testing.TB, s *Server, c *Client) { } } +// MeowForTest sets up c's network stack without going on the network and +// hands its meow straight to s, as if it had arrived over DERP. A test can +// then check how s took the client before c advertises any endpoints. +func MeowForTest(t testing.TB, s *Server, c *Client) { + t.Helper() + c.startMu.Lock() + err := c.initLocked() + c.startMu.Unlock() + if err != nil { + t.Fatalf("initializing client: %v", err) + } + s.lb.onMeow(c.lb.pub, c.lb.discoPublic()) +} + // PingForTest waits for the client's DERP connection and performs the // meow/meowed handshake. func PingForTest(t testing.TB, s *Server, c *Client) PingResult { diff --git a/tailcat.go b/tailcat.go index 52e0723c2..a09b670a8 100644 --- a/tailcat.go +++ b/tailcat.go @@ -375,6 +375,12 @@ type locoBackend struct { hybrid bool // whether to use the hybrid post-quantum WireGuard handshake isServer bool + // discoPriv is the node's path-discovery key. A server derives it from + // its node key, because the key is part of its address. A client gets a + // fresh one per Client, so a server can tell a restarted client from the + // old one and drop the old one's direct path. + discoPriv key.DiscoPrivate + // discoPublic returns the node's disco public key, memoized to // avoid redoing the curve25519 derivation for every client that // joins. @@ -686,7 +692,7 @@ func (s *Server) startLocked(ctx context.Context) error { return fmt.Errorf("missing RegionID in %v", logger.AsJSON(reg)) } - lb := newLocoBackend(priv, psk) + lb := newLocoBackend(priv, discoPrivateForNode(priv), psk) lb.hybrid = s.Hybrid lb.logf = logf lb.dm = &tailcfg.DERPMap{} @@ -1060,7 +1066,9 @@ func (s *Server) TailcatAddr() Addr { return s.lb.tailcatAddr() } -func newLocoBackend(priv key.NodePrivate, psk PresharedKey) *locoBackend { +// newLocoBackend returns a backend for node key priv that uses discoPriv +// for path discovery. +func newLocoBackend(priv key.NodePrivate, discoPriv key.DiscoPrivate, psk PresharedKey) *locoBackend { pub := priv.Public() addr := tcAddrForKey(pub) addrPrefix := netip.PrefixFrom(addr, addr.BitLen()) @@ -1071,8 +1079,9 @@ func newLocoBackend(priv key.NodePrivate, psk PresharedKey) *locoBackend { addr: addr, addrPrefix: addrPrefix, presharedKey: psk, + discoPriv: discoPriv, } - lb.discoPublic = sync.OnceValue(func() key.DiscoPublic { return discoPrivateForNode(lb.priv).Public() }) + lb.discoPublic = sync.OnceValue(func() key.DiscoPublic { return lb.discoPriv.Public() }) return lb } @@ -1656,8 +1665,9 @@ func (b *locoBackend) onEngineStatus(st *wgengine.Status, err error) { // control plane flow uses in regular Tailscale. The peer's magicsock // reacts by disco-pinging those endpoints, which both teaches it a // direct path to us and teaches us its address from the pings we -// receive back. It's called whenever our endpoints change and when a -// peer first completes the meow handshake, and is idempotent. +// receive back. It's called whenever our endpoints change, when a peer +// first completes the meow handshake, and when a known client comes back +// with a new disco key. It is idempotent. func (b *locoBackend) advertiseEndpoints() { if runtime.GOOS == "js" { // In browsers this does nothing: js/wasm has no UDP, so @@ -1678,7 +1688,6 @@ func (b *locoBackend) advertiseEndpoints() { return } payload := (&disco.CallMeMaybe{MyNumber: eps}).AppendMarshal(nil) - discoPriv := discoPrivateForNode(b.priv) mc := b.sys.MagicSock.Get() regionID := b.derpRegionID() for _, p := range peers { @@ -1688,7 +1697,7 @@ func (b *locoBackend) advertiseEndpoints() { pkt := make([]byte, 0, 512) pkt = append(pkt, disco.Magic...) pkt = b.discoPublic().AppendTo(pkt) - pkt = append(pkt, discoPriv.Shared(p.DiscoKey()).Seal(payload)...) + pkt = append(pkt, b.discoPriv.Shared(p.DiscoKey()).Seal(payload)...) if _, err := mc.SendDERPPacketTo(p.Key(), regionID, pkt); err != nil { b.logf("advertiseEndpoints to %v: %v", p.Key().ShortString(), err) } @@ -1811,14 +1820,27 @@ func (lb *locoBackend) Start() error { } // onMeow handles a MeowPing from the client with node key src and -// disco key discoPub, adding it as a WireGuard peer. It reports -// whether the client is allowed and configured, meaning a "meowed" +// disco key discoPub, adding it as a WireGuard peer. For a client it +// already knows that comes back with a different disco key (a restarted +// client), it updates the peer's disco key instead. It reports whether +// the client is allowed and configured, meaning a "meowed" // acknowledgment may be sent. func (b *locoBackend) onMeow(src key.NodePublic, discoPub key.DiscoPublic) bool { b.logf("got meow from %v", src.String()) b.mu.Lock() defer b.mu.Unlock() - if _, ok := b.clients[src]; ok { + if n, ok := b.clients[src]; ok { + if n.DiscoKey == discoPub { + return true + } + // The client restarted with a new disco key. Updating it makes + // magicsock forget the old process's direct path, so replies go + // through DERP until the new path is found. + n = n.Clone() // the old netmap still holds views of n + n.DiscoKey = discoPub + b.clients[src] = n + b.setNetworkMapLocked() + go b.advertiseEndpoints() return true } if b.allowClient != nil { @@ -2018,13 +2040,13 @@ func createEngine(logf logger.Logf, lb *locoBackend) (err error) { if lb.isServer { conf.DERPAppName = "tailcat-server" } - // Both sides deterministically derive a separate disco key from their - // node private key. The public disco key, unlike the node key, is safe to - // expose in direct-path disco frames. Knowing our own disco private key - // is what lets either side seal the - // call-me-maybe messages that advertise our UDP endpoints (see - // locoBackend.advertiseEndpoints). - conf.ForceDiscoKey = discoPrivateForNode(lb.priv) + // The server derives a separate disco key from its node private key, + // and a client uses a fresh one (see locoBackend.discoPriv). The public + // disco key, unlike the node key, is safe to expose in direct-path + // disco frames. Knowing our own disco private key is what lets either + // side seal the call-me-maybe messages that advertise our UDP + // endpoints (see locoBackend.advertiseEndpoints). + conf.ForceDiscoKey = lb.discoPriv netns.SetEnabled(false) e, err := wgengine.NewUserspaceEngine(logf, conf) if err != nil { @@ -2122,7 +2144,7 @@ func (c *Client) initLocked() error { if ci.ServerDiscoPublic.IsZero() { 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 := newLocoBackend(c.nodeKeyLocked(), key.NewDisco(), ci.PresharedKey) lb.logf = logf lb.dm = &tailcfg.DERPMap{} lb.serverPub = ci.ServerPublic.NodePublic diff --git a/tailcat_test.go b/tailcat_test.go index 6bc880c62..f3515d4ba 100644 --- a/tailcat_test.go +++ b/tailcat_test.go @@ -638,6 +638,128 @@ func TestDisconnectClient(t *testing.T) { } } +// TestClientRestartSameKey checks that when a client process restarts +// with the same node key, the server stops using the old process's +// direct UDP path as soon as the new process's meow arrives. The server +// used to keep that path, so its WireGuard handshake response could go +// to a dead port and the new client waited for the handshake retry, +// about 5 s. +func TestClientRestartSameKey(t *testing.T) { + t.Parallel() + + dm := integration.RunDERPAndSTUN(t, mkLogger(t, "derpstun"), "127.0.0.1") + reg := dm.Regions[1] + if reg == nil { + t.Fatal("no region 1 in derpmap") + } + + s := &Server{Key: key.NewNode(), Logf: mkLogger(t, "server"), Region: reg} + t.Cleanup(func() { s.Close() }) + s.OnTCP = func(port uint16) func(net.Conn) { + if port != 80 { + return nil + } + return func(c net.Conn) { + io.WriteString(c, "hello\n") + c.Close() + } + } + if err := s.Start(); err != nil { + t.Fatalf("server Start: %v", err) + } + + dial := func(c *Client, timeout time.Duration) (time.Duration, error) { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + t0 := time.Now() + conn, err := c.DialTCPPort(ctx, 80) + if err != nil { + return 0, err + } + defer conn.Close() + conn.SetReadDeadline(time.Now().Add(timeout)) + got, err := io.ReadAll(conn) + if err != nil { + return 0, err + } + if string(got) != "hello\n" { + return 0, fmt.Errorf("read %q; want %q", got, "hello\n") + } + return time.Since(t0), nil + } + + nodeKey := key.NewNode() + + // serverPath reports the direct address the server uses for nodeKey, + // or "" if it sends over DERP. + serverPath := func() string { + if ps, ok := s.Status().Peer[nodeKey.Public()]; ok { + return ps.CurAddr + } + return "" + } + // waitDirect waits until c and the server both use a direct path and + // returns the server's address for c. + waitDirect := func(c *Client) string { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + res, err := c.DiscoPing(ctx) + cancel() + if err == nil && res.Endpoint != "" { + if p := serverPath(); p != "" { + return p + } + } + if time.Now().After(deadline) { + t.Fatalf("no direct path both ways (last ping %+v, %v; server path %q)", res, err, serverPath()) + } + time.Sleep(100 * time.Millisecond) + } + } + + prev := &Client{Server: s.TailcatAddr(), Key: nodeKey, Logf: mkLogger(t, "client0")} + t.Cleanup(func() { prev.Close() }) + PingForTest(t, s, prev) + if _, err := dial(prev, 10*time.Second); err != nil { + t.Fatalf("client0: %v", err) + } + + // Restart twice, so the second restart replaces a client that was + // itself a restart. + for i := 1; i <= 2; i++ { + oldPath := waitDirect(prev) + prev.Close() + // WireGuard rounds handshake timestamps down to about 16.8 ms and + // rejects one that isn't newer than the last from the same key + // as a replay. A real process restart takes longer than that. + time.Sleep(50 * time.Millisecond) + + name := fmt.Sprintf("client%d", i) + c := &Client{Server: s.TailcatAddr(), Key: nodeKey, Logf: mkLogger(t, name)} + t.Cleanup(func() { c.Close() }) + + // Hand the new process's meow to the server before the client goes + // on the network. Once it is up, the client advertises its endpoints, + // and on a fast machine the server can find the new path that way + // before the first dial, which hides the bug. Here only the meow can + // make the server drop the previous process's path. + MeowForTest(t, s, c) + if p := serverPath(); p == oldPath { + t.Errorf("%s: after the new process's meow, the server still sends to the previous process at %s", name, p) + } + + PingForTest(t, s, c) + d, err := dial(c, 10*time.Second) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + t.Logf("%s dialed in %v", name, d) + prev = c + } +} + func TestUDP(t *testing.T) { dm := integration.RunDERPAndSTUN(t, mkLogger(t, "derpstun"), "127.0.0.1") reg := dm.Regions[1]