Documentation
¶
Index ¶
- Constants
- Variables
- func EdgePSKDispatchHandler(s *EdgePSKs) reconcile.DispatchHandler
- func ProgrammedEndpoint(p api.SnapshotPeer, mesh netip.Prefix) (endpoint string, directRejected bool)
- func ReconcileHandler(mgr *Manager, psks EdgePSKLookup) reconcile.ReconcileHandler
- type Config
- type EdgePSKFetcher
- type EdgePSKInstaller
- type EdgePSKLookup
- type EdgePSKs
- type Manager
- func (m *Manager) AddPeer(peer api.Peer) error
- func (m *Manager) ConfigurePeers(ctx context.Context, peers []api.Peer) error
- func (m *Manager) MeshPeerStats() ([]MeshPeerStat, error)
- func (m *Manager) MeshPrefix() netip.Prefix
- func (m *Manager) OSInterfaceName() string
- func (m *Manager) PeerIndex() *PeerIndex
- func (m *Manager) RemovePeer(publicKey []byte) error
- func (m *Manager) RemovePeerByID(peerID string) error
- func (m *Manager) RunEndpointSelection(ctx context.Context, interval time.Duration) error
- func (m *Manager) SetLocalPrefixes(fn func() ([]netip.Prefix, error))
- func (m *Manager) SetPeerPSK(peerNodeID, publicKey string, psk []byte) error
- func (m *Manager) Setup(ctx context.Context, identity *registration.NodeIdentity) error
- func (m *Manager) Teardown() error
- func (m *Manager) UpdatePeer(peer api.Peer) error
- func (m *Manager) UpdatePrivateKey(privateKey []byte) error
- type MeshPeerStat
- type NetlinkController
- func (c *NetlinkController) AddPeer(iface string, cfg PeerConfig) error
- func (c *NetlinkController) ConfigureAddress(name string, address string) error
- func (c *NetlinkController) CreateInterface(name string, privateKey []byte, listenPort int) error
- func (c *NetlinkController) DeleteInterface(name string) error
- func (c *NetlinkController) PeerStats(name string) ([]PeerStat, error)
- func (c *NetlinkController) RemovePeer(iface string, publicKey []byte) error
- func (c *NetlinkController) SetInterfaceUp(name string) error
- func (c *NetlinkController) SetMTU(name string, mtu int) error
- func (c *NetlinkController) SetPrivateKey(name string, privateKey []byte) error
- type OSInterfaceNamer
- type PeerConfig
- type PeerIndex
- func (p *PeerIndex) Add(peerID, publicKey string)
- func (p *PeerIndex) Count() int
- func (p *PeerIndex) LoadFromPeers(peers []api.Peer)
- func (p *PeerIndex) Lookup(peerID string) (publicKey string, ok bool)
- func (p *PeerIndex) NodeIDsByPublicKey() map[[32]byte]string
- func (p *PeerIndex) Remove(peerID string)
- func (p *PeerIndex) Update(peerID, newPublicKey string)
- type PeerStat
- type PeerStatsReader
- type UserspaceBackend
- func (b *UserspaceBackend) AddPeer(name string, cfg PeerConfig) error
- func (b *UserspaceBackend) CreateDevice(name string, tdev tun.Device, privateKey []byte, listenPort int) error
- func (b *UserspaceBackend) DeleteDevice(name string) error
- func (b *UserspaceBackend) PeerStats(name string) ([]PeerStat, error)
- func (b *UserspaceBackend) RemovePeer(name string, publicKey []byte) error
- func (b *UserspaceBackend) SetPrivateKey(name string, privateKey []byte) error
- type WGController
Constants ¶
const DefaultInterfaceName = "plexd0"
DefaultInterfaceName is the default WireGuard interface name.
const DefaultListenPort = 51820
DefaultListenPort is the default WireGuard UDP listen port.
const DefaultPersistentKeepalive = 25 * time.Second
DefaultPersistentKeepalive is the keepalive interval for an unset PersistentKeepalive, the value wg(8) suggests for a peer behind NAT.
const EndpointSelectionInterval = 5 * time.Second
EndpointSelectionInterval is how often RunEndpointSelection reads the device in plexd up.
Variables ¶
var ErrPeerStatsUnsupported = errors.New("wireguard: controller cannot read peer stats")
ErrPeerStatsUnsupported is returned by MeshPeerStats when the controller cannot read peer runtime state, or when there is no controller at all.
Functions ¶
func EdgePSKDispatchHandler ¶ added in v0.11.0
func EdgePSKDispatchHandler(s *EdgePSKs) reconcile.DispatchHandler
EdgePSKDispatchHandler returns a reconcile.DispatchHandler that syncs s against the peers of every successful pull. Dispatch handlers run before the reconcile handlers, so a new peer's PSK is fetched before the WireGuard handler adds the peer in the same cycle.
func ProgrammedEndpoint ¶ added in v0.11.0
func ProgrammedEndpoint(p api.SnapshotPeer, mesh netip.Prefix) (endpoint string, directRejected bool)
ProgrammedEndpoint returns the endpoint the pull gives p without its candidates: its direct endpoint when that is usable (see usableDirectEndpoint), otherwise its relay fallback, which may be empty. directRejected reports a non-empty direct endpoint that was refused, so the caller can say why it is left out. The node API's peer list shows this endpoint; the device's endpoint is the one endpoint selection settles on.
func ReconcileHandler ¶
func ReconcileHandler(mgr *Manager, psks EdgePSKLookup) reconcile.ReconcileHandler
ReconcileHandler returns a reconcile.ReconcileHandler that applies peer changes from the StateDiff to the WireGuard interface via the Manager. PeersToRemove are node IDs resolved through the peer index; adds and updates are converted from the snapshot shape via peerFromSnapshot, with the dial order dialOrder builds and the edge PSK psks holds for the peer's current public key. A nil psks programs no PSK. Order: removes first, then updates, then adds. Individual failures are logged and collected; an aggregated error is returned.
The host's interface prefixes and the mesh prefix are read once per call. When the prefixes cannot be read, every candidate is ordered as off-link, which still tries each of them.
Types ¶
type Config ¶
type Config struct {
// InterfaceName is the WireGuard network interface name.
// Default: "plexd0"
InterfaceName string `yaml:"interface_name"`
// ListenPort is the UDP port WireGuard listens on.
// Default: 51820
ListenPort int `yaml:"listen_port"`
// MTU is the interface MTU. 0 means system default.
MTU int `yaml:"mtu"`
// EdgePSK controls whether plexd fetches each edge's PSK from the control
// plane and programs it on the peer. A pointer, so an unset key stays
// distinguishable from an explicit false: WireGuard needs the same PSK on
// both ends of a tunnel, so during a rolling upgrade an operator sets
// `edge_psk: false` on upgraded nodes until every node of the Domain runs a
// plexd that installs edge PSKs, and that false must survive ApplyDefaults.
// Default: true (nil reads as enabled).
EdgePSK *bool `yaml:"edge_psk"`
// PersistentKeepalive is the interval at which WireGuard sends an empty
// packet to an idle mesh peer. It holds open the NAT mapping a node opened
// by dialing out, and it makes WireGuard start a handshake towards a newly
// programmed endpoint of an idle peer, which endpoint selection depends on.
// A pointer, so an unset key stays distinguishable from an explicit 0s,
// which turns the keepalive, and with it endpoint selection, off.
// Default: 25s (nil reads as DefaultPersistentKeepalive).
PersistentKeepalive *time.Duration `yaml:"persistent_keepalive"`
}
Config holds the configuration for WireGuard tunnel management. Config is passed as a constructor argument — no file I/O in this package.
func (*Config) ApplyDefaults ¶
func (c *Config) ApplyDefaults()
ApplyDefaults sets default values for zero-valued fields.
func (*Config) EdgePSKEnabled ¶ added in v0.11.0
EdgePSKEnabled returns the effective EdgePSK setting: true unless explicitly set to false.
func (*Config) KeepaliveInterval ¶ added in v0.11.0
KeepaliveInterval returns the effective PersistentKeepalive: the configured value, or DefaultPersistentKeepalive when the key is unset.
type EdgePSKFetcher ¶ added in v0.11.0
type EdgePSKFetcher interface {
FetchEdgePSK(ctx context.Context, nodeID, peerNodeID string) (*api.EdgePSKEnvelope, error)
}
EdgePSKFetcher fetches the sealed PSK for one edge. *api.ControlPlane implements it.
type EdgePSKInstaller ¶ added in v0.11.0
EdgePSKInstaller programs an edge PSK on the device peer that carries publicKey. *Manager implements it.
type EdgePSKLookup ¶ added in v0.11.0
EdgePSKLookup returns the edge PSK fetched for a peer, keyed by the peer's node ID and the public key it was fetched for. A PSK fetched for another key belongs to a different device peer, so it is never returned.
type EdgePSKs ¶ added in v0.11.0
type EdgePSKs struct {
// contains filtered or unexported fields
}
EdgePSKs fetches, opens and installs the pairwise edge PSK of every mesh peer, and keeps them in memory for the reconcile handler to program on the peers it adds or updates.
It runs the contract's re-fetch rule: a PSK is fetched when a peer first appears, when its public key changes, and after this node completes its own key rotation (InvalidateAll). A failed fetch is retried on the next pull. An envelope whose epoch sorts below the highest one already accepted for the edge is refused, because a mesh key rotation does not rotate the NSK and an older envelope would reinstall a retired key.
Keys, envelopes and the NSK never reach a log line or an error.
func NewEdgePSKs ¶ added in v0.11.0
func NewEdgePSKs(fetcher EdgePSKFetcher, nodeID string, nsk []byte, installer EdgePSKInstaller, logger *slog.Logger) *EdgePSKs
NewEdgePSKs builds an EdgePSKs for the node nodeID, opening envelopes under nsk (copied) and programming PSKs through installer.
func (*EdgePSKs) InvalidateAll ¶ added in v0.11.0
func (s *EdgePSKs) InvalidateAll()
InvalidateAll marks every PSK stale, so the next Sync fetches each peer's again. plexd calls it once its own key rotation committed.
func (*EdgePSKs) Lookup ¶ added in v0.11.0
Lookup returns a copy of the PSK held for peerNodeID when it was fetched for publicKey, stale or not: a stale PSK stays on the device until its replacement arrives. A PSK fetched for another key belongs to another device peer and is never returned.
func (*EdgePSKs) Sync ¶ added in v0.11.0
func (s *EdgePSKs) Sync(ctx context.Context, peers []api.SnapshotPeer)
Sync brings the PSKs in line with peers: it forgets peers that left, fetches the PSK of every peer the re-fetch rule names, and installs every PSK the installer has not accepted yet. It never returns an error: a failed fetch is logged and retried on the next pull, and an older control plane sees at most one request per pull.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager manages the WireGuard interface and peer configuration.
func NewManager ¶
func NewManager(ctrl WGController, cfg Config, logger *slog.Logger) *Manager
NewManager creates a new Manager. Config defaults are applied automatically.
func (*Manager) AddPeer ¶
AddPeer adds a peer to the WireGuard interface with the first entry of its dial order as the endpoint, starts its endpoint selection, and updates the peer index.
func (*Manager) ConfigurePeers ¶
ConfigurePeers bulk-configures all peers. Individual errors are logged but not returned.
func (*Manager) MeshPeerStats ¶ added in v0.10.0
func (m *Manager) MeshPeerStats() ([]MeshPeerStat, error)
MeshPeerStats reads the managed interface and returns the state of every device peer the peer index maps to a node ID, sorted by NodeID. It returns an empty, non-nil slice when no device peer maps.
A device peer whose key the index does not map is dropped. That is the case for a key left on the device after the peer's key rotated, and for a key two node IDs share (see PeerIndex.NodeIDsByPublicKey). A peer with no handshake is kept, because the tunnel metrics report it; the handshake reporter drops it itself. Endpoint passes through as the device reports it, and the consumers apply their own wire rules.
func (*Manager) MeshPrefix ¶ added in v0.11.0
MeshPrefix returns the Domain mesh prefix the interface was set up with, or the mesh IP's host /32 when the identity carried no usable domain_mesh_cidr. It is the zero prefix before Setup succeeds.
A peer endpoint inside this prefix would be routed through the mesh interface itself, so WireGuard would send a peer's encrypted packets into its own tunnel; endpoint selection refuses such an endpoint.
func (*Manager) OSInterfaceName ¶ added in v0.8.0
OSInterfaceName returns the name the operating system knows the managed interface by, which is what net.InterfaceByName and the host's own tooling resolve. It is Config.InterfaceName everywhere except macOS, where the controller creates a utun the kernel names utunN.
Callers that address the interface through plexd keep using Config.InterfaceName: the bridge managers and the status report. The policy enforcer takes the name this method returns, because pf on macOS matches the kernel's name.
func (*Manager) RemovePeer ¶
RemovePeer removes a peer from the WireGuard interface by public key.
func (*Manager) RemovePeerByID ¶
RemovePeerByID removes a peer by its peer ID, looking up the public key in the index.
func (*Manager) RunEndpointSelection ¶ added in v0.11.0
RunEndpointSelection runs selectEndpoints every interval until ctx is done, then returns nil.
It returns nil at once when the keepalive is off: WireGuard starts a handshake only when it sends something, so without the keepalive an idle peer never tries a newly programmed endpoint and a trial would prove nothing. Every peer then keeps the first entry of its dial order. It also returns nil, after one pass, when the controller cannot read peer stats.
func (*Manager) SetLocalPrefixes ¶ added in v0.11.0
SetLocalPrefixes sets the function the reconcile handler reads this host's interface prefixes from, to order a peer's on-link candidates first. Call it before the handler runs.
func (*Manager) SetPeerPSK ¶ added in v0.11.0
SetPeerPSK programs psk on the device peer of peerNodeID, when that peer was last written with publicKey. A peer not written yet, or written with another key, gets nothing: the PSK belongs to a different device peer, and the next AddPeer or UpdatePeer for the key takes it from the edge-PSK store.
The write carries the recorded peer's allowed IPs, which every device write replaces, and an empty endpoint, which leaves the device's endpoint as it is.
func (*Manager) Setup ¶
func (m *Manager) Setup(ctx context.Context, identity *registration.NodeIdentity) error
Setup creates and configures the WireGuard interface using the node identity.
func (*Manager) UpdatePeer ¶
UpdatePeer updates a peer configuration. WireGuard AddPeer is idempotent (upsert).
A connected peer whose public key is unchanged keeps the endpoint on the device, which may be one WireGuard roamed to: the write carries no endpoint, and the selection resumes from the new order's position of the entry last programmed. Any other peer starts over from the first entry of its new order, like AddPeer. A rotated key is a new device peer to WireGuard, which has no endpoint yet.
func (*Manager) UpdatePrivateKey ¶ added in v0.2.0
UpdatePrivateKey installs a rotated private key on the managed interface.
type MeshPeerStat ¶ added in v0.10.0
type MeshPeerStat struct {
NodeID string
Endpoint netip.AddrPort // invalid when the device knows no endpoint
LastHandshake time.Time // zero when no handshake has completed
RxBytes, TxBytes uint64
}
MeshPeerStat is one mesh peer's runtime state, keyed by the control plane's node ID instead of the WireGuard public key the device reports.
type NetlinkController ¶
type NetlinkController struct {
// contains filtered or unexported fields
}
NetlinkController implements WGController using Linux netlink and wgctrl.
func NewNetlinkController ¶
func NewNetlinkController(logger *slog.Logger) *NetlinkController
NewNetlinkController returns a new NetlinkController.
func (*NetlinkController) AddPeer ¶
func (c *NetlinkController) AddPeer(iface string, cfg PeerConfig) error
AddPeer adds or updates a peer on the named WireGuard interface. A new wgctrl client is created per call to avoid stale netlink socket issues across long-lived controller instances. The creation cost is negligible.
func (*NetlinkController) ConfigureAddress ¶
func (c *NetlinkController) ConfigureAddress(name string, address string) error
ConfigureAddress adds a CIDR address to the named interface.
func (*NetlinkController) CreateInterface ¶
func (c *NetlinkController) CreateInterface(name string, privateKey []byte, listenPort int) error
CreateInterface creates a WireGuard interface with the given name, configures it with the provided private key and listen port.
func (*NetlinkController) DeleteInterface ¶
func (c *NetlinkController) DeleteInterface(name string) error
DeleteInterface deletes the named WireGuard interface. It is idempotent: deleting a non-existent interface returns nil.
func (*NetlinkController) PeerStats ¶ added in v0.10.0
func (c *NetlinkController) PeerStats(name string) ([]PeerStat, error)
PeerStats reads every peer's runtime state from the named interface. Like AddPeer it opens a wgctrl client per call; the handshake reporter and the tunnel collector each call it once per interval, so a long-lived netlink socket would buy nothing. A missing interface returns an error wrapping os.ErrNotExist, which wgctrl maps from ENODEV.
wgctrl already gives a zero LastHandshakeTime for a peer that never completed a handshake, so it passes through unchanged.
func (*NetlinkController) RemovePeer ¶
func (c *NetlinkController) RemovePeer(iface string, publicKey []byte) error
RemovePeer removes a peer from the named WireGuard interface by public key.
func (*NetlinkController) SetInterfaceUp ¶
func (c *NetlinkController) SetInterfaceUp(name string) error
SetInterfaceUp brings the named interface up.
func (*NetlinkController) SetMTU ¶
func (c *NetlinkController) SetMTU(name string, mtu int) error
SetMTU sets the MTU on the named interface.
func (*NetlinkController) SetPrivateKey ¶ added in v0.2.0
func (c *NetlinkController) SetPrivateKey(name string, privateKey []byte) error
SetPrivateKey replaces the named device's private key without touching its listen port or peers.
type OSInterfaceNamer ¶ added in v0.8.0
type OSInterfaceNamer interface {
// OSInterfaceName returns the kernel's name for the interface created
// under the configured name, and false when no such interface exists.
OSInterfaceName(name string) (string, bool)
}
OSInterfaceNamer is implemented by controllers on platforms where the kernel, not the configuration, names the interface. macOS is the case: WireGuard there runs on a utun device the kernel calls utunN, while plexd keys the device, its UAPI endpoint and its log lines by the configured name.
Only code that hands the name back to the operating system needs this: the readiness check, which resolves the interface with net.InterfaceByName; the pf enforcer, whose rules match on the kernel name; and the site-to-site manager's route calls, because route(8) takes the kernel name. Everything addressing the device through plexd keeps the configured name.
type PeerConfig ¶
type PeerConfig struct {
PublicKey []byte
Endpoint string
AllowedIPs []string
PSK []byte // nil if no PSK
PersistentKeepalive int
}
PeerConfig holds the WireGuard-native configuration for a single peer.
func PeerConfigFromAPI ¶
func PeerConfigFromAPI(peer api.Peer) (PeerConfig, error)
PeerConfigFromAPI translates an api.Peer to a WireGuard PeerConfig. PublicKey and PSK are decoded from base64; an empty PSK is allowed.
type PeerIndex ¶
type PeerIndex struct {
// contains filtered or unexported fields
}
PeerIndex maintains a thread-safe mapping from peer IDs to base64-encoded public keys. This bridges the gap between the control plane (which uses peer IDs) and WireGuard (which uses public keys).
func (*PeerIndex) LoadFromPeers ¶
LoadFromPeers bulk-populates the index from a slice of api.Peer. It clears all existing entries before adding the new ones.
func (*PeerIndex) Lookup ¶
Lookup returns the public key for the given peerID and whether it was found.
func (*PeerIndex) NodeIDsByPublicKey ¶ added in v0.10.0
NodeIDsByPublicKey returns the reverse mapping, from each stored public key's raw bytes to its peer ID. It is what turns a device read, which knows peers only by key, back into the control plane's node IDs.
A stored key that is not valid base64 or does not decode to 32 bytes is skipped, because no device peer can carry it. A key two peer IDs share is left out: the device holds a single peer for it, and attributing that peer's state to either ID would report an edge no single node owns.
type PeerStat ¶ added in v0.10.0
type PeerStat struct {
PublicKey [32]byte
Endpoint netip.AddrPort // invalid when the device knows no endpoint
LastHandshake time.Time // zero when no handshake has completed
RxBytes uint64
TxBytes uint64
}
PeerStat is one peer's runtime state as the device reports it.
type PeerStatsReader ¶ added in v0.10.0
type PeerStatsReader interface {
// PeerStats returns every peer on the named device, in the device's order.
// A device that does not exist returns an error wrapping os.ErrNotExist.
PeerStats(name string) ([]PeerStat, error)
}
PeerStatsReader is implemented by controllers that can read peer runtime state.
It is optional, like OSInterfaceNamer, rather than a WGController method: only the handshake report and the tunnel metrics read the device, and adding the method to WGController would force it onto every test double that implements the interface for unrelated reasons. Callers type-assert, and a controller without it reports nothing.
type UserspaceBackend ¶ added in v0.8.0
type UserspaceBackend struct {
// contains filtered or unexported fields
}
UserspaceBackend runs wireguard-go devices inside the plexd process. The per-OS controllers create the tun device, hand it to CreateDevice, and program addresses, MTU and the interface flag themselves; this backend owns the wireguard-go device lifecycle, the private key, the listen port, the peers, and the UAPI endpoint that lets wg(8) read the device.
It is the base of the macOS (utun) and Windows (Wintun) WGController implementations and of the bridge access and site-to-site controllers. On Linux plexd stays on the kernel path (NetlinkController); this backend merely compiles and is tested there.
Configuration is applied in process through the device's UAPI text protocol (device.Device.IpcSet), not through wgctrl's userspace transport: wgctrl finds a userspace device only under a root-owned socket directory on Unix and a LocalSystem-owned named pipe on Windows, so its configure path cannot run unprivileged. The served UAPI endpoint still lets wgctrl and wg(8) read the device.
func NewUserspaceBackend ¶ added in v0.8.0
func NewUserspaceBackend(logger *slog.Logger) *UserspaceBackend
NewUserspaceBackend returns a backend wired to the production UDP bind and the per-platform UAPI endpoint.
func (*UserspaceBackend) AddPeer ¶ added in v0.8.0
func (b *UserspaceBackend) AddPeer(name string, cfg PeerConfig) error
AddPeer adds or updates a peer on the named device. A public key that already exists updates that peer in place.
func (*UserspaceBackend) CreateDevice ¶ added in v0.8.0
func (b *UserspaceBackend) CreateDevice(name string, tdev tun.Device, privateKey []byte, listenPort int) error
CreateDevice starts a wireguard-go device named name over tdev, configured with privateKey and listenPort, and serves its UAPI endpoint.
Ownership of tdev passes to the backend: on any error CreateDevice closes it (directly before the device exists, through device.Close afterwards), and a caller never closes the tun it handed in. A listenPort of 0 lets wireguard-go pick an ephemeral port. The device is brought up here, so a port already in use surfaces as an error from this call.
func (*UserspaceBackend) DeleteDevice ¶ added in v0.8.0
func (b *UserspaceBackend) DeleteDevice(name string) error
DeleteDevice closes the named device and its UAPI listener. It is idempotent: deleting a device that does not exist returns nil.
func (*UserspaceBackend) PeerStats ¶ added in v0.10.0
func (b *UserspaceBackend) PeerStats(name string) ([]PeerStat, error)
PeerStats reads every peer's runtime state from the named device through the same in-process UAPI that configures it, so it needs no privilege and no served socket. A device that does not exist returns an error wrapping os.ErrNotExist.
func (*UserspaceBackend) RemovePeer ¶ added in v0.8.0
func (b *UserspaceBackend) RemovePeer(name string, publicKey []byte) error
RemovePeer removes a peer from the named device by public key. A key with no matching peer is not an error.
func (*UserspaceBackend) SetPrivateKey ¶ added in v0.8.0
func (b *UserspaceBackend) SetPrivateKey(name string, privateKey []byte) error
SetPrivateKey replaces the named device's private key without touching its listen port or peers.
type WGController ¶
type WGController interface {
CreateInterface(name string, privateKey []byte, listenPort int) error
// DeleteInterface deletes the named WireGuard interface.
// Implementations must be idempotent: deleting a non-existent interface must return nil.
DeleteInterface(name string) error
ConfigureAddress(name string, address string) error
SetInterfaceUp(name string) error
SetMTU(name string, mtu int) error
AddPeer(iface string, cfg PeerConfig) error
RemovePeer(iface string, publicKey []byte) error
// SetPrivateKey replaces the named device's private key without touching
// its listen port or peers.
SetPrivateKey(name string, privateKey []byte) error
}
WGController abstracts OS-level WireGuard operations for testability.