wireguard

package
v0.41.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 37 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	MinFailureDetection = 5 * time.Second
	MaxFailureDetection = connectedHandshakeAge
)

MinFailureDetection and MaxFailureDetection bound the failure-detection time SetFailureDetection holds: a positive value outside them is clamped to the nearer one. The floor is the control plane's. The ceiling is connectedHandshakeAge: past that age the stale-handshake branch re-dials a relayed peer whatever the value says.

View Source
const DefaultInterfaceName = "plexd0"

DefaultInterfaceName is the default WireGuard interface name.

View Source
const DefaultListenPort = 51820

DefaultListenPort is the default WireGuard UDP listen port.

View Source
const DefaultMTU = 1420

DefaultMTU is the MTU Linux and wireguard-go give a WireGuard link: 1500 minus 80. Every controller creates the device at it, so Setup writes no MTU when it chooses this one.

View Source
const DefaultPersistentKeepalive = 25 * time.Second

DefaultPersistentKeepalive is the keepalive interval for an unset PersistentKeepalive, the value wg(8) suggests for a peer behind NAT.

View Source
const DefaultRTTProbeInterval = 30 * time.Second

DefaultRTTProbeInterval is the interval RunRTTProbe runs a round at when it is given none, the default heartbeat interval.

View Source
const EndpointSelectionInterval = 5 * time.Second

EndpointSelectionInterval is how often RunEndpointSelection reads the device in plexd up.

View Source
const MTUProbeInterval = 10 * time.Minute

MTUProbeInterval is how often RunMTUProbe measures the uplink again in plexd up.

View Source
const MinMTU = 1280

MinMTU is the smallest MTU detection programs, IPv6's minimum link MTU. It bounds how far an uplink that drops probes, or an on-path attacker who drops them, can push the mesh MTU down.

View Source
const RTTProbePort = 7911

RTTProbePort is the UDP port of the round-trip probe. Every plexd holds one socket on this port of its mesh address, which sends the node's probes and answers its peers' probes, so a probe and its answer both travel from this port to this port. The bridge watch of shared subnets (see Manager.watchBridges) writes its round-trip requests on the same socket, so they and their answers travel the same way. It lies above 1023, so plexd binds it without CAP_NET_BIND_SERVICE, and below 32768, outside Linux's ephemeral range and the mesh ports of the mesh source rewrite. The policy backends pass UDP to this port over the mesh interface without a rule (policy.RTTProbePort), so a probe and its answer pass under any policy. The backends cannot import this package, so TestRTTProbePortIsPolicyExempt keeps the two constants in step.

Variables

View Source
var ErrMeshAddressInvalid = errors.New("invalid mesh address")

ErrMeshAddressInvalid is returned by Readdress for an address the mesh interface does not take.

View Source
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.

View Source
var ErrReaddressUnsupported = errors.New("the mesh address cannot be replaced while plexd runs")

ErrReaddressUnsupported is returned by Readdress while CanReaddress is false.

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 FailureDetectionDispatchHandler added in v0.38.0

func FailureDetectionDispatchHandler(mgr *Manager) reconcile.DispatchHandler

FailureDetectionDispatchHandler returns a reconcile.DispatchHandler that hands the failure-detection time of every successful pull to mgr (see Manager.SetFailureDetection). The block is decoded here rather than in FetchState, and leniently, as the reachability block is: a malformed tuning value must not fail the pull that carries the peers and the policy.

Per pull:

  • An absent block or a null changes nothing and logs nothing: the node keeps the value of its last pull that carried one.
  • A block json.Unmarshal refuses, such as a string or a fractional detect_after_seconds, changes nothing and logs wireguard: failure detection block malformed at Warn, once until a block decodes again.
  • A detect_after_seconds of zero or less, {} included, changes nothing. A value from 1 to 4 applies MinFailureDetection, and one above 180 applies MaxFailureDetection. The integer is bounded before it is multiplied by time.Second, so no value overflows a time.Duration. Each logs wireguard: failure detection time out of range at Warn, once per run of the same raw value; a value from 5 to 180 ends the run.
  • A value in range, clamped or not, goes to SetFailureDetection, which logs the value when it changed.

The state lives in the closure, which only the reconcile goroutine enters, so it needs no lock.

func MeshMTU added in v0.17.0

func MeshMTU(pathMTU int) int

MeshMTU returns the mesh MTU for an uplink that carries IPv4 packets of pathMTU bytes: pathMTU minus the encapsulation overhead, capped at DefaultMTU and floored at MinMTU. A 1500-byte uplink gives DefaultMTU, so a healthy node keeps the MTU it always had.

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, and an ID the index no longer holds is already gone: a failed handler run leaves the reconciler's snapshot as it was, so the next run hands the same removal over again, and failing it then would fail every run after. Adds and updates are converted from the snapshot shape via peerFromSnapshot, with the dial order dialOrder builds, the relays that end it as Fallbacks, and the edge PSK psks holds for the peer's current public key. A nil psks programs no PSK. Order: removes first, then the pull's shared subnets, then updates, then adds, then the shared subnet writes, then the peer routes. The shared subnets step (see Manager.setSharedSubnets) takes the shared_subnets block and picks each subnet's holder before the updates and adds convert a peer, so every peer written carries the shared subnets it holds and none it does not. A pull can change a holder without changing either peer entry, so the shared subnet writes (see Manager.syncSharedSubnets) then write every peer on the device whose routed subnets the holders changed. They leave out a peer whose update or add failed in the run: a failed write leaves the peer as it was, and the next run applies the whole entry. A nil desired skips both steps, and the manager keeps the shared subnets it holds. The handler ends with syncPeerRoutes, which routes the routed subnets of the peers now on the device through the mesh interface and removes the routes no peer lists any more. 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, and no routed subnet is skipped as inside a local network.

func SendRelayProbe added in v0.22.0

func SendRelayProbe(meshIP netip.Addr) error

SendRelayProbe sends the relay liveness probe: one datagram of one zero byte to UDP port 9 of meshIP. The host routes it into the mesh interface, and WireGuard carries it to the peer as data, which the peer's WireGuard answers with a keepalive whether or not anything listens on the port. An address that is not IPv4 is refused, because mesh IPs are IPv4.

Types

type AddressReplacer added in v0.40.0

type AddressReplacer interface {
	ReplaceAddress(name, oldAddress, newAddress string) error
}

AddressReplacer is implemented by controllers that can swap the address of a live interface. oldAddress and newAddress are CIDRs of one length.

It is optional, as OSInterfaceNamer and PeerStatsReader are, so no test double has to grow. A call that failed halfway succeeds when it is repeated with the same arguments: an implementation tolerates an address that is already there on an add, and one that is not there on a remove.

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 sizes the interface to the uplink (see
	// MeshMTU); a positive value pins it.
	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

func (c *Config) EdgePSKEnabled() bool

EdgePSKEnabled returns the effective EdgePSK setting: true unless explicitly set to false.

func (*Config) KeepaliveInterval added in v0.11.0

func (c *Config) KeepaliveInterval() time.Duration

KeepaliveInterval returns the effective PersistentKeepalive: the configured value, or DefaultPersistentKeepalive when the key is unset.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks that configuration values are within acceptable ranges.

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

type EdgePSKInstaller interface {
	SetPeerPSK(peerNodeID, publicKey string, psk []byte) error
}

EdgePSKInstaller programs an edge PSK on the device peer that carries publicKey. *Manager implements it.

type EdgePSKLookup added in v0.11.0

type EdgePSKLookup interface {
	Lookup(peerNodeID, publicKey string) ([]byte, bool)
}

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

func (s *EdgePSKs) Lookup(peerNodeID, publicKey string) ([]byte, bool)

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

func (m *Manager) AddPeer(peer api.Peer) error

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) CanReaddress added in v0.40.0

func (m *Manager) CanReaddress() bool

CanReaddress reports whether Readdress can replace the mesh IP while plexd runs: Setup succeeded, the controller implements AddressReplacer, the mesh IP is IPv4, and the interface carries a prefix shorter than /32. Setup leaves meshPrefix zero until it succeeds.

DECISION: plexd declares mesh_readdress only when it can follow, and this is the test. An interface that carries the host /32 fallback of interfaceAddress has no prefix but its own address, so Readdress would refuse every move as outside it.

func (*Manager) ConfigurePeers

func (m *Manager) ConfigurePeers(ctx context.Context, peers []api.Peer) error

ConfigurePeers bulk-configures all peers. Individual errors are logged but not returned.

func (*Manager) FailureDetection added in v0.38.0

func (m *Manager) FailureDetection() (time.Duration, bool)

FailureDetection returns the failure-detection time m holds, and false while it holds none.

func (*Manager) MeshIP added in v0.40.0

func (m *Manager) MeshIP() netip.Addr

MeshIP returns the node's mesh IP the interface carries: the one Setup parsed from the identity, or the one Readdress last replaced it with. It is the zero address before Setup succeeds and when the identity's mesh IP does not parse.

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 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.

RTT is the latest round-trip time the round-trip probe measured to the peer (see RunRTTProbe), zero when the peer holds no value. The tunnel metrics ignore it. Endpoint selection reads it only in the bridge watch, where a value makes the bridge proven, which picks its stimulus and its window (see watchBridges).

SharedSubnets are the shared subnets whose holder the peer is when the call reads them (see setSharedSubnets), each list the caller's own. They are copied under mu, which is released before the round-trip probe's mutex is taken: the two are never held together, and no caller holds mu.

func (*Manager) MeshPrefix added in v0.11.0

func (m *Manager) MeshPrefix() netip.Prefix

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

func (m *Manager) OSInterfaceName() string

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) PeerIndex

func (m *Manager) PeerIndex() *PeerIndex

PeerIndex returns the peer index.

func (*Manager) Readdress added in v0.40.0

func (m *Manager) Readdress(addr netip.Addr) error

Readdress replaces the mesh IP the interface carries with addr, in place: the interface, its peers and their tunnels stay up. In order:

  1. It returns an error wrapping ErrReaddressUnsupported while CanReaddress is false.
  2. It returns an error wrapping ErrMeshAddressInvalid when addr, unmapped, is not IPv4, is unspecified, loopback, multicast or link-local, or lies outside MeshPrefix.
  3. It returns nil without a call when addr is the current mesh IP.
  4. It replaces the address through the controller (AddressReplacer), both with the prefix length of MeshPrefix. An error is returned wrapped as "wireguard: readdress:" and leaves the mesh IP as it was, so the next call for addr repeats the replace with the same arguments, which succeeds after a call that failed halfway.
  5. It stores addr as the mesh IP.
  6. It closes the round-trip probe's socket when one is held, so its reader ends and the next round listens on addr.
  7. It adds the route of every routed subnet it holds again (see addPeerRoutesAgain).
  8. It logs wireguard: mesh address replaced at Info.

MeshPrefix does not change. Calls must not overlap: plexd up makes them from the dispatch handler of the reconcile loop alone.

DECISION: a node re-addresses only inside the mesh prefix its interface was set up with. Every part that copied MeshPrefix at startup stays correct, and a pull cannot point the interface at a network of the host.

func (*Manager) RemovePeer

func (m *Manager) RemovePeer(publicKey []byte) error

RemovePeer removes a peer from the WireGuard interface by public key.

func (*Manager) RemovePeerByID

func (m *Manager) RemovePeerByID(peerID string) error

RemovePeerByID removes a peer by its peer ID, looking up the public key in the index.

func (*Manager) RunEndpointSelection added in v0.11.0

func (m *Manager) RunEndpointSelection(ctx context.Context, interval time.Duration) error

RunEndpointSelection runs selectEndpoints every interval until ctx is done, then returns nil. While a failure-detection time is held, a pass runs every passInterval instead. The loop reads it after every pass and resets its ticker when it changed, so a new value takes effect at most one pass of the old interval late.

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) RunMTUProbe added in v0.17.0

func (m *Manager) RunMTUProbe(ctx context.Context, interval time.Duration) error

RunMTUProbe measures the uplink every interval until ctx is done, then returns nil, and fits the mesh MTU to each round (see adjustMTU). The probe in Setup counts as the first round, so the first one here comes an interval after the call.

It returns nil at once when no probe is set or Config.MTU pins the MTU.

func (*Manager) RunRTTProbe added in v0.39.0

func (m *Manager) RunRTTProbe(ctx context.Context, interval time.Duration) error

RunRTTProbe measures the round-trip time to each mesh peer through the tunnel until ctx is done, and then closes its socket, waits for the reader and returns nil, with the socket handle (rttTable.socket) nil. MeshPeerStats reports the values as MeshPeerStat.RTT. A non-positive interval is replaced with DefaultRTTProbeInterval. The first round runs half an interval after the start and one round runs per interval after that, so a round's answers are in before the handshake report that follows when interval is the heartbeat interval. A round that outlasts the interval delays the next one. It also returns nil, with the socket closed, when the controller cannot read peer stats.

A round, in order (see rttRound):

  1. Listens when it holds no socket, none yet or one whose reader ended (see rttRead). Readdress closes the socket, so the round after it listens on the new address. A failure logs wireguard: rtt probe listen failed, at Warn the first time and at Debug while it keeps failing. The round then sends nothing, counts one unanswered probe for every peer that holds a value, and ends.
  2. Reads MeshPeerStats. ErrPeerStatsUnsupported logs wireguard: rtt probe unavailable, the controller cannot read peer stats at Info and ends the probe. Any other error logs wireguard: rtt probe round failed at Warn and ends the round with every value as it was.
  3. Takes each peer whose handshake is younger than connectedHandshakeAge, whose dial state exists, and whose mesh IP is an IPv4 address inside the mesh prefix other than the node's own. The entry of every other peer is deleted, so a peer that comes back starts without a value.
  4. Sends a probe to each taken peer in node ID order, rttProbeGap apart (see rttSend).

One probe per peer is outstanding at a time, and a new one replaces it. A node whose identity carries no usable domain_mesh_cidr holds a host /32 as its mesh prefix, so it probes nobody and answers nobody. Relay liveness (checkRelay, watchRelay) is unaffected; an answer moves RxBytes like any other packet.

DECISION: one probe per peer per interval. The value travels once per heartbeat interval with the handshake report, so more probes would measure what nobody reads. At the default interval that costs a node two 108-byte packets per peer every 30 s, its probe and its answer to the peer's probe (a 16-byte datagram is an 80-byte WireGuard message), about 0.6 MB a day per peer. The bridge watch of shared subnets writes requests on the same socket to each bridge that holds a value, on every endpoint selection pass (see Manager.watchBridges). The reader drops their replies, whose nonce matches no outstanding probe (see rttTable.answered), so they measure nothing and the decision stands; they move the device's RxBytes, which is what the watch reads.

func (*Manager) SetFailureDetection added in v0.38.0

func (m *Manager) SetFailureDetection(detectAfter time.Duration) (time.Duration, bool)

SetFailureDetection sets the failure-detection time, how long a relayed peer may stay silent before endpoint selection dials the next relay of its set (see watchRelay), and how long the path to the bridge of a shared subnet may stay dead before endpoint selection moves the subnet to the next live bridge of its entry (see watchBridges). It returns the value in force and whether it changed. A value of zero or less is ignored, and any other is clamped to MinFailureDetection and MaxFailureDetection. While a value is held, each pass watches relayed peers with watchRelay instead of checkRelay, and the bridges of the shared subnets with watchBridges, and RunEndpointSelection runs a pass every detectPass of the value, or at its own interval when that is shorter (see passInterval). While none is held, no bridge is watched and no subnet moves on its own.

A change restarts the silence window of every relayed peer and the window of every bridge of a shared subnet, so no peer is judged against a window it did not start under, and logs wireguard: failure detection time set with the new value, the previous one (0s when none was held) and the pass interval it gives. The value is not persisted: the first pull after a start delivers it again.

func (*Manager) SetLocalPrefixes added in v0.11.0

func (m *Manager) SetLocalPrefixes(fn func() ([]netip.Prefix, error))

SetLocalPrefixes sets the function the reconcile handler reads this host's interface prefixes from, to order a peer's on-link candidates first. Endpoint selection reads it too, to try a relayed peer's direct entries again when a local network makes one of them on-link. Call it before the handler and RunEndpointSelection run.

func (*Manager) SetPathMTUProbe added in v0.17.0

func (m *Manager) SetPathMTUProbe(probe func(context.Context) (int, error))

SetPathMTUProbe sets the function Setup and RunMTUProbe measure the uplink with. It returns the largest IPv4 packet size, in bytes, that reached a STUN server. Call it before Setup, like SetLocalPrefixes; without it the interface keeps DefaultMTU unless Config.MTU pins another.

func (*Manager) SetPeerPSK added in v0.11.0

func (m *Manager) SetPeerPSK(peerNodeID, publicKey string, psk []byte) error

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) SetPeerRouter added in v0.36.0

func (m *Manager) SetPeerRouter(r PeerRouter)

SetPeerRouter sets the router the reconcile handler programs the routes of the peers' routed subnets with. Call it before the handler runs. Without one, the manager programs the routed subnets as allowed IPs and adds no route.

func (*Manager) SetRelayProbe added in v0.22.0

func (m *Manager) SetRelayProbe(send func(meshIP netip.Addr) error)

SetRelayProbe sets the function endpoint selection sends the relay liveness probe with (see checkRelay, and watchRelay under a failure-detection time); plexd up passes SendRelayProbe. Call it before RunEndpointSelection, like SetLocalPrefixes. Without it no probe goes out, and a relayed peer counts as failed only once its handshake goes stale, whatever failure-detection time is held. The bridge watch of shared subnets sends the same probe to a bridge that answers no round-trip probe (see watchBridges); without a sender, the path to such a bridge counts as dead only once its handshake goes stale.

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.

It chooses the interface MTU first: a positive Config.MTU pins it, otherwise one round of the path MTU probe sizes it with MeshMTU, and without a probe, or when the round fails, it is DefaultMTU. The round runs before CreateInterface, so a round that waits out its timeout holds up startup without a half-configured interface on the host meanwhile.

func (*Manager) Teardown

func (m *Manager) Teardown() error

Teardown removes the routes syncPeerRoutes programmed and then deletes the WireGuard interface. A route it cannot remove is logged at Warn and stops nothing: the delete takes the interface's routes with it.

func (*Manager) UpdatePeer

func (m *Manager) UpdatePeer(peer api.Peer) error

UpdatePeer updates a peer configuration. WireGuard AddPeer is idempotent (upsert).

The first rule that applies decides the write:

  • A peer with no state, or whose public key changed, 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. The device peer of the old key is removed first: WireGuard moves to the new key only the allowed IPs its write names, so the old key would keep a routed subnet the update no longer lists and could still send from it.
  • A relayed peer, or one in a direct retry, whose update names relays tries its direct entries again (see retryDirect) when the update adds a direct entry that is neither among its direct entries nor remembered (see dialState.remembered): it tries every direct entry of the update that is not remembered, in the update's order, and ends on the relay relayAfter names. A running retry the update adds nothing to goes on with the entries it had left that the update still lists, from the first of them, or dials that relay at once when none is left. A direct entry the update drops is remembered (see triedAfter), here and in the two rules after this one.
  • A peer whose programmed entry is one of its Fallbacks, and that is relayed or not connected, moves to the update's first relay at once, on a fresh device peer (see redial), when the update takes its relay away (see relayMoved), and logs the move. A connected peer that is not relayed runs on a path it roamed to (see relayedOver), which the move would cut.
  • A relayed peer whose relay is still among the update's Fallbacks stays on it, connected or not, even on a standby it moved to on its own: the write carries no endpoint, and the position moves to the relay's in the new order.
  • A connected peer 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. A relayed peer gets here only when the update has no Fallbacks, and it stops being relayed.
  • Any other peer starts over from the first entry of its new order, including a peer in a direct retry whose update names no relays.

A failed write leaves the state as it was.

func (*Manager) UpdatePrivateKey added in v0.2.0

func (m *Manager) UpdatePrivateKey(privateKey []byte) error

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
	RTT              time.Duration // zero when the peer holds no value
	// SharedSubnets are the shared subnets whose holder is the peer, sorted
	// by address and then by prefix length, nil when there are none.
	SharedSubnets []string
}

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 MeshRewriter added in v0.39.0

type MeshRewriter struct {
	// contains filtered or unexported fields
}

MeshRewriter rewrites, inside the process, the source of what the far end of a registered interface sends into the mesh to the mesh interface's address.

Windows has no kernel mechanism that fits: WinNAT translates nothing into the mesh beside the NetNat object the bridge NAT keeps for the mesh prefix, and what it translates passes no WFP forward filter. Every packet between a provider's or a tunnel's device and the mesh device already passes through plexd, because all of them are wireguard-go devices of this process. Wrap puts the rewriter between each such device and its tun, so a far end's packet is translated and handed to the mesh device's wireguard-go before Windows sees it, and a mesh peer's reply goes back the same way. The rules are in meshrewrite_nat.go.

The three rewrite methods have the signatures of bridge.MeshSourceRewriter; this package does not import internal/bridge, so the assertion sits with the wiring in cmd/plexd/cmd. All of them are idempotent. Nothing of a rewrite outlives the process.

func NewMeshRewriter added in v0.39.0

func NewMeshRewriter(logger *slog.Logger) *MeshRewriter

NewMeshRewriter returns a rewriter that knows no device and holds no rewrite.

func (*MeshRewriter) AddMeshSourceRewrite added in v0.39.0

func (r *MeshRewriter) AddMeshSourceRewrite(fromIface, meshIface string) error

AddMeshSourceRewrite rewrites the source of what the far ends behind fromIface send into the mesh to the address of meshIface, the first IPv4 address it carries. Both must be devices Wrap knows; a fromIface that is none, such as a vendor client's adapter, needs no rewrite, because its client already sends with the host's address. A rewrite that exists for fromIface is left alone.

func (*MeshRewriter) RemoveMeshSourceRewrite added in v0.39.0

func (r *MeshRewriter) RemoveMeshSourceRewrite(fromIface, meshIface string) error

RemoveMeshSourceRewrite forgets the rewrite of fromIface and its flows. meshIface is not needed to find it and is only logged. Idempotent: an interface without a rewrite returns nil.

func (*MeshRewriter) ResetMeshSourceRewrite added in v0.39.0

func (r *MeshRewriter) ResetMeshSourceRewrite() error

ResetMeshSourceRewrite forgets every rewrite and its flows. Nothing of a rewrite outlives the process, so a start has nothing to remove.

func (*MeshRewriter) SetMeshAddress added in v0.40.0

func (r *MeshRewriter) SetMeshAddress(meshIface string, addr netip.Addr)

SetMeshAddress moves every rewrite into meshIface to addr, the address the mesh interface carries since the node was moved, and forgets the flows that were translated to another address. A rewrite reads the address once, when it is added, so without this call it would keep the address the interface no longer holds. An addr that is no IPv4 address changes nothing, since the rules rewrite IPv4 alone.

func (*MeshRewriter) Wrap added in v0.39.0

func (r *MeshRewriter) Wrap(name string, dev tun.Device) tun.Device

Wrap returns the tun.Device to hand wireguard-go in place of dev and knows it under name until it is closed.

A nil dev returns nil, so UserspaceBackend.CreateDevice still refuses it. The wrapper owns dev: closing the wrapper closes dev.

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.

A WireGuard link that already holds the name is one a process left behind that ended without its teardown, as a plexd that was killed or crashed does: the kernel keeps the link when its process ends. CreateInterface deletes that link with its addresses, routes and peers and creates the interface afresh, so the next start does not run without its mesh interface until someone deletes the link by hand. A link of another type keeps the name and fails the create.

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. The allowed IPs are converted with allowedIPPrefixes.

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) ReplaceAddress added in v0.40.0

func (c *NetlinkController) ReplaceAddress(name, oldAddress, newAddress string) error

ReplaceAddress swaps oldAddress for newAddress on the named interface. The link, its peers and the routes through it stay.

It takes five netlink calls: add the new address as a /32, delete the old address, add the new address with its prefix length, delete the /32, and replace the new address with itself. The order is measured on kernel 6.8.0-147 with a dummy link that held 10.99.0.1/24 and a route 172.16.5.0/24 through it. Deleting the only address of a link removes every route of the link, that route included. Adding the new address and then deleting the old one removes both addresses and every route, because the new one is a secondary of the old one and promote_secondaries is 0. The first four calls keep the route and end with 10.99.0.0/24 proto kernel src 10.99.0.9. Switching promote_secondaries on would write /proc/sys, which fails in a container that holds NET_ADMIN alone.

systemd-resolved keeps the addresses of a link by family and address, without the prefix length, so it takes the delete of the /32 as the removal of the new address, holds no address for the link and drops the link's DNS scope. The fifth call changes neither the address nor a route and makes the kernel send RTM_NEWADDR for the address again, so a listener that keeps addresses that way ends holding it. That was measured on the same kernel with systemd-resolved 255.

A pair of /32 addresses takes two calls, add the new one and delete the old one, because the other calls would delete the address they just added, and its last event for the new address is already its add. The adds tolerate EEXIST and the deletes EADDRNOTAVAIL, so a call that failed halfway succeeds when it is repeated with the same arguments.

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 route calls of the manager's peer routes, 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 NewPeerIndex

func NewPeerIndex() *PeerIndex

NewPeerIndex creates an empty PeerIndex.

func (*PeerIndex) Add

func (p *PeerIndex) Add(peerID, publicKey string)

Add adds or overwrites the mapping from peerID to publicKey.

func (*PeerIndex) Count

func (p *PeerIndex) Count() int

Count returns the number of peers in the index.

func (*PeerIndex) LoadFromPeers

func (p *PeerIndex) LoadFromPeers(peers []api.Peer)

LoadFromPeers bulk-populates the index from a slice of api.Peer. It clears all existing entries before adding the new ones.

func (*PeerIndex) Lookup

func (p *PeerIndex) Lookup(peerID string) (publicKey string, ok bool)

Lookup returns the public key for the given peerID and whether it was found.

func (*PeerIndex) NodeIDsByPublicKey added in v0.10.0

func (p *PeerIndex) NodeIDsByPublicKey() map[[32]byte]string

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.

func (*PeerIndex) Remove

func (p *PeerIndex) Remove(peerID string)

Remove removes the mapping for peerID. It is a no-op if peerID is not present.

func (*PeerIndex) Update

func (p *PeerIndex) Update(peerID, newPublicKey string)

Update updates the mapping from peerID to newPublicKey. It is equivalent to Add but semantically distinct for clarity.

type PeerRouter added in v0.36.0

type PeerRouter interface {
	// AddRoute adds a route for subnet, a CIDR, through the interface the
	// operating system knows as iface.
	AddRoute(subnet, iface string) error
	// RemoveRoute removes the route for subnet through iface.
	RemoveRoute(subnet, iface string) error
}

PeerRouter adds and removes the routes that carry a peer's routed subnets into the mesh interface. Every bridge.RouteController satisfies it. Both calls are idempotent: adding a route that exists and removing one that does not return nil.

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
	// AllowedIPs are the peer's allowed IPs in the device's order, nil when
	// it has none.
	AllowedIPs []netip.Prefix
}

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL