From 85d10d3f03b2e57f997eceded296fd9d56ccfce4 Mon Sep 17 00:00:00 2001 From: James Tucker Date: Thu, 29 Oct 2026 21:42:28 +0000 Subject: [PATCH] wgengine/magicsock: reject stale peer relay challenges Check the handshake generation before recording the challenge path. Add regression coverage for a stale challenge arriving before the current one. --- wgengine/magicsock/relaymanager.go | 4 ++++ wgengine/magicsock/relaymanager_test.go | 32 +++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/wgengine/magicsock/relaymanager.go b/wgengine/magicsock/relaymanager.go index 0b487f20b..998e5449c 100644 --- a/wgengine/magicsock/relaymanager.go +++ b/wgengine/magicsock/relaymanager.go @@ -614,6 +614,10 @@ func (r *relayManager) handleRxDiscoMsgRunLoop(event relayDiscoMsgEvent) { // No outstanding work tied to this challenge, discard. return } + if msg.Generation != work.handshakeGen { + // Reject stale challenges before recording the handshake path. + return + } _, ok = r.handshakeWorkAwaitingPong[work] if ok { // We've seen a challenge for this relay endpoint previously, diff --git a/wgengine/magicsock/relaymanager_test.go b/wgengine/magicsock/relaymanager_test.go index 671550b37..1b6770a4b 100644 --- a/wgengine/magicsock/relaymanager_test.go +++ b/wgengine/magicsock/relaymanager_test.go @@ -4,6 +4,7 @@ package magicsock import ( + "net/netip" "testing" "tailscale.com/disco" @@ -46,6 +47,37 @@ func TestRelayManagerInitAndIdle(t *testing.T) { <-rm.runLoopStoppedCh } +func TestRelayManagerStaleHandshakeChallenge(t *testing.T) { + rm := &relayManager{} + rm.init() + <-rm.runLoopStoppedCh // drive runLoop handlers synchronously + server := key.NewDisco().Public() + work := &relayHandshakeWork{ + se: udprelay.ServerEndpoint{ServerDisco: server, VNI: 1}, + handshakeGen: 2, + rxDiscoMsgCh: make(chan relayDiscoMsgEvent, 1), + doneCh: make(chan relayEndpointHandshakeWorkDoneEvent, 1), + } + rm.handshakeWorkByServerDiscoVNI[serverDiscoVNI{server, 1}] = work + event := relayDiscoMsgEvent{ + disco: server, + from: netip.MustParseAddrPort("127.0.0.1:12345"), + vni: 1, + msg: &disco.BindUDPRelayEndpointChallenge{ + BindUDPRelayEndpointCommon: disco.BindUDPRelayEndpointCommon{VNI: 1, Generation: 1}, + }, + } + rm.handleRxDiscoMsgRunLoop(event) + if len(work.rxDiscoMsgCh) != 0 || len(rm.handshakeWorkAwaitingPong) != 0 || len(rm.addrPortVNIToHandshakeWork) != 0 { + t.Fatal("stale challenge claimed the new handshake's path") + } + event.msg.(*disco.BindUDPRelayEndpointChallenge).Generation = 2 + rm.handleRxDiscoMsgRunLoop(event) + if len(work.rxDiscoMsgCh) != 1 || len(rm.handshakeWorkAwaitingPong) != 1 || len(rm.addrPortVNIToHandshakeWork) != 1 { + t.Fatal("current challenge was not accepted after a stale challenge") + } +} + // TestRelayManagerZeroServerDisco verifies that a [disco.CallMeMaybeVia] with // a zero ServerDisco is dropped rather than crashing the process in // [relayManager.ensureDiscoInfoFor]'s DiscoPrivate.Shared call, which rejects