nat

package
v0.25.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: Apache-2.0 Imports: 17 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

Overview

Package nat provides NAT traversal via STUN for plexd mesh nodes.

Package nat implements STUN-based NAT traversal and endpoint discovery.

Index

Constants

View Source
const DefaultMinReportInterval = 10 * time.Second

DefaultMinReportInterval is the default floor on the deadline-driven endpoint report cadence.

View Source
const DefaultRefreshInterval = 60 * time.Second

DefaultRefreshInterval is the default interval between STUN binding refreshes.

View Source
const DefaultTimeout = 5 * time.Second

DefaultTimeout is the default per-server STUN request timeout.

View Source
const MTUProbeTimeout = 2 * time.Second

MTUProbeTimeout bounds one probe round.

Variables

View Source
var DefaultSTUNServers = []string{
	"stun.l.google.com:19302",
	"stun.cloudflare.com:3478",
}

DefaultSTUNServers is the default list of STUN servers used for NAT traversal.

View Source
var ErrMTUProbeInconclusive = errors.New("nat: mtu probe: no STUN server answered")

ErrMTUProbeInconclusive is returned by ProbePathMTU when no STUN server answered any probe, so the round says nothing about the path.

View Source
var MTUProbeSizes = []int{1500, 1492, 1480, 1472, 1460, 1452, 1440, 1428, 1420, 1400, 1380, 1360}

MTUProbeSizes are the IPv4 packet sizes ProbePathMTU tries, in bytes.

They cover the common uplinks, Ethernet (1500), PPPoE (1492), DS-Lite (1460) and DS-Lite over PPPoE (1452), with steps in between, down to 1360. A path smaller than 1360 leaves the mesh at its 1280 minimum anyway, so nothing below it is worth a datagram. Every entry minus the 28 bytes of IPv4 and UDP header is a valid size for buildPaddedBindingRequest.

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

func ProbePathMTU(ctx context.Context, servers []string, timeout time.Duration) (int, error)

ProbePathMTU returns the largest IPv4 packet size, in bytes, that reached a STUN server.

Every server gets an unpadded baseline request and one request per MTUProbeSizes entry, padded to that packet size and sent with the don't-fragment bit set, all at once. Each request goes out on its own socket: Linux reports a router's "fragmentation needed" as EMSGSIZE on the next read of the socket that sent the packet, and on a shared socket that error could not be pinned to a probe. A request that draws an error, or no answer before the round ends, was not carried. The errors are not classified, because they all mean the same thing here.

The result is the maximum over servers, not the minimum: an answer proves the uplink carried that size, and one lost probe at one server must not lower the mesh MTU. The baseline counts as 48 bytes, so a server that answers only the unpadded request still yields a result.

The round lasts at most timeout, or until ctx is done, and ends as soon as every probe has: on a healthy uplink after one round trip. When nothing was answered, the error wraps ErrMTUProbeInconclusive and each server's reason. With no servers it is the bare sentinel, and no socket is opened. When ctx is done at the end of the round, the error is ctx's, whatever was answered. The probe logs nothing; its callers do.

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

func (c *Config) LocalCandidatesEnabled() bool

LocalCandidatesEnabled returns the effective LocalCandidates setting: true unless explicitly set to false.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks that configuration values are within acceptable ranges. CandidateInterfaces is checked before the Enabled early return, because the candidate publisher runs whether or not STUN traversal is enabled.

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

type Interface struct {
	Name     string
	Index    int
	Flags    net.Flags
	Prefixes []netip.Prefix
}

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

func SystemInterfaces() ([]Interface, error)

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

type MappedAddress struct {
	IP   net.IP
	Port int
}

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 NATType

type NATType string

NATType represents the classified NAT behavior.

const (
	NATNone      NATType = "none"
	NATFullCone  NATType = "full_cone"
	NATSymmetric NATType = "symmetric"
	NATUnknown   NATType = "unknown"
)

func (NATType) Wire added in v0.2.0

func (t NATType) Wire() string

Wire returns the control-plane wire representation of the NAT type. The wire enum has no "none": an un-NATed endpoint is directly reachable with no filtering, which is the full_cone traversal posture.

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

type UDPSTUNClient struct {
	Timeout time.Duration
}

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.

Jump to

Keyboard shortcuts

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