From 4e869858eb39a77aa230b313d2d590d165d567ba Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Wed, 2 Dec 2026 03:01:58 +0000 Subject: [PATCH] tailcat: stop trusting a restarted client's old direct path A client's disco key is derived from its node key, so a client process that restarts with the same key file comes back with the same disco key. The server's onMeow returned early for a known client, so the server's magicsock kept trusting 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 append a random 8-byte instance ID, one per Client, to their meow pings. When a known client's meow carries a different instance ID, the server makes magicsock stop trusting its direct path, so replies also go over DERP until a new direct path is confirmed. A retried meow or a later Ping from the same Client repeats the ID and keeps a good path. To reset the path, the server upserts the peer into magicsock with a throwaway disco key and then with the real one, which reuses magicsock's handling of a peer whose disco key changed. Removing and re-adding the peer doesn't work: the WireGuard peer keeps sending through the removed magicsock endpoint. PR #201 instead gave each Client a fresh disco key, but then a new client restarting against an older server would be stuck on DERP: the old server keeps the first disco key it saw. With the instance ID, every mix of old and new clients and servers behaves at least as before. Old servers ignore the extra bytes, as ParseMeowPing always has, and old clients send none, so new servers never reset their paths. Measured with the tailcat binary on a local DERP, eight restarts of a client process sharing one saved key took 0.07 s each with a new client and server. Every other mix of old and new still took about 5 s on two or three of the eight. TestClientRestartSameKey and the MeowForTest helper are from PR #201, along with the diagnosis. The test now also checks that a repeated meow from the same Client keeps its direct path. Fixes #199 Co-authored-by: cnupy <38653063+cnupy@users.noreply.github.com> Signed-off-by: Brad Fitzpatrick --- disco.go | 30 +++++++++++ disco_test.go | 28 +++++++++++ export_test.go | 14 ++++++ tailcat.go | 62 ++++++++++++++++++++--- tailcat_test.go | 130 ++++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 257 insertions(+), 7 deletions(-) diff --git a/disco.go b/disco.go index 28d5d3aeb..82f6b5fe6 100644 --- a/disco.go +++ b/disco.go @@ -68,3 +68,33 @@ func ParseMeowPing(pkt []byte) (nodeKey key.NodePublic, discoKey key.DiscoPublic func IsMeowedPacket(pkt []byte) bool { return len(pkt) >= 5 && [4]byte(pkt[:4]) == meowMagic && pkt[4] == meowTypePong } + +// meowInstanceLen is the length of the optional instance ID that follows +// the keys in a meow ping. +const meowInstanceLen = 8 + +// meowInstanceID identifies one [Client] value, and so one client process. +// Clients send it after the keys in every meow ping. The server compares it +// with the instance ID it saw last for the same node key, so it can tell a +// restarted client from a retried meow even though the disco key, which is +// derived from the node key, stays the same. The zero value means that the +// client didn't send one, as clients older than v0.9.0 don't. +type meowInstanceID [meowInstanceLen]byte + +// appendMeowInstance appends id to a meow ping from [EncodeMeowPing]. +// Servers older than v0.9.0 ignore it, because [ParseMeowPing] ignores +// trailing bytes. +func appendMeowInstance(pkt []byte, id meowInstanceID) []byte { + return append(pkt, id[:]...) +} + +// parseMeowInstance returns the instance ID in a meow ping that +// [ParseMeowPing] accepted, or the zero value if it has none. +func parseMeowInstance(pkt []byte) meowInstanceID { + const off = 4 + 1 + key.NodePublicRawLen + key.DiscoPublicRawLen + var id meowInstanceID + if len(pkt) >= off+meowInstanceLen { + copy(id[:], pkt[off:]) + } + return id +} diff --git a/disco_test.go b/disco_test.go index dd83a64f5..a55d63841 100644 --- a/disco_test.go +++ b/disco_test.go @@ -174,3 +174,31 @@ func TestMeowMagicDistinct(t *testing.T) { t.Error("meow magic collides with disco magic") } } + +// TestMeowInstance checks the optional instance ID after the keys in a +// meow ping, including that a ping without one, from a client older than +// v0.9.0, reads as the zero ID. +func TestMeowInstance(t *testing.T) { + nodeKey := key.NewNode().Public() + discoKey := key.NewDisco().Public() + old := EncodeMeowPing(nodeKey, discoKey) + if got := parseMeowInstance(old); got != (meowInstanceID{}) { + t.Errorf("instance ID of a ping without one = %x; want zero", got) + } + + id := meowInstanceID{1, 2, 3, 4, 5, 6, 7, 8} + pkt := appendMeowInstance(EncodeMeowPing(nodeKey, discoKey), id) + if got := parseMeowInstance(pkt); got != id { + t.Errorf("instance ID = %x; want %x", got, id) + } + // ParseMeowPing, as in servers older than v0.9.0, must still accept + // the longer ping. + gotNode, gotDisco, ok := ParseMeowPing(pkt) + if !ok || gotNode != nodeKey || gotDisco != discoKey { + t.Errorf("ParseMeowPing of a ping with an instance ID = %v, %v, %v", gotNode, gotDisco, ok) + } + // A truncated instance ID reads as none. + if got := parseMeowInstance(pkt[:len(pkt)-1]); got != (meowInstanceID{}) { + t.Errorf("instance ID of a truncated ping = %x; want zero", got) + } +} diff --git a/export_test.go b/export_test.go index 7a3ab3bc5..c54ff9b43 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(), c.lb.meowInstance) +} + // 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..7ec393c20 100644 --- a/tailcat.go +++ b/tailcat.go @@ -395,6 +395,15 @@ type locoBackend struct { nm *netmap.NetworkMap eps []netip.AddrPort // our current local UDP endpoints, sorted closeOnce sync.Once + + // clientInstance is, for the server, the meow instance ID last seen + // from each client in clients. It has an entry exactly when clients + // does, which is zero for a client too old to send one. + clientInstance map[key.NodePublic]meowInstanceID + + // meowInstance is, for a client, the instance ID it sends in its + // meow pings. + meowInstance meowInstanceID } func (b *locoBackend) derpRegionID() tailcfg.DERPRegionID { @@ -715,12 +724,13 @@ func (s *Server) startLocked(ctx context.Context) error { return true // server ignores meowed } if _, discoPub, ok := ParseMeowPing(pkt); ok { + inst := parseMeowInstance(pkt) mc := lb.sys.MagicSock.Get() go func() { // Only reply once the client is fully added as a peer: // "meowed" is the ack that tells the client it can // start dialing. Disallowed clients get no reply. - if lb.onMeow(src, discoPub) { + if lb.onMeow(src, discoPub, inst) { mc.SendDERPPacketTo(src, regionID, EncodeMeowed()) } }() @@ -1810,15 +1820,26 @@ func (lb *locoBackend) Start() error { return nil } -// 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" -// acknowledgment may be sent. -func (b *locoBackend) onMeow(src key.NodePublic, discoPub key.DiscoPublic) bool { +// onMeow handles a MeowPing from the client with node key src, disco +// key discoPub, and instance ID inst, adding it as a WireGuard peer. It +// reports whether the client is allowed and configured, meaning a +// "meowed" acknowledgment may be sent. +// +// A meow from a known client with a different instance ID comes from a +// new process using the same node key, such as a restarted client. The +// server then stops trusting the old process's direct path (see +// resetClientPathLocked). +func (b *locoBackend) onMeow(src key.NodePublic, discoPub key.DiscoPublic, inst meowInstanceID) bool { b.logf("got meow from %v", src.String()) b.mu.Lock() defer b.mu.Unlock() if _, ok := b.clients[src]; ok { + if b.clientInstance[src] != inst { + b.logf("client %v restarted; resetting its path", src.ShortString()) + b.clientInstance[src] = inst + b.resetClientPathLocked(src) + go b.advertiseEndpoints() + } return true } if b.allowClient != nil { @@ -1860,6 +1881,7 @@ func (b *locoBackend) onMeow(src key.NodePublic, discoPub key.DiscoPublic) bool AllowedIPs: []netip.Prefix{pfxOf(tcAddrForKey(src))}, HomeDERP: b.derpRegionID(), }) + mak.Set(&b.clientInstance, src, inst) b.setNetworkMapLocked() // No engine reconfig needed: the WireGuard device learns about the @@ -1911,10 +1933,35 @@ func (b *locoBackend) removeClientLocked(k key.NodePublic) bool { return false } delete(b.clients, k) + delete(b.clientInstance, k) b.setNetworkMapLocked() return true } +// resetClientPathLocked makes magicsock stop trusting the direct UDP +// path it has for the connected client k, which may lead to an earlier +// process using k. Otherwise the server would keep sending only to that +// path, including its WireGuard handshake response to the new process, +// which would then wait about 5 s for the handshake retry (see issue +// #199). Until a new direct path is confirmed, magicsock also sends +// over DERP. +// +// Magicsock does this when a peer's disco key changes, but that can't +// signal a restarted client: its disco key is derived from its node key, +// so it's the same in every process. Instead, this briefly gives +// magicsock a throwaway disco key for k and then the real one again. +// Each change resets the path in place. Removing and re-adding k +// wouldn't work, because the WireGuard peer would keep sending through +// the removed magicsock endpoint. b.mu must be held. +func (b *locoBackend) resetClientPathLocked(k key.NodePublic) { + n := b.clients[k] + mc := b.sys.MagicSock.Get() + tmp := n.Clone() + tmp.DiscoKey = key.NewDisco().Public() + mc.UpsertPeer(tmp.View()) + mc.UpsertPeer(n.View()) +} + func (b *locoBackend) Status() *ipnstate.Status { mc := b.sys.MagicSock.Get() eng := b.sys.Engine.Get() @@ -2123,6 +2170,7 @@ 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) + cryptorand.Read(lb.meowInstance[:]) lb.logf = logf lb.dm = &tailcfg.DERPMap{} lb.serverPub = ci.ServerPublic.NodePublic @@ -2333,7 +2381,7 @@ func (c *Client) ping(ctx context.Context) (PingResult, error) { dstNode := c.ci.ServerPublic.NodePublic derpRegion := c.lb.derpRegionID() - pkt := EncodeMeowPing(c.lb.pub, mc.DiscoPublicKey()) + pkt := appendMeowInstance(EncodeMeowPing(c.lb.pub, mc.DiscoPublicKey()), c.lb.meowInstance) // DERP delivery is best effort: the relay drops packets sent to a // key that isn't connected yet, so the ping (or its ack) is lost diff --git a/tailcat_test.go b/tailcat_test.go index 6bc880c62..b42779e10 100644 --- a/tailcat_test.go +++ b/tailcat_test.go @@ -638,6 +638,136 @@ 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) + + // Another meow from the same Client, like a retry or a later + // Ping, must keep the direct path. + MeowForTest(t, s, prev) + if p := serverPath(); p == "" { + t.Errorf("client%d: a repeated meow from the same Client dropped its direct path %s", i-1, oldPath) + } + + 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]