Documentation
¶
Overview ¶
Package nat provides NAT traversal via STUN for plexd mesh nodes.
Package nat implements STUN-based NAT traversal and endpoint discovery.
Index ¶
- Constants
- Variables
- func EligiblePrefixes(ifaces []Interface, f CandidateFilter) []netip.Prefix
- func GatherCandidates(port int, f CandidateFilter) (candidates []string, truncated int, err error)
- func SelectCandidates(ifaces []Interface, port int, f CandidateFilter) (candidates []string, truncated int)
- type CandidateFilter
- type CandidatePublisher
- type CandidateReporter
- type Config
- type Discoverer
- type DiscoveryResult
- type EndpointReporter
- type Interface
- type MappedAddress
- type NATType
- type PortMapping
- type STUNClient
- type UDPSTUNClient
Constants ¶
const DefaultMinReportInterval = 10 * time.Second
DefaultMinReportInterval is the default floor on the deadline-driven endpoint report cadence.
const DefaultRefreshInterval = 60 * time.Second
DefaultRefreshInterval is the default interval between STUN binding refreshes.
const DefaultTimeout = 5 * time.Second
DefaultTimeout is the default per-server STUN request timeout.
Variables ¶
var DefaultSTUNServers = []string{
"stun.l.google.com:19302",
"stun.cloudflare.com:3478",
}
DefaultSTUNServers is the default list of STUN servers used for NAT traversal.
Functions ¶
func EligiblePrefixes ¶ added in v0.11.0
func EligiblePrefixes(ifaces []Interface, f CandidateFilter) []netip.Prefix
EligiblePrefixes returns the prefixes of every eligible address, under the same interface and address rules SelectCandidates applies. An IPv4-mapped IPv6 prefix comes back as the IPv4 prefix it carries. The WireGuard manager reads them to tell which of a peer's candidates share a subnet with this node, so they are neither deduplicated against the candidates nor capped at api.MaxEndpointCandidates.
func GatherCandidates ¶ added in v0.11.0
func GatherCandidates(port int, f CandidateFilter) (candidates []string, truncated int, err error)
GatherCandidates reads the host's interfaces and selects the candidates joined with port. A failed read is returned unchanged.
func SelectCandidates ¶ added in v0.11.0
func SelectCandidates(ifaces []Interface, port int, f CandidateFilter) (candidates []string, truncated int)
SelectCandidates renders each eligible address joined with port as a host:port candidate. The order is IPv4 before IPv6, then the lower interface index, then the lower address, so a report is stable across cycles and the cap keeps the same addresses. An address on two interfaces is published once, at its first position. Past api.MaxEndpointCandidates the rest are dropped and counted in truncated. Nothing eligible yields an empty non-nil slice, the report that withdraws every earlier candidate.
Types ¶
type CandidateFilter ¶ added in v0.11.0
type CandidateFilter struct {
// Interfaces is an allowlist of interface names. Empty means every
// eligible interface. A listed name bypasses virtualInterfacePrefixes.
Interfaces []string
// ExcludeInterfaces names interfaces that are always skipped: the mesh
// interface, whose addresses a peer reaches through the tunnel itself.
ExcludeInterfaces []string
// ExcludePrefix skips every address inside it: the Domain mesh prefix.
// The zero prefix skips nothing.
ExcludePrefix netip.Prefix
}
CandidateFilter narrows the interfaces and addresses published as endpoint candidates.
type CandidatePublisher ¶ added in v0.11.0
type CandidatePublisher struct {
// contains filtered or unexported fields
}
CandidatePublisher reports the node's local endpoint candidates to the control plane on its own loop. It is independent of STUN discovery: a node whose STUN servers are unreachable still has LAN addresses a peer on the same network can dial, and a failed initial discovery ends the Discoverer for good.
func NewCandidatePublisher ¶ added in v0.11.0
func NewCandidatePublisher(gather func() ([]string, int, error), cfg Config, logger *slog.Logger) *CandidatePublisher
NewCandidatePublisher creates a CandidatePublisher. gather returns the candidates to report and how many were dropped past the cap; cfg supplies RefreshInterval and MinReportInterval.
func (*CandidatePublisher) Run ¶ added in v0.11.0
func (p *CandidatePublisher) Run(ctx context.Context, reporter CandidateReporter, nodeID string) error
Run reports the candidates at once and then once per cycle until ctx is done, when it returns nil. After an accepted report the next one follows the control plane's stale_after deadline as the Discoverer's does; after any failure, a failed interface read included, it follows RefreshInterval. No answer ends the loop: a control plane that does not serve the operation yet is asked again every cycle, so an upgrade is picked up without a restart.
type CandidateReporter ¶ added in v0.11.0
type CandidateReporter interface {
ReportEndpointCandidates(ctx context.Context, nodeID string, req api.EndpointCandidatesRequest) (*api.EndpointCandidatesResponse, error)
}
CandidateReporter abstracts the control plane's endpoint candidates API. *api.ControlPlane satisfies it.
type Config ¶
type Config struct {
// Enabled controls whether NAT traversal is active.
// Default: true (set by ApplyDefaults).
Enabled bool `yaml:"enabled"`
// STUNServers is the list of STUN server addresses (host:port).
STUNServers []string `yaml:"stun_servers"`
// RefreshInterval is the interval between STUN binding refreshes.
// Must be at least 10s.
RefreshInterval time.Duration `yaml:"refresh_interval"`
// Timeout is the per-server STUN request timeout.
// Must be positive.
Timeout time.Duration `yaml:"timeout"`
// MinReportInterval is the floor on the endpoint report cadence derived
// from the control plane's stale_after deadline. A short deadline can
// otherwise drive STUN queries and endpoint reports well above
// RefreshInterval; raising this bounds how far the server may accelerate
// the loop. Must be positive.
// Default: 10s (set by ApplyDefaults).
MinReportInterval time.Duration `yaml:"min_report_interval"`
// LocalCandidates controls whether the node publishes its local interface
// addresses as endpoint candidates. A pointer, so an unset key stays
// distinguishable from an explicit false: publishing is the default, and
// `local_candidates: false` must survive ApplyDefaults exactly as written
// rather than be decided by its zero-value heuristic. It is independent of
// Enabled, because a node whose STUN servers are unreachable still has LAN
// addresses a peer can dial.
// Default: true (nil reads as enabled).
LocalCandidates *bool `yaml:"local_candidates"`
// CandidateInterfaces restricts the published candidates to the named
// interfaces. Empty publishes every eligible interface. A named interface
// is published even when its name marks it as virtual (docker0, br-...),
// because naming it is the operator's choice.
CandidateInterfaces []string `yaml:"candidate_interfaces"`
}
Config holds the configuration for NAT traversal.
func (*Config) ApplyDefaults ¶
func (c *Config) ApplyDefaults()
ApplyDefaults sets default values for zero-valued fields. On a zero-valued Config, Enabled defaults to true. To disable NAT traversal, set Enabled=false before or after calling ApplyDefaults.
func (*Config) LocalCandidatesEnabled ¶ added in v0.11.0
LocalCandidatesEnabled returns the effective LocalCandidates setting: true unless explicitly set to false.
type Discoverer ¶
type Discoverer struct {
// contains filtered or unexported fields
}
Discoverer performs STUN-based NAT traversal to discover the node's public endpoint.
STUN runs on its own ephemeral UDP socket, never on the WireGuard listen port: the kernel WireGuard socket owns that port, and UDP port sharing would require SO_REUSEPORT on both sockets, which the kernel side does not set — a bind attempt fails with EADDRINUSE on every node whose WireGuard interface is up. The mapped address therefore describes the STUN socket's mapping, and the published endpoint carries the mapped IP with the advertised WireGuard listen port instead. That endpoint is exact wherever the NAT preserves the port; where it translates ports, the reported port_mapping (translated) marks the endpoint as an assumption that holds only where the router forwards or preserves the listen port.
func NewDiscoverer ¶
func NewDiscoverer(client STUNClient, cfg Config, advertisePort int, logger *slog.Logger) *Discoverer
NewDiscoverer creates a new Discoverer. advertisePort is the WireGuard listen port carried in every published endpoint.
func (*Discoverer) Discover ¶
func (d *Discoverer) Discover(ctx context.Context) (*DiscoveryResult, error)
Discover performs STUN binding requests to discover the public endpoint and classify NAT type.
func (*Discoverer) LastResult ¶
func (d *Discoverer) LastResult() *DiscoveryResult
LastResult returns the most recently discovered NAT info, or nil if no discovery has succeeded.
func (*Discoverer) Run ¶
func (d *Discoverer) Run(ctx context.Context, reporter EndpointReporter, nodeID string) error
Run performs initial STUN discovery, reports the endpoint, then enters a refresh loop. It blocks until ctx is cancelled or an unrecoverable error occurs.
type DiscoveryResult ¶
type DiscoveryResult struct {
Endpoint string // "ip:port" format
NATType NATType
PortMapping PortMapping
}
DiscoveryResult holds the outcome of a STUN discovery cycle.
type EndpointReporter ¶
type EndpointReporter interface {
ReportEndpoint(ctx context.Context, nodeID string, req api.EndpointRequest) (*api.EndpointResponse, error)
}
EndpointReporter abstracts the control plane endpoint reporting API.
type Interface ¶ added in v0.11.0
Interface is one network interface as candidate gathering sees it: the fields of net.Interface the eligibility rules read, and its addresses as prefixes. It exists so the rules can be tested over fabricated interfaces instead of the host's.
func SystemInterfaces ¶ added in v0.11.0
SystemInterfaces reads the host's interfaces and their addresses. An interface whose addresses cannot be read is skipped rather than failing the whole read, and an address that is not an *net.IPNet is ignored.
type MappedAddress ¶
MappedAddress represents a STUN XOR-MAPPED-ADDRESS result.
func (MappedAddress) Routable ¶ added in v0.2.0
func (m MappedAddress) Routable() bool
Routable reports whether the address can serve as this node's public endpoint: a port in 1..65535 and an IP that is neither loopback, link-local, nor unspecified.
A STUN Binding Response is unauthenticated, so the mapped address it carries is attacker-influenceable: an on-path attacker or the operator of a configured STUN server can name any address. The control plane hands that address to every mesh peer, which would then aim WireGuard handshakes at it — traffic redirection and a reflection primitive against a third party. A loopback or unspecified value instead blackholes the node. Neither is ever a legitimate public endpoint, so both are rejected before the address is published.
func (MappedAddress) String ¶
func (m MappedAddress) String() string
String returns the address in canonical "host:port" form; IPv6 hosts are bracketed per RFC 5952.
type PortMapping ¶ added in v0.12.0
type PortMapping string
PortMapping records whether the NAT kept the STUN probe's source port, and so whether the published endpoint was observed or assumed. Its values are the wire values of the endpoint report's port_mapping member.
const ( // PortPreserved: the mapped port equals the probe's source port. The // published endpoint (mapped IP, WireGuard listen port) matches what // discovery observed. PortPreserved PortMapping = "preserved" // PortTranslated: the NAT assigned its own port. The published endpoint // assumes the router forwards or preserves the WireGuard listen port. PortTranslated PortMapping = "translated" )
type STUNClient ¶
type STUNClient interface {
Bind(ctx context.Context, serverAddr string, localPort int) (MappedAddress, int, error)
}
STUNClient abstracts STUN binding operations for testability.
Bind sends a Binding Request to serverAddr from localPort and returns the mapped address together with the local port the request was actually sent from. A localPort of 0 lets the OS pick an ephemeral port; the returned port tells the caller which one, so a discovery cycle can reuse it across servers and compare their mapped addresses meaningfully.
type UDPSTUNClient ¶
UDPSTUNClient performs STUN binding requests over UDP.
func (*UDPSTUNClient) Bind ¶
func (c *UDPSTUNClient) Bind(ctx context.Context, serverAddr string, localPort int) (MappedAddress, int, error)
Bind sends a STUN Binding Request to serverAddr from localPort (0 for an OS-assigned ephemeral port) and returns the mapped address from the response along with the local port the socket was bound to.