network

package
v1.20.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: AGPL-3.0 Imports: 15 Imported by: 3

Documentation

Index

Constants

View Source
const VPNRouteMetric = 9999

VPNRouteMetric is the route metric/priority assigned to routes we add for the tunnel, so that an overlapping local/connected route is always preferred over the VPN route to the same destination rather than the two silently racing based on insertion order. It needs to be higher than any metric a local route is realistically going to have: on Linux, automatic metrics assigned by NetworkManager (which also apply to the connected subnet route, not just the default route) go up to 600 for Wi-Fi; on Windows, automatic interface metrics plus route metric rarely exceed a few hundred. 9999 comfortably clears both without needing to query the local routing table at add-time.

Variables

View Source
var ErrNoPhysicalRoute = errors.New("no route outside the tunnel")

ErrNoPhysicalRoute is returned (wrapped) when a bypass route can't be installed or reconciled because there is currently no route to the destination outside the tunnel - typically because the host is offline or between networks. Callers can treat it as transient: the next reconcile after the network comes back installs the route.

View Source
var NativeConfigDisabled = false

NativeConfigDisabled, when true, skips the raw `ifconfig`/`route` subprocess calls this package otherwise makes on darwin (configureDarwin, removeDarwinAddress, DarwinAddRouteWithSource, DarwinRemoveRoute) while still populating the JSON-facing NetworkSettings state. This must be set when the TUN device's addresses/routes are instead owned by an external mechanism that reconciles them independently - namely Apple's NetworkExtension (NEPacketTunnelProvider.setTunnelNetworkSettings), which is the sole sanctioned way to configure that virtual interface. Running our own ifconfig/route commands in addition to NE applying its own settings was observed to install two competing routes to the same destination (one via NE's gatewayAddress-based route, one via our own `-ifa` route), so the two mechanisms must be mutually exclusive rather than layered.

View Source
var PreferLocalRoutes = false

PreferLocalRoutes controls whether routes added by AddRoutes are given the explicit high VPNRouteMetric priority, so that an overlapping local/ connected route always takes precedence over the VPN route to the same destination. Defaults to false (routes are added with the OS default metric/priority, matching behavior prior to the introduction of VPNRouteMetric); callers that want local routes to win opt in by setting this to true (e.g. from a config value) before routes are added.

Functions

func AddBypassRouteForDestination added in v1.18.0

func AddBypassRouteForDestination(destIP string, tunnelInterface string) error

AddBypassRouteForDestination installs an explicit /32 host route for destIP using whatever gateway/interface the OS routing table currently uses to reach it - i.e. the physical/original path, not the tunnel. It must be called BEFORE AddGatewayDefaultRoute so the destination's own path is pinned down first and can never be captured by the more general gateway route. This is the same technique wg-quick uses (set_endpoint_direct_route) to keep a WireGuard peer's own UDP traffic from being captured by the gateway route it is itself responsible for installing.

tunnelInterface is the interface the gateway route is (or will be) installed on. Routes on it are ignored when looking up the current path to destIP, so a bypass route added while the gateway route is already installed still points at the physical network rather than back into the tunnel. May be "" if there is no tunnel interface to ignore.

NetworkSettings is always populated (an excluded route, for mobile packet-tunnel providers), regardless of GOOS; the OS routing table is only touched on desktop platforms, which have no equivalent of NEIPv4Settings.excludedRoutes/VpnService.Builder.excludeRoute.

func AddGatewayDefaultRoute added in v1.18.0

func AddGatewayDefaultRoute(interfaceName, sourceIP string) error

AddGatewayDefaultRoute installs the OS-level "route everything" equivalent for a full-tunnel/gateway peer. NetworkSettings is always populated first (regardless of GOOS - mobile packet-tunnel providers read it independent of platform, see AddRouteForServerIPWithSource), via an IsDefault included route. On desktop platforms, where olm manages the OS routing table directly, this then also installs the standard wg-quick split-default-route technique (0.0.0.0/1 + 128.0.0.0/1) instead of a literal 0.0.0.0/0, so the host's real default route is never replaced or raced with - it is only outranked by two strictly more-specific halves. PreferLocalRoutes (if set) still applies to these routes exactly as it does to any other tunnel route, so an overlapping local/LAN route continues to win even in gateway mode.

func AddIPv4Address added in v1.16.0

func AddIPv4Address(address string, subnetMask string) error

AddIPv4Address appends an additional IPv4 address/subnet mask pair to the tunnel's network settings. This is how a secondary interface address gets exposed to mobile (iOS/Android) packet-tunnel providers, which read the full IPv4Addresses/IPv4SubnetMasks arrays (not just the first entry) and re-apply them on every settings poll.

It requires a primary address to already be set (via SetIPv4Settings, i.e. ConfigureInterface) and refuses to add otherwise: on mobile platforms, array order is what determines which address the OS treats as primary, so appending to an empty list would silently make this "additional" address the primary one instead.

func AddIPv4ExcludedRoute added in v1.18.0

func AddIPv4ExcludedRoute(route IPv4Route)

AddIPv4ExcludedRoute adds a single excluded route, e.g. so mobile (iOS/Android) packet-tunnel providers keep a specific destination (a site's live endpoint, the control-plane server) out of an otherwise-broad included route such as a full-tunnel/gateway default route. Mirrors AddIPv4IncludedRoute's dedup-by-equality behavior.

func AddIPv4IncludedRoute added in v1.8.0

func AddIPv4IncludedRoute(route IPv4Route)

func AddRouteForNetworkConfig added in v1.8.0

func AddRouteForNetworkConfig(destination string) error

func AddRouteForNetworkConfigWithGateway added in v1.16.0

func AddRouteForNetworkConfigWithGateway(destination string, gateway string) error

AddRouteForNetworkConfigWithGateway is AddRouteForNetworkConfig with an explicit gateway address for the route entry surfaced via NetworkSettings. This is consumed by mobile (iOS/macOS NetworkExtension) packet-tunnel providers as NEIPv4Route.gatewayAddress. NetworkExtension gives us no direct way to pin a route's source address (no equivalent of BSD's `route -ifa`) - but setting gatewayAddress to one of the tunnel interface's own addresses makes the OS resolve "how do I reach this gateway" recursively to that address/interface pairing, which is what determines the source address used for packets matching the route. This is the same underlying mechanism as `route add -gateway` (see DarwinAddRoute's gateway branch).

func AddRouteForServerIP added in v1.8.0

func AddRouteForServerIP(serverIP, interfaceName string) error

addRouteForServerIP adds an OS-specific route for the server IP

func AddRouteForServerIPWithSource added in v1.16.0

func AddRouteForServerIPWithSource(serverIP, interfaceName string, sourceIP string) error

AddRouteForServerIPWithSource is AddRouteForServerIP with an explicit source address for the darwin route (see DarwinAddRouteWithSource) - needed when the interface carries more than one address, e.g. an exit node connection where the interface's primary address belongs to the site tunnel rather than the exit node.

func AddRoutes added in v1.8.0

func AddRoutes(remoteSubnets []string, interfaceName string) error

addRoutes adds routes for each subnet in RemoteSubnets

func AddRoutesWithSource added in v1.16.0

func AddRoutesWithSource(remoteSubnets []string, interfaceName string, sourceIP string) error

AddRoutesWithSource is AddRoutes with an explicit source address for the darwin routes (see DarwinAddRouteWithSource) - needed when the interface carries more than one address (e.g. a site tunnel address alongside an exit node's secondary address), so the routes for these subnets are pinned to the address they actually belong to rather than whichever address darwin would otherwise default to.

func AddSecondaryAddress added in v1.16.0

func AddSecondaryAddress(interfaceName string, addr string) error

AddSecondaryAddress adds an additional IP address (given as CIDR, e.g. "10.10.0.5/32") to an already-configured interface. It also records the address in the shared NetworkSettings (see AddIPv4Address) so mobile (iOS/Android) packet-tunnel providers pick it up on their next settings poll - those platforms have no OS-level interface to configure directly, so this is the only way they learn about the address.

func ClearNetworkSettings added in v1.8.0

func ClearNetworkSettings()

ClearNetworkSettings clears all network settings

func ConfigureInterface added in v1.8.0

func ConfigureInterface(interfaceName string, tunnelIp string, mtu int) error

ConfigureInterface configures a network interface with an IP address and brings it up

func DarwinAddBypassRoute added in v1.18.0

func DarwinAddBypassRoute(destIP string, tunnelInterface string) error

DarwinAddBypassRoute adds an explicit /32 host route for destIP via whatever gateway/interface the kernel currently uses to reach it (parsed from `route -n get`), so a broader route added afterward can never capture this destination - see AddBypassRouteForDestination. If that route is on tunnelInterface - i.e. a gateway route (0.0.0.0/1 + 128.0.0.0/1) is already capturing destIP - the physical default route, which the gateway route deliberately leaves in place, is used instead (see darwinBypassNextHop).

func DarwinAddRoute added in v1.8.0

func DarwinAddRoute(destination string, gateway string, interfaceName string) error

DarwinAddRoute adds a route via the BSD routing table. Unlike Linux/Windows, BSD's routing table has no per-route metric - preference between an overlapping local route and this VPN route is instead resolved by longest-prefix-match, and `route add` (as opposed to `route change`) fails rather than replacing an existing route to the same destination, so a local route is never displaced by one we add here.

func DarwinAddRouteWithSource added in v1.16.0

func DarwinAddRouteWithSource(destination string, gateway string, interfaceName string, sourceIP string) error

DarwinAddRouteWithSource is DarwinAddRoute with an explicit source address (route(8) `-ifa`). This is required when the interface carries more than one address (e.g. an exit node's secondary tunnel address alongside the site tunnel's primary address): without `-ifa`, BSD picks a source address for the route on its own - typically the interface's primary address - and WireGuard's own reverse-path filtering on the remote end will silently drop packets whose source doesn't match the peer's configured AllowedIPs, even though the tunnel/handshake itself stays up.

func DarwinRemoveBypassRoute added in v1.18.0

func DarwinRemoveBypassRoute(destIP string) error

DarwinRemoveBypassRoute removes a route previously added by DarwinAddBypassRoute.

func DarwinRemoveRoute added in v1.8.0

func DarwinRemoveRoute(destination string) error

func FindUnusedUTUN added in v1.8.0

func FindUnusedUTUN() (string, error)

func GetIncrementor added in v1.8.0

func GetIncrementor() int

func GetJSON added in v1.8.0

func GetJSON() (string, error)

func GetLocalEndpoints added in v1.15.0

func GetLocalEndpoints(port uint16, excludeInterface string, allowedInterfaces []string) []string

GetLocalEndpoints returns "ip:port" strings (bracketed for IPv6, e.g. "[fe80::1]:51820") for every usable, non-loopback IP address bound to a network interface on this host. The list is ordered with interfaces most likely to be a genuine host network (wired/Wi-Fi) first, and interfaces that are typically synthetic (Docker, VPN tunnels, hypervisor bridges, etc.) last, so callers should try the results roughly in order.

excludeInterface, if non-empty, is skipped entirely - this is normally the name of our own WireGuard/TUN interface, whose address is the tunnel IP and not a useful endpoint to advertise.

allowedInterfaces, if non-empty, restricts the result to only those interface names (an allowlist), letting callers report a single known-good interface instead of every candidate on the host.

If interfaces cannot be enumerated (e.g. insufficient OS permissions), an info message is logged and an empty slice is returned.

func LinuxAddBypassRoute added in v1.18.0

func LinuxAddBypassRoute(destIP string, tunnelInterface string) error

LinuxAddBypassRoute adds an explicit /32 host route for destIP via whatever gateway/interface the kernel currently uses to reach it, so a broader route added afterward (e.g. a gateway/full-tunnel default route) can never capture this destination - see AddBypassRouteForDestination. Routes on tunnelInterface are ignored when picking that path - see linuxBypassNextHop. Replaces any existing /32 route to destIP.

func LinuxAddRoute added in v1.8.0

func LinuxAddRoute(destination string, gateway string, interfaceName string) error

func LinuxRemoveBypassRoute added in v1.18.0

func LinuxRemoveBypassRoute(destIP string) error

LinuxRemoveBypassRoute removes a route previously added by LinuxAddBypassRoute. It deliberately does not re-derive the route via RouteGet - by the time this runs, our own /32 bypass route is the most specific match for destIP and RouteGet would just find itself - so it instead deletes by destination alone.

func LinuxRemoveRoute added in v1.8.0

func LinuxRemoveRoute(destination string, interfaceName string) error

func ManagesHostRoutes added in v1.18.1

func ManagesHostRoutes() bool

ManagesHostRoutes reports whether this package installs routes in the host OS routing table itself (desktop platforms), as opposed to only populating NetworkSettings for a mobile/NetworkExtension host app to apply.

func ReconcileBypassRoute added in v1.18.1

func ReconcileBypassRoute(destIP string, tunnelInterface string) (bool, error)

ReconcileBypassRoute makes sure the host route AddBypassRouteForDestination installed for destIP is still present and still follows the current physical path, re-adding or moving it if not. The OS drops these routes along with the interface or address they were on (e.g. switching Wi-Fi networks, or Wi-Fi to Ethernet), and if the default route moves to a different interface they would otherwise keep using the old one. Routes on tunnelInterface are ignored, as in AddBypassRouteForDestination. Returns whether anything changed; a no-op where ManagesHostRoutes is false. NetworkSettings is not touched - platforms that apply excluded routes from it track the physical network themselves.

func RemoveBypassRouteForDestination added in v1.18.0

func RemoveBypassRouteForDestination(destIP string) error

RemoveBypassRouteForDestination reverses AddBypassRouteForDestination.

func RemoveGatewayDefaultRoute added in v1.18.0

func RemoveGatewayDefaultRoute(interfaceName string) error

RemoveGatewayDefaultRoute reverses AddGatewayDefaultRoute.

func RemoveIPv4Address added in v1.16.0

func RemoveIPv4Address(address string)

RemoveIPv4Address removes a previously added secondary IPv4 address.

func RemoveIPv4ExcludedRoute added in v1.18.0

func RemoveIPv4ExcludedRoute(route IPv4Route)

RemoveIPv4ExcludedRoute reverses AddIPv4ExcludedRoute.

func RemoveIPv4IncludedRoute added in v1.8.0

func RemoveIPv4IncludedRoute(route IPv4Route)

func RemoveRouteForNetworkConfig added in v1.8.0

func RemoveRouteForNetworkConfig(destination string) error

func RemoveRouteForNetworkConfigWithGateway added in v1.16.0

func RemoveRouteForNetworkConfigWithGateway(destination string, gateway string) error

RemoveRouteForNetworkConfigWithGateway is RemoveRouteForNetworkConfig with an explicit gateway address. This must match whatever gateway the route was added with (see AddRouteForNetworkConfigWithGateway) - RemoveIPv4IncludedRoute matches by full struct equality, so a mismatched gateway means the entry is silently never found/removed.

func RemoveRouteForServerIP added in v1.8.0

func RemoveRouteForServerIP(serverIP string, interfaceName string) error

removeRouteForServerIP removes an OS-specific route for the server IP

func RemoveRouteForServerIPWithSource added in v1.16.0

func RemoveRouteForServerIPWithSource(serverIP string, interfaceName string, sourceIP string) error

RemoveRouteForServerIPWithSource is RemoveRouteForServerIP with an explicit source/gateway address - must match whatever was passed to AddRouteForServerIPWithSource when the route was added (see RemoveRouteForNetworkConfigWithGateway).

func RemoveRoutes added in v1.8.0

func RemoveRoutes(remoteSubnets []string, interfaceName string) error

removeRoutesForRemoteSubnets removes routes for each subnet in RemoteSubnets. interfaceName must match the interface the routes were added on (see AddRoutes) so that only the routes we own are deleted, never an unrelated local/native route to the same destination on another interface.

func RemoveSecondaryAddress added in v1.16.0

func RemoveSecondaryAddress(interfaceName string, addr string) error

RemoveSecondaryAddress removes an IP address (given as CIDR) previously added with AddSecondaryAddress, including from the shared NetworkSettings used by mobile packet-tunnel providers.

func SetDNSServers added in v1.8.0

func SetDNSServers(servers []string)

SetDNSServers sets the DNS servers

func SetIPv4ExcludedRoutes added in v1.8.0

func SetIPv4ExcludedRoutes(routes []IPv4Route)

func SetIPv4IncludedRoutes added in v1.8.0

func SetIPv4IncludedRoutes(routes []IPv4Route)

SetIPv4IncludedRoutes sets the included IPv4 routes

func SetIPv4Settings added in v1.8.0

func SetIPv4Settings(addresses []string, subnetMasks []string)

SetIPv4Settings sets IPv4 addresses and subnet masks

func SetIPv6ExcludedRoutes added in v1.8.0

func SetIPv6ExcludedRoutes(routes []IPv6Route)

SetIPv6ExcludedRoutes sets the excluded IPv6 routes

func SetIPv6IncludedRoutes added in v1.8.0

func SetIPv6IncludedRoutes(routes []IPv6Route)

SetIPv6IncludedRoutes sets the included IPv6 routes

func SetIPv6Settings added in v1.8.0

func SetIPv6Settings(addresses []string, networkPrefixes []string)

SetIPv6Settings sets IPv6 addresses and network prefixes

func SetMTU added in v1.8.0

func SetMTU(mtu int)

SetMTU sets the MTU value

func SetTunnelRemoteAddress added in v1.8.0

func SetTunnelRemoteAddress(address string)

SetTunnelRemoteAddress sets the tunnel remote address

func WatchRouteChanges added in v1.18.1

func WatchRouteChanges(ctx context.Context, onChange func()) error

WatchRouteChanges calls onChange whenever the host's routing table, interface addresses or link state change - debounced, so one network switch results in one call - until ctx is done. Only events from the OS are watched: changes this process makes itself (e.g. adding bypass routes) also trigger it, so onChange must be idempotent. A no-op where ManagesHostRoutes is false, since there are no host routes to keep up to date there.

func WindowsAddBypassRoute added in v1.18.0

func WindowsAddBypassRoute(destIP string, tunnelInterface string) error

func WindowsAddRoute added in v1.8.0

func WindowsAddRoute(destination string, gateway string, interfaceName string) error

func WindowsRemoveBypassRoute added in v1.18.0

func WindowsRemoveBypassRoute(destIP string) error

func WindowsRemoveRoute added in v1.8.0

func WindowsRemoveRoute(destination string, interfaceName string) error

Types

type IPv4Route added in v1.8.0

type IPv4Route struct {
	DestinationAddress string `json:"destination_address"`
	SubnetMask         string `json:"subnet_mask,omitempty"`
	GatewayAddress     string `json:"gateway_address,omitempty"`
	IsDefault          bool   `json:"is_default,omitempty"`
}

IPv4Route represents an IPv4 route

type IPv6Route added in v1.8.0

type IPv6Route struct {
	DestinationAddress  string `json:"destination_address"`
	NetworkPrefixLength int    `json:"network_prefix_length,omitempty"`
	GatewayAddress      string `json:"gateway_address,omitempty"`
	IsDefault           bool   `json:"is_default,omitempty"`
}

IPv6Route represents an IPv6 route

type NetworkSettings added in v1.8.0

type NetworkSettings struct {
	TunnelRemoteAddress string      `json:"tunnel_remote_address,omitempty"`
	MTU                 *int        `json:"mtu,omitempty"`
	DNSServers          []string    `json:"dns_servers,omitempty"`
	IPv4Addresses       []string    `json:"ipv4_addresses,omitempty"`
	IPv4SubnetMasks     []string    `json:"ipv4_subnet_masks,omitempty"`
	IPv4IncludedRoutes  []IPv4Route `json:"ipv4_included_routes,omitempty"`
	IPv4ExcludedRoutes  []IPv4Route `json:"ipv4_excluded_routes,omitempty"`
	IPv6Addresses       []string    `json:"ipv6_addresses,omitempty"`
	IPv6NetworkPrefixes []string    `json:"ipv6_network_prefixes,omitempty"`
	IPv6IncludedRoutes  []IPv6Route `json:"ipv6_included_routes,omitempty"`
	IPv6ExcludedRoutes  []IPv6Route `json:"ipv6_excluded_routes,omitempty"`
}

NetworkSettings represents the network configuration for the tunnel

func GetSettings added in v1.8.0

func GetSettings() NetworkSettings

Jump to

Keyboard shortcuts

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