diff --git a/control/controlclient/map.go b/control/controlclient/map.go index 1d8b76a73..5552eadea 100644 --- a/control/controlclient/map.go +++ b/control/controlclient/map.go @@ -1001,11 +1001,42 @@ func (ms *mapSession) sortedPeers() []tailcfg.NodeView { return ret } +var metricDupKeyPeersDropped = clientmetric.NewCounter("controlclient_dup_key_peers_dropped") + +// dropDupKeyPeers removes peers whose node key is also used by a peer with a +// higher node ID, modifying peers in place and returning the shortened slice. +// The peers must be sorted by node ID, as returned by +// [mapSession.sortedPeers]. +// +// Control should never send two peers with the same node key; it's a server +// bug if it does. The rest of the client (magicsock, wgengine) requires node +// keys to be unique, so keep only the highest node ID (normally the newest +// node) and log loudly about the rest. See +// https://github.com/tailscale/corp/issues/52092. +func (ms *mapSession) dropDupKeyPeers(peers []tailcfg.NodeView) []tailcfg.NodeView { + winner := make(map[key.NodePublic]tailcfg.NodeID, len(peers)) + dups := false + for _, p := range peers { + if lower, ok := winner[p.Key()]; ok { + dups = true + metricDupKeyPeersDropped.Add(1) + ms.logf("[unexpected] controlclient: control sent peers %v and %v with the same node key %s; ignoring %v", lower, p.ID(), p.Key().ShortString(), lower) + } + winner[p.Key()] = p.ID() // later peers have higher IDs, so they win + } + if !dups { + return peers + } + return slices.DeleteFunc(peers, func(p tailcfg.NodeView) bool { + return winner[p.Key()] != p.ID() + }) +} + // netmap returns a fully populated NetworkMap from the last state seen from // a call to updateStateFromResponse, filling in omitted // information from prior MapResponse values. func (ms *mapSession) netmap() *netmap.NetworkMap { - peerViews := ms.sortedPeers() + peerViews := ms.dropDupKeyPeers(ms.sortedPeers()) var msgs map[tailcfg.DisplayMessageID]tailcfg.DisplayMessage if len(ms.lastDisplayMessages) != 0 { diff --git a/control/controlclient/map_test.go b/control/controlclient/map_test.go index ac8df74ae..bc4663c09 100644 --- a/control/controlclient/map_test.go +++ b/control/controlclient/map_test.go @@ -11,6 +11,7 @@ import ( "maps" "net/netip" "reflect" + "slices" "strings" "sync/atomic" "testing" @@ -404,6 +405,44 @@ func (ms *mapSession) netmapForResponse(res *tailcfg.MapResponse) *netmap.Networ return ms.netmap() } +// TestNetmapDropsDupKeyPeers tests that when control sends several peers with +// the same node key, the netmap keeps only the one with the highest node ID. +// See https://github.com/tailscale/corp/issues/52092. +func TestNetmapDropsDupKeyPeers(t *testing.T) { + k := key.NewNode().Public() + other := key.NewNode().Public() + ms := newTestMapSession(t, nil) + peerIDs := func(nm *netmap.NetworkMap) (ids []tailcfg.NodeID) { + for _, p := range nm.Peers { + ids = append(ids, p.ID()) + } + return ids + } + + nm := ms.netmapForResponse(&tailcfg.MapResponse{ + Node: new(tailcfg.Node), + Peers: []*tailcfg.Node{ + {ID: 4, Key: k}, + {ID: 1, Key: k}, + {ID: 2, Key: other}, + {ID: 3, Key: k}, + }, + }) + if got, want := peerIDs(nm), []tailcfg.NodeID{2, 4}; !slices.Equal(got, want) { + t.Errorf("peers = %v; want %v", got, want) + } + + // Once control removes the winner, the next highest node ID with that + // key takes its place. + nm = ms.netmapForResponse(&tailcfg.MapResponse{ + Node: new(tailcfg.Node), + PeersRemoved: []tailcfg.NodeID{4}, + }) + if got, want := peerIDs(nm), []tailcfg.NodeID{2, 3}; !slices.Equal(got, want) { + t.Errorf("after removal, peers = %v; want %v", got, want) + } +} + func TestNetmapForResponse(t *testing.T) { t.Run("implicit_packetfilter", func(t *testing.T) { somePacketFilter := []tailcfg.FilterRule{ diff --git a/wgengine/magicsock/magicsock.go b/wgengine/magicsock/magicsock.go index edda0be72..b13f37d36 100644 --- a/wgengine/magicsock/magicsock.go +++ b/wgengine/magicsock/magicsock.go @@ -3265,24 +3265,31 @@ func (c *Conn) updateNodes(self tailcfg.NodeView, peers []tailcfg.NodeView) (pee entriesPerBuffer := debugRingBufferSize(len(peers)) - // Build the new peer map while upserting each peer. newPeers := make(map[tailcfg.NodeID]tailcfg.NodeView, len(peers)) for _, n := range peers { newPeers[n.ID()] = n - c.upsertPeerLocked(n, flags, entriesPerBuffer) } if len(newPeers) != len(peers) { // Duplicate NodeIDs in the input shouldn't happen, but log if so. c.logf("[unexpected] magicsock.updateNodes: %d peers input but %d unique IDs", len(peers), len(newPeers)) } - // Clean up node-key-keyed state for peers that are gone or have - // rotated their node key. + // Clean up state for peers that are gone or have rotated their node + // key before upserting, so a node key handed from a removed node to a + // new node (control deleted a node and the machine re-registered with + // its old node key) isn't seen as a conflict by upsertPeerLocked. + // See https://github.com/tailscale/corp/issues/52092. for id, prev := range c.peersByID { if n, ok := newPeers[id]; !ok || n.Key() != prev.Key() { delete(c.derpRoute, prev.Key()) delete(c.peerLastDerp, prev.Key()) + if ep, ok := c.peerMap.endpointForNodeID(id); ok { + c.peerMap.deleteEndpoint(ep) + } } } + for _, n := range peers { + c.upsertPeerLocked(n, flags, entriesPerBuffer) + } hadPeers := len(c.peersByID) > 0 c.peersByID = newPeers // A key-less conn can't STUN; the ReSTUN("set-private-key") on @@ -3370,18 +3377,14 @@ func (c *Conn) upsertPeerLocked(n tailcfg.NodeView, flags debugFlags, entriesPer // we don't get this far. If ok was false above, that means it's a key // that differs from the one the NodeID had. But double check. if ep.nodeID != n.ID() { - // Server error. This is known to be a particular issue for Mullvad - // nodes (http://go/corp/27300), so log a distinct error for the - // Mullvad and non-Mullvad cases. The error will be logged either way, - // so an approximate heuristic is fine. - // - // When #27300 is fixed, we can delete this branch and log the same - // panic for any public key moving. - if strings.HasSuffix(n.Name(), ".mullvad.ts.net.") { - devPanicf("public key moved between Mullvad nodeIDs (old=%v new=%v, key=%s); see http://go/corp/27300", ep.nodeID, n.ID(), n.Key().String()) - } else { - devPanicf("public key moved between nodeIDs (old=%v new=%v, key=%s)", ep.nodeID, n.ID(), n.Key().String()) - } + // Both callers remove the endpoints of peers that are gone + // before upserting, so ep's node is still a current peer: two + // live nodeIDs in one peer list share a node key. controlclient + // drops such duplicates, but other SetNetworkMap callers (such + // as ingressd) may not, so log it rather than panicking. The + // existing endpoint keeps the key. See + // https://github.com/tailscale/corp/issues/52092. + c.logf("[unexpected] magicsock: node key %s used by both nodeID %v and %v (%q); ignoring %v", n.Key().ShortString(), ep.nodeID, n.ID(), n.Name(), n.ID()) } else { // Internal data structures out of sync. devPanicf("public key found in peerMap but not by nodeID") @@ -3450,6 +3453,19 @@ func (c *Conn) UpsertPeer(n tailcfg.NodeView) { return } flags := c.debugFlagsLocked() + if ep, ok := c.peerMap.endpointForNodeKey(n.Key()); ok && ep.nodeID != n.ID() { + // The node key moved to a new nodeID, typically because control + // deleted the old node and the machine re-registered with its + // persisted node key, and this add arrived before the old node's + // removal. Treat it as an implicit removal of the old node, which + // makes its later RemovePeer a no-op. The relay-server update + // below is keyed by node key and so covers the old node too. + // See https://github.com/tailscale/corp/issues/52092. + c.logf("magicsock: node key %s moved from nodeID %v to %v (%q)", n.Key().ShortString(), ep.nodeID, n.ID(), n.Name()) + if _, ok := c.removePeerLocked(ep.nodeID); !ok { + c.peerMap.deleteEndpoint(ep) // peersByID lacked ep.nodeID + } + } if prev, ok := c.peersByID[n.ID()]; ok && prev.Key() != n.Key() { delete(c.derpRoute, prev.Key()) delete(c.peerLastDerp, prev.Key()) @@ -3491,10 +3507,26 @@ func (c *Conn) RemovePeer(nid tailcfg.NodeID) { c.mu.Unlock() return } - prev, ok := c.peersByID[nid] + prev, ok := c.removePeerLocked(nid) + relayClientEnabled := c.relayClientEnabled + c.mu.Unlock() + + if ok && buildfeatures.HasNATTraversal && relayClientEnabled { + // Tell the relay manager to drop the peer. The run loop no-ops + // this if the peer wasn't a relay server. + c.relayManager.handleRelayServerRemove(prev.Key()) + } +} + +// removePeerLocked removes the peer with nodeID nid from c.peersByID, +// c.peerMap and the node-key-keyed state, returning the removed node. It +// reports false if nid wasn't a peer. It doesn't update the relay manager. +// +// c.mu must be held. +func (c *Conn) removePeerLocked(nid tailcfg.NodeID) (prev tailcfg.NodeView, ok bool) { + prev, ok = c.peersByID[nid] if !ok { - c.mu.Unlock() - return + return prev, false } delete(c.peersByID, nid) delete(c.derpRoute, prev.Key()) @@ -3510,15 +3542,7 @@ func (c *Conn) RemovePeer(nid tailcfg.NodeID) { if dk := prev.DiscoKey(); !dk.IsZero() && !c.peerMap.knownPeerDiscoKey(dk) { delete(c.discoInfo, dk) } - - relayClientEnabled := c.relayClientEnabled - c.mu.Unlock() - - if buildfeatures.HasNATTraversal && relayClientEnabled { - // Tell the relay manager to drop the peer. The run loop no-ops - // this if the peer wasn't a relay server. - c.relayManager.handleRelayServerRemove(prev.Key()) - } + return prev, true } // relayCandidateLocked reports whether peer p is eligible to be a relay diff --git a/wgengine/magicsock/magicsock_test.go b/wgengine/magicsock/magicsock_test.go index 8fdbefddc..1d438c003 100644 --- a/wgengine/magicsock/magicsock_test.go +++ b/wgengine/magicsock/magicsock_test.go @@ -2635,6 +2635,94 @@ func TestPeerDERPStateCleanup(t *testing.T) { } } +// TestNodeKeyMovedBetweenNodeIDs tests that a node key handed from a +// removed node to a new node (as happens when control deletes a node and the +// same machine re-registers with its persisted node key) results in an +// endpoint for the new node and none for the old one, via both the full +// SetNetworkMap path and the incremental UpsertPeer/RemovePeer path. +// See https://github.com/tailscale/corp/issues/52092. +func TestNodeKeyMovedBetweenNodeIDs(t *testing.T) { + k := randNodeKey() + dk := randDiscoKey() + oldNode := &tailcfg.Node{ID: 100, Key: k, DiscoKey: dk, Endpoints: eps("192.168.1.2:1")} + newNode := &tailcfg.Node{ID: 200, Key: k, DiscoKey: dk, Endpoints: eps("192.168.1.2:1")} + + // checkOwner verifies that the endpoint for k belongs to want, and that + // the peer set is exactly {want}. + checkOwner := func(t *testing.T, c *Conn, want tailcfg.NodeID) { + t.Helper() + c.mu.Lock() + defer c.mu.Unlock() + ep, ok := c.peerMap.endpointForNodeKey(k) + if !ok { + t.Fatalf("no endpoint for key") + } + if ep.nodeID != want { + t.Errorf("endpoint nodeID = %v; want %v", ep.nodeID, want) + } + if _, ok := c.peerMap.endpointForNodeID(want); !ok { + t.Errorf("no endpoint for nodeID %v", want) + } + if n := c.peerMap.nodeCount(); n != 1 { + t.Errorf("peerMap nodeCount = %d; want 1", n) + } + if _, ok := c.peersByID[want]; len(c.peersByID) != 1 || !ok { + t.Errorf("peersByID has %d entries; want only %v", len(c.peersByID), want) + } + } + + t.Run("SetNetworkMap", func(t *testing.T) { + c := newTestConn(t) + defer c.Close() + c.SetNetworkMap(tailcfg.NodeView{}, nodeViews([]*tailcfg.Node{oldNode})) + checkOwner(t, c, 100) + c.SetNetworkMap(tailcfg.NodeView{}, nodeViews([]*tailcfg.Node{newNode})) + checkOwner(t, c, 200) + // An unchanged netmap takes the fast path; the endpoint must remain. + c.SetNetworkMap(tailcfg.NodeView{}, nodeViews([]*tailcfg.Node{newNode})) + checkOwner(t, c, 200) + }) + + t.Run("UpsertThenRemove", func(t *testing.T) { + c := newTestConn(t) + defer c.Close() + c.UpsertPeer(oldNode.View()) + checkOwner(t, c, 100) + // Control's delta adds the new node before removing the old one. + c.UpsertPeer(newNode.View()) + checkOwner(t, c, 200) + c.RemovePeer(100) + checkOwner(t, c, 200) + }) + + t.Run("RemoveThenUpsert", func(t *testing.T) { + c := newTestConn(t) + defer c.Close() + c.UpsertPeer(oldNode.View()) + c.RemovePeer(100) + c.UpsertPeer(newNode.View()) + checkOwner(t, c, 200) + }) + + t.Run("SameListDuplicate", func(t *testing.T) { + // Two live nodeIDs with the same key in one peer list is a control + // data error. It must not panic, and the first node in the list + // keeps the endpoint. + c := newTestConn(t) + defer c.Close() + c.SetNetworkMap(tailcfg.NodeView{}, nodeViews([]*tailcfg.Node{oldNode, newNode})) + c.mu.Lock() + ep, ok := c.peerMap.endpointForNodeKey(k) + c.mu.Unlock() + if !ok || ep.nodeID != 100 { + t.Fatalf("endpoint = %v, %v; want nodeID 100", ep, ok) + } + // Dropping the first node hands the key to the second. + c.SetNetworkMap(tailcfg.NodeView{}, nodeViews([]*tailcfg.Node{newNode})) + checkOwner(t, c, 200) + }) +} + // newWireguard starts up a new wireguard-go device attached to a test tun, and // returns the device, tun and endpoint port. To add peers call device.IpcSet // with UAPI instructions.