Files
tailscale/wgengine/wgcfg/device.go
T
Brad FitzpatrickandBrad Fitzpatrick f831469c27 wgengine,ipn/ipnlocal: sync wireguard-go peers incrementally on netmap deltas
Previously, any peer added or removed by an incremental netmap delta
was only visible to wireguard-go after a full authReconfig: wgcfg's
ReconfigDevice re-installed a PeerLookupFunc closing over a freshly
built map of every peer's allowed IPs, doing O(n) work per change.

Instead, install the wireguard-go device hooks once, backed by live
state. Engine.SetPeerConfigFunc installs a single long-lived
PeerLookupFunc that queries LocalBackend's per-node RouteManager on
demand, and Engine.SyncDevicePeer does O(1) per-peer device sync
(remove, or update allowed IPs) as each delta mutation is applied.
Full reconfigs keep an O(n peers) device sync for now, but with no
lookup closure to reinstall and no removed-peer resurrection race; a
later change removes full-config peer syncing entirely.

The RouteManager's PeerAllowedIPs accessor backs the new hooks: its
sorted output makes unchanged state a no-op update, and its peer
filtering mirrors nmcfg.WGCfg, so expired peers and peers predating
both DERP and disco contribute no prefixes and thus cannot be lazily
created in the device, which matters because wireguard-go validates
inbound source IPs against per-peer allowed IPs.

The engine's SetPeerByIPPacketFunc callback is now authoritative when
installed, since LocalBackend's implementation covers subnet routes
and exit-node routes via the RouteManager's outbound table; the
engine's own reconfig-time BART table only serves engines running
without a LocalBackend.

The forced authReconfig on peer add/remove stays for now: the
WireGuard device no longer needs it, but OS routes, the quad-100
resolver's MagicDNS hosts map, and tstun's masquerade/jailed peer
config are still derived from the full peer set. Making those
delta-aware is the next step before gating it.

Updates #12542

Change-Id: I3ba8c7c324bca0ad0269279d03f53b1f17fb63a2
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2026-07-13 13:35:13 -07:00

107 lines
3.3 KiB
Go

// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package wgcfg
import (
"fmt"
"net/netip"
"github.com/tailscale/wireguard-go/conn"
"github.com/tailscale/wireguard-go/device"
"github.com/tailscale/wireguard-go/tun"
"tailscale.com/types/logger"
)
// NewDevice returns a wireguard-go Device configured for Tailscale use.
func NewDevice(tunDev tun.Device, bind conn.Bind, logger *device.Logger) *device.Device {
return device.NewDevice(tunDev, bind, logger)
}
// NewPeerLookupFunc returns a [device.PeerLookupFunc] that lazily
// creates peers using allowedIPs as the source of each peer's allowed
// IPs. The peer's endpoint is derived from its public key via bind.
func NewPeerLookupFunc(bind conn.Bind, logf logger.Logf, allowedIPs func(device.NoisePublicKey) ([]netip.Prefix, bool)) device.PeerLookupFunc {
return func(pubk device.NoisePublicKey) (_ *device.NewPeerConfig, ok bool) {
ips, ok := allowedIPs(pubk)
if !ok {
return nil, false
}
ep, err := bind.ParseEndpoint(fmt.Sprintf("%x", pubk[:]))
if err != nil {
logf("wgcfg: failed to parse endpoint for peer %x: %v", pubk[:8], err)
return nil, false
}
return &device.NewPeerConfig{
AllowedIPs: ips,
Endpoint: ep,
}, true
}
}
// ReconfigDevice replaces the existing device configuration with cfg.
//
// Instead of using the UAPI text protocol, it uses the wireguard-go direct API
// to install a [device.PeerLookupFunc] callback that creates peers on demand.
//
// The caller is responsible for:
// - calling [device.Device.SetPrivateKey] when the key changes
// - installing a [device.PeerByIPPacketFunc] on the device for outbound
// packet routing (e.g. via [tailscale.com/wgengine.Engine.SetPeerByIPPacketFunc])
func ReconfigDevice(d *device.Device, cfg *Config, logf logger.Logf) (err error) {
defer func() {
if err != nil {
logf("wgcfg.Reconfig failed: %v", err)
}
}()
// Build peer map: public key → allowed IPs.
peers := make(map[device.NoisePublicKey][]netip.Prefix, len(cfg.Peers))
for _, p := range cfg.Peers {
peers[p.PublicKey.Raw32()] = p.AllowedIPs
}
// Remove peers not in the new config.
d.RemoveMatchingPeers(func(pk device.NoisePublicKey) bool {
_, exists := peers[pk]
return !exists
})
// Update AllowedIPs on any already-active peers whose config may have
// changed. Peers that don't exist yet will get the correct AllowedIPs
// from PeerLookupFunc when they are lazily created.
for pk, allowedIPs := range peers {
if peer, ok := d.LookupActivePeer(pk); ok {
peer.SetAllowedIPs(allowedIPs)
}
}
// Install callback for lazy peer creation (incoming packets).
bind := d.Bind()
d.SetPeerLookupFunc(func(pubk device.NoisePublicKey) (_ *device.NewPeerConfig, ok bool) {
allowedIPs, ok := peers[pubk]
if !ok {
return nil, false
}
ep, err := bind.ParseEndpoint(fmt.Sprintf("%x", pubk[:]))
if err != nil {
logf("wgcfg: failed to parse endpoint for peer %x: %v", pubk[:8], err)
return nil, false
}
return &device.NewPeerConfig{
AllowedIPs: allowedIPs,
Endpoint: ep,
}, true
})
// RemoveMatchingPeers _again_, now that SetPeerLookupFunc is installed,
// lest any removed peers got re-created before the new SetPeerLookupFunc
// func was installed.
d.RemoveMatchingPeers(func(pk device.NoisePublicKey) bool {
_, exists := peers[pk]
return !exists
})
return nil
}