heath, ipn/local, wgengine/magicsock: detect and report exit node health problems

updates tailscale/corp#33077

Tracks the usage of an exit node within magicsock and raises a
health warning on send failures and clears it once the exit node
is healthy.

Signed-off-by: Jonathan Nobels <[email protected]>
This commit is contained in:
Jonathan Nobels committed 2026-07-30 14:30:08 -04:00
1 parent 70a03faafe
commit 7440f5bf7b
13 files changed
+380 -38

No files matched your search

+1 -1
View File
@@ -94,7 +94,7 @@ tailscale.com/cmd/tailscaled dependencies: (generated by github.com/tailscale/de
tailscale.com/net/dns/resolver from tailscale.com/net/dns+
tailscale.com/net/dnscache from tailscale.com/control/controlclient+
tailscale.com/net/dnsfallback from tailscale.com/cmd/tailscaled+
tailscale.com/net/flowtrack from tailscale.com/wgengine/filter
tailscale.com/net/flowtrack from tailscale.com/wgengine/filter+
tailscale.com/net/ipset from tailscale.com/ipn/ipnlocal+
tailscale.com/net/netaddr from tailscale.com/ipn+
tailscale.com/net/netcheck from tailscale.com/wgengine/magicsock+
+1 -1
View File
@@ -111,7 +111,7 @@ tailscale.com/cmd/tailscaled dependencies: (generated by github.com/tailscale/de
tailscale.com/net/dns/resolver from tailscale.com/net/dns+
tailscale.com/net/dnscache from tailscale.com/control/controlclient+
tailscale.com/net/dnsfallback from tailscale.com/cmd/tailscaled+
tailscale.com/net/flowtrack from tailscale.com/wgengine/filter
tailscale.com/net/flowtrack from tailscale.com/wgengine/filter+
tailscale.com/net/ipset from tailscale.com/ipn/ipnlocal+
tailscale.com/net/netaddr from tailscale.com/ipn+
tailscale.com/net/netcheck from tailscale.com/cmd/tailscale/cli+
+4
View File
@@ -40,4 +40,8 @@ const (
// ArgDomains provides a Warnable with a comma-delimited list of domain
// names involved in the unhealthy state.
ArgDomains Arg = "domains"
// ArgExitNodeName provides a Warnable with the display name of the exit
// node peer involved in the unhealthy state.
ArgExitNodeName Arg = "exit-node-name"
)
+25
View File
@@ -311,3 +311,28 @@ var ipForwardingWarnable = condRegister(func() *Warnable {
ImpactsConnectivity: true,
}
})
// ExitNodeUnreachableWarnable is a Warnable that warns the user that connections
// via the configured exit node are failing. This is a high-severity warning because it indicates
// that the user is unable to route traffic through their exit node, which can significantly impact connectivity.
var ExitNodeUnreachableWarnable = condRegister(func() *Warnable {
return &Warnable{
Code: tsconst.HealthWarnableExitNodeUnreachable,
Title: "Exit node unreachable",
Severity: SeverityHigh,
DependsOn: []*Warnable{NetworkStatusWarnable},
ImpactsConnectivity: true,
// Suppresses one-off errors
TimeToVisible: 10 * time.Second,
Text: func(args Args) string {
name := args[ArgExitNodeName]
if name == "" {
name = "the configured exit node"
}
if e := args[ArgError]; e != "" {
return fmt.Sprintf("Tailscale is unable to route traffic via exit node %q: %s. Connectivity may be affected.", name, e)
}
return fmt.Sprintf("Tailscale is unable to route traffic via exit node %q. Connectivity may be affected.", name)
},
}
})
+32
View File
@@ -6157,6 +6157,8 @@ func (b *LocalBackend) authReconfigLocked() {
}
b.logf("[v1] authReconfig: ra=%v dns=%v 0x%02x: %v", prefs.RouteAll(), prefs.CorpDNS(), flags, err)
b.updateExitNodeHealthTargetLocked(nm, prefs)
b.initPeerAPIListenerLocked()
if buildfeatures.HasAppConnectors {
go b.goTracker.Go(b.readvertiseAppConnectorRoutes)
@@ -6186,6 +6188,36 @@ func (b *LocalBackend) setDataPlanePeerRoutes() {
b.e.SetPeerRoutes(native4, native6, routes)
}
// updateExitNodeHealthTargetLocked informs magicsock which peer (if any) is
// currently configured as the exit node, so magicsock can raise or clear
// [health.ExitNodeUnreachableWarnable] based on send outcomes.
//
// b.mu must be held.
func (b *LocalBackend) updateExitNodeHealthTargetLocked(nm *netmap.NetworkMap, prefs ipn.PrefsView) {
ms, ok := b.sys.MagicSock.GetOK()
if !ok {
return
}
var (
exitKey key.NodePublic
exitName string
)
if id := prefs.ExitNodeID(); !id.IsZero() && nm != nil {
if peer, ok := nm.PeerWithStableID(id); ok {
exitKey = peer.Key()
exitName = peer.Name()
if exitName == "" {
if hi := peer.Hostinfo(); hi.Valid() {
exitName = hi.Hostname()
}
} else {
exitName, _, _ = strings.Cut(exitName, ".")
}
}
}
ms.SetExitNodePeer(exitKey, exitName)
}
// shouldUseOneCGNATRoute reports whether we should prefer to make one big
// CGNAT /10 route rather than a /32 per peer.
//
+1
View File
@@ -24,4 +24,5 @@ const (
HealthWarnableApplyDiskConfig = "apply-disk-config"
HealthWarnableWarmingUp = "warming-up"
HealthWarnableTLSCertPending = "tls-cert-pending"
HealthWarnableExitNodeUnreachable = "exit-node-unreachable"
)
+7
View File
@@ -517,6 +517,9 @@ func (de *endpoint) initFakeUDPAddr() {
// Conn.noteRecvActivity no more than once every 10s, returning true if it
// was called, otherwise false.
func (de *endpoint) noteRecvActivity(src epAddr, now mono.Time) bool {
// Any packet from this peer is proof of reachability.
de.c.NoteExitNodeReachabilityResult(de.publicKey, nil)
if de.isWireguardOnly {
de.mu.Lock()
de.bestAddr.ap = src.ap
@@ -1075,6 +1078,7 @@ func (de *endpoint) send(buffs [][]byte, offset int) error {
if rid := de.c.fallbackDERPRegionForPeer(de.publicKey); rid != 0 {
derpAddr = netip.AddrPortFrom(tailcfg.DerpMagicIPAddr, uint16(rid))
} else {
de.c.NoteExitNodeReachabilityResult(de.publicKey, errNoUDPOrDERP)
return errNoUDPOrDERP
}
}
@@ -1139,6 +1143,9 @@ func (de *endpoint) send(buffs [][]byte, offset int) error {
return nil
}
}
if err != nil {
de.c.NoteExitNodeReachabilityResult(de.publicKey, err)
}
return err
}
+96
View File
@@ -0,0 +1,96 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package magicsock
import (
"tailscale.com/health"
"tailscale.com/types/key"
)
// SetExitNodePeer sets the peer that magicsock should treat as the current
// exit node for health monitoring. Pass a zero nodeKey to clear the
// exit-node association.
//
// displayName is used in the health warning text and may be empty.
//
// See [Conn.NoteExitNodeReachabilityResult] for how reachability results
// against this peer are surfaced as [health.ExitNodeUnreachableWarnable].
func (c *Conn) SetExitNodePeer(nodeKey key.NodePublic, displayName string) {
var newKey *key.NodePublic
if !nodeKey.IsZero() {
k := nodeKey
newKey = &k
}
old := c.exitNodeKey.Swap(newKey)
c.mu.Lock()
c.exitNodeName = displayName
c.mu.Unlock()
if sameExitNodeKey(old, newKey) {
return
}
// The identity of the tracked peer changed (including transitions to or
// from the zero key). Any warning we were carrying was about the old
// peer, so clear it and let subsequent reachability results decide the
// state of the new peer from scratch.
if c.exitNodeUnhealthy.CompareAndSwap(true, false) {
c.health.SetHealthy(health.ExitNodeUnreachableWarnable)
}
}
func sameExitNodeKey(a, b *key.NodePublic) bool {
switch {
case a == nil && b == nil:
return true
case a == nil || b == nil:
return false
}
return *a == *b
}
// IsExitNodePeer reports whether k is the peer currently configured as the
// exit node (see [Conn.SetExitNodePeer]). It's safe to call from hot paths:
// the check is a single atomic-pointer load plus a NodePublic comparison,
// and does not acquire c.mu.
func (c *Conn) IsExitNodePeer(k key.NodePublic) bool {
p := c.exitNodeKey.Load()
return p != nil && *p == k
}
// NoteExitNodeReachabilityResult updates
// [health.ExitNodeUnreachableWarnable] based on a reachability outcome for
// peerKey. It is a no-op when peerKey is not the currently configured exit
// node peer.
//
// err == nil signals that peerKey was reached (e.g. a WireGuard packet
// arrived from the peer), causing the warning to clear. err != nil signals
// a reachability failure (e.g. magicsock could not deliver a WireGuard
// packet to the peer) and raises the warning; the [Warnable]'s
// TimeToVisible suppresses transient blips.
func (c *Conn) NoteExitNodeReachabilityResult(peerKey key.NodePublic, err error) {
if err == nil && !c.exitNodeUnhealthy.Load() {
return
}
k := c.exitNodeKey.Load()
if k == nil || *k != peerKey {
return
}
if err == nil {
if c.exitNodeUnhealthy.CompareAndSwap(true, false) {
c.health.SetHealthy(health.ExitNodeUnreachableWarnable)
}
return
}
if !c.exitNodeUnhealthy.CompareAndSwap(false, true) {
return
}
c.mu.Lock()
exitName := c.exitNodeName
c.mu.Unlock()
c.health.SetUnhealthy(health.ExitNodeUnreachableWarnable, health.Args{
health.ArgExitNodeName: exitName,
health.ArgError: err.Error(),
})
}
+152
View File
@@ -0,0 +1,152 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package magicsock
import (
"errors"
"testing"
"tailscale.com/health"
"tailscale.com/types/key"
"tailscale.com/util/eventbus/eventbustest"
)
// newConnWithHealth returns a magicsock Conn wired up to a fresh
// health.Tracker so tests can observe warnable transitions without
// spinning up the full magicStack.
func newConnWithHealth(t *testing.T) (*Conn, *health.Tracker) {
t.Helper()
bus := eventbustest.NewBus(t)
ht := health.NewTracker(bus)
c := newConn(t.Logf)
c.health = ht
return c, ht
}
func TestExitNodeReachabilityNoOpWhenNotSet(t *testing.T) {
c, ht := newConnWithHealth(t)
peer := key.NewNode().Public()
c.NoteExitNodeReachabilityResult(peer, errors.New("send failed"))
if ht.IsUnhealthy(health.ExitNodeUnreachableWarnable) {
t.Fatalf("warnable set even though no exit node was configured")
}
c.NoteExitNodeReachabilityResult(peer, nil)
if ht.IsUnhealthy(health.ExitNodeUnreachableWarnable) {
t.Fatalf("warnable set after success with no exit node")
}
if c.exitNodeUnhealthy.Load() {
t.Fatalf("exitNodeUnhealthy=true after no-op path")
}
}
func TestExitNodeReachabilityFailureMarksUnhealthy(t *testing.T) {
c, ht := newConnWithHealth(t)
exit := key.NewNode().Public()
c.SetExitNodePeer(exit, "exitbox")
c.NoteExitNodeReachabilityResult(exit, errors.New("no UDP or DERP addr"))
if !ht.IsUnhealthy(health.ExitNodeUnreachableWarnable) {
t.Fatalf("warnable not set after send failure to exit node")
}
if !c.exitNodeUnhealthy.Load() {
t.Fatalf("exitNodeUnhealthy=false after send failure")
}
}
func TestExitNodeReachabilitySuccessClearsWarnable(t *testing.T) {
c, ht := newConnWithHealth(t)
exit := key.NewNode().Public()
c.SetExitNodePeer(exit, "thepacketsmustflow")
c.NoteExitNodeReachabilityResult(exit, errors.New("the packets are not flowing"))
if !ht.IsUnhealthy(health.ExitNodeUnreachableWarnable) {
t.Fatalf("warnable should be set")
}
c.NoteExitNodeReachabilityResult(exit, nil)
if ht.IsUnhealthy(health.ExitNodeUnreachableWarnable) {
t.Fatalf("warnable still set after successful send")
}
if c.exitNodeUnhealthy.Load() {
t.Fatalf("exitNodeUnhealthy=true after clear")
}
}
func TestExitNodeReachabilityOnlyReactsToConfiguredPeer(t *testing.T) {
c, ht := newConnWithHealth(t)
exit := key.NewNode().Public()
other := key.NewNode().Public()
c.SetExitNodePeer(exit, "thepacketsmustflow")
c.NoteExitNodeReachabilityResult(other, errors.New("the packets are not flowing"))
if ht.IsUnhealthy(health.ExitNodeUnreachableWarnable) {
t.Fatalf("send failure to non-exit peer raised exit-node warning")
}
}
func TestExitNodeSwitchingClearsPriorWarning(t *testing.T) {
c, ht := newConnWithHealth(t)
a := key.NewNode().Public()
b := key.NewNode().Public()
c.SetExitNodePeer(a, "exit-a")
c.NoteExitNodeReachabilityResult(a, errors.New("the packets are not flowing"))
if !ht.IsUnhealthy(health.ExitNodeUnreachableWarnable) {
t.Fatalf("precondition: warnable should be set for peer a")
}
c.SetExitNodePeer(b, "exit-b")
if ht.IsUnhealthy(health.ExitNodeUnreachableWarnable) {
t.Fatalf("switching exit node did not clear the prior peer's warning")
}
if c.exitNodeUnhealthy.Load() {
t.Fatalf("exitNodeUnhealthy=true after peer switch")
}
}
func TestExitNodeClearingResetsWarning(t *testing.T) {
c, ht := newConnWithHealth(t)
exit := key.NewNode().Public()
c.SetExitNodePeer(exit, "exitbox")
c.NoteExitNodeReachabilityResult(exit, errors.New("the packets are not flowing"))
if !ht.IsUnhealthy(health.ExitNodeUnreachableWarnable) {
t.Fatalf("precondition: warnable should be set")
}
c.SetExitNodePeer(key.NodePublic{}, "")
if ht.IsUnhealthy(health.ExitNodeUnreachableWarnable) {
t.Fatalf("clearing the exit node did not clear the warning")
}
if c.exitNodeUnhealthy.Load() {
t.Fatalf("exitNodeUnhealthy=true after clearing exit node")
}
}
func TestExitNodeSetSameKeyIsIdempotent(t *testing.T) {
c, ht := newConnWithHealth(t)
exit := key.NewNode().Public()
c.SetExitNodePeer(exit, "exitbox")
c.NoteExitNodeReachabilityResult(exit, errors.New("boom"))
if !ht.IsUnhealthy(health.ExitNodeUnreachableWarnable) {
t.Fatalf("precondition: warnable should be set")
}
// Re-setting the same key must not clear the warning — nothing about
// the tracked peer has changed.
c.SetExitNodePeer(exit, "exitbox-refreshed-name")
if !ht.IsUnhealthy(health.ExitNodeUnreachableWarnable) {
t.Fatalf("warnable was cleared when re-setting the same exit node key")
}
}
+13
View File
@@ -426,6 +426,19 @@ type Conn struct {
// This allows tests to pass when the user's machine is offline,
// but allows us to still test network-down behaviour when desired.
checkNetworkUpDuringTests bool
// exitNodeKey points to the NodeKey of the peer currently configured
// as the exit node, or is nil if no exit node is configured. Accessed
// via atomic ops so the send/receive hot paths can compare against it
// without acquiring c.mu. See [Conn.SetExitNodePeer].
exitNodeKey atomic.Pointer[key.NodePublic]
// exitNodeName is a human-friendly name for the exit node peer, used
// in the exit-node health warning. Guarded by c.mu.
exitNodeName string
// exitNodeUnhealthy tracks whether [health.ExitNodeUnreachableWarnable]
// is currently set for the exit-node peer, so send/receive hot paths
// only touch the health tracker on state transitions.
exitNodeUnhealthy atomic.Bool
}
// SetDebugLoggingEnabled controls whether spammy debug logging is enabled.
+36 -2
View File
@@ -1,11 +1,10 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
//go:build !ts_omit_debug
package wgengine
import (
"errors"
"fmt"
"net/netip"
"runtime"
@@ -14,6 +13,8 @@ import (
"time"
"github.com/gaissmai/bart"
"tailscale.com/envknob"
"tailscale.com/feature/buildfeatures"
"tailscale.com/net/flowtrack"
"tailscale.com/net/packet"
"tailscale.com/net/tstun"
@@ -26,6 +27,15 @@ type flowtrackTuple = flowtrack.Tuple
const tcpTimeoutBeforeDebug = 5 * time.Second
// trackAllOpenFlows reports whether every outbound TCP SYN should be tracked
// for connect-failure diagnostics. When false, only SYNs destined for the
// configured exit-node peer are tracked (the [health.ExitNodeUnreachableWarnable]
// signal); everything else skips the pendOpen map entirely, so minimal builds
// pay near-zero cost when no exit node is set.
var trackAllOpenFlows = sync.OnceValue(func() bool {
return buildfeatures.HasDebug && envknob.BoolDefaultTrue("TS_DEBUG_CONNECT_FAILURES")
})
type pendingOpenFlow struct {
timer *time.Timer // until giving up on the flow
@@ -101,6 +111,14 @@ func (e *userspaceEngine) trackOpenPreFilterIn(pp *packet.Parsed, t *tstun.Wrapp
if removed && pp.TCPFlags&packet.TCPRst != 0 {
e.logf("open-conn-track: flow TCP %v got RST by peer", f)
}
// A SYN-ACK (or RST) travelled back through the peer that would forward
// this flow. If that peer is the configured exit node, that proves
// traffic is currently flowing through it — clear any
// [health.ExitNodeUnreachableWarnable] we may have raised. No-op if the
// peer isn't the exit node.
if pip, ok := e.peerForIP(pp.Src.Addr()); ok {
e.magicConn.NoteExitNodeReachabilityResult(pip.Node.Key(), nil)
}
return
}
@@ -165,6 +183,16 @@ func (e *userspaceEngine) trackOpenPostFilterOut(pp *packet.Parsed, t *tstun.Wra
return
}
// When full debug tracking is off, we still want to detect exit-node
// reachability failures. Track only flows destined via the current
// exit-node peer; everything else returns before touching pendOpen.
if !trackAllOpenFlows() {
pip, ok := e.peerForIP(pp.Dst.Addr())
if !ok || !e.magicConn.IsExitNodePeer(pip.Node.Key()) {
return
}
}
flow := flowtrack.MakeTuple(pp.IPProto, pp.Src, pp.Dst)
e.mu.Lock()
@@ -205,6 +233,12 @@ func (e *userspaceEngine) onOpenTimeout(flow flowtrack.Tuple) {
return
}
n := pip.Node
// Report the timeout as an exit-node reachability failure. No-op if n
// is not the currently configured exit-node peer. This is the signal
// that raises [health.ExitNodeUnreachableWarnable]; any config change
// or upstream policy that breaks TCP through the exit node lands here.
e.magicConn.NoteExitNodeReachabilityResult(n.Key(),
errors.New("TCP connection through exit node timed out"))
if !n.IsWireGuardOnly() {
if n.DiscoKey().IsZero() {
e.logf("open-conn-track: timeout opening %v; peer node %v running pre-0.100", flow, n.Key().ShortString())
-24
View File
@@ -1,24 +0,0 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
//go:build ts_omit_debug
package wgengine
import (
"tailscale.com/net/packet"
"tailscale.com/net/tstun"
"tailscale.com/wgengine/filter"
)
type flowtrackTuple = struct{}
type pendingOpenFlow struct{}
func (*userspaceEngine) trackOpenPreFilterIn(pp *packet.Parsed, t *tstun.Wrapper) (res filter.Response) {
panic("unreachable")
}
func (*userspaceEngine) trackOpenPostFilterOut(pp *packet.Parsed, t *tstun.Wrapper) (res filter.Response) {
panic("unreachable")
}
+12 -10
View File
@@ -24,7 +24,6 @@ import (
"go4.org/mem"
"tailscale.com/control/controlknobs"
"tailscale.com/drive"
"tailscale.com/envknob"
"tailscale.com/feature"
"tailscale.com/feature/buildfeatures"
"tailscale.com/health"
@@ -463,16 +462,19 @@ func NewUserspaceEngine(logf logger.Logf, conf Config) (_ Engine, reterr error)
}
e.tundev.PreFilterPacketOutboundToWireGuardEngineIntercept = e.handleLocalPackets
if buildfeatures.HasDebug && envknob.BoolDefaultTrue("TS_DEBUG_CONNECT_FAILURES") {
if e.tundev.PreFilterPacketInboundFromWireGuard != nil {
return nil, errors.New("unexpected PreFilterIn already set")
}
e.tundev.PreFilterPacketInboundFromWireGuard = e.trackOpenPreFilterIn
if e.tundev.PostFilterPacketOutboundToWireGuard != nil {
return nil, errors.New("unexpected PostFilterOut already set")
}
e.tundev.PostFilterPacketOutboundToWireGuard = e.trackOpenPostFilterOut
// Install the connect-tracking filters. They power two things:
// - [health.ExitNodeUnreachableWarnable] (always active when an exit
// node is configured; ~zero cost otherwise).
// - Debug diagnostics for stuck TCP connections (all-flow tracking,
// gated on TS_DEBUG_CONNECT_FAILURES inside the filter functions).
if e.tundev.PreFilterPacketInboundFromWireGuard != nil {
return nil, errors.New("unexpected PreFilterIn already set")
}
e.tundev.PreFilterPacketInboundFromWireGuard = e.trackOpenPreFilterIn
if e.tundev.PostFilterPacketOutboundToWireGuard != nil {
return nil, errors.New("unexpected PostFilterOut already set")
}
e.tundev.PostFilterPacketOutboundToWireGuard = e.trackOpenPostFilterOut
e.wgLogger = wglog.NewLogger(logf, func(wgString string) (tsString string, ok bool) {
fn := e.wgPeerLookup.Load()