OPNsense plugin · os-wg-client-tunnels 3.14

WireGuard Upstream Tunnels

Turns a VPN provider's WireGuard config file into a policy-routed upstream on OPNsense in one dialog, keeps it enforced, and tells you when someone changes a piece of it by hand.

8 pages → 1 dialog
to create a tunnel
~15 steps → 5 clicks
to move a tunnel to a new server
6 safeguards
core has no setting for, kept in force continuously

Why this plugin

Running a VPN provider as an upstream, a gateway that selected LANs are policy-routed through while the firewall itself keeps using its native WANs, is a well-trodden OPNsense setup. It is also one of the most fiddly: each tunnel is eight separate objects on eight core pages, applied in an order core does not enforce. Most of the ways it goes wrong are silent. Traffic keeps flowing, every status page reads green, and it is flowing somewhere you did not intend.

Wrong WAN, silently

A handshake sent before the endpoint route exists leaves by the default WAN, and WireGuard keeps that source address for good.

A tunnel as the default route

When a WAN's gateway goes down, core's election can pick a tunnel as the default, sending the firewall's own traffic into the VPN.

MTU blackholes

On a WAN with a smaller path MTU, large TCP packets vanish and TLS handshakes hang, because the packet-too-big notice goes to the NATed tunnel address.

Un-NATed leaks

A LAN or delegated IPv6 address that reaches a tunnel untranslated is handed to the provider as is.

IPv6 that never comes up

Core adds far-gateway host routes for IPv4 only, so a tunnel's IPv6 gateway has no route to its next hop.

Drift

Someone edits a route, a gateway or an interface MTU by hand, and the tunnel quietly stops matching its design.

The plugin builds every piece in one save, applies it in the order that works, renders the safeguards core lacks at every filter reload, and flags drift as a finding that names the core page that fixes it.

By the numbers

TaskBy hand on the core pagesWith the plugin
Create a tunnelPeer, instance, interface assignment, IPv4 and IPv6 gateways, endpoint route, outbound NAT per LAN and family, measured MTU and matching MSS; about 8 pages and a chain of applies in a specific orderCreate → load the config → name it, pick the WAN and a monitor IP → Save → confirm
Move to a new serverAbout 15 steps on 5 pages, with 3 ordering trapsEdit → Load file → Measure → Save → confirm
Move to another WANEdit the endpoint route, apply, restart the tunnel, check the pf state really movedEdit → pick the WAN → Save
Change NAT sourcesAdd or delete one outbound NAT rule per source and familyEdit → select or deselect sources → Save
Change the MTUMeasure by hand, edit the instance MTU, recompute and set MSSEdit → Measure → Save; the clamp follows by itself
Remove a tunnelFind and delete every object it owns, after checking nothing references themRemove → confirm; refused, changing nothing, while anything still references it

Source and install

Install it from the signed LegoTypes repository: see Install. The plugin is not in the official OPNsense repository. Source: LegoTypes/plugins, net/wg-client-tunnels. The package is os-wg-client-tunnels; its page URL, configd actions and namespace keep the wgclienttunnels name. It targets OPNsense 26.7 with core's built-in WireGuard, and its changelog is in pkg-descr.

Configuration

Everything is on one page under VPN > WireGuard > Upstream tunnels: a settings pane, each switch with core's help (its info icon, or full help) and, for WAN pins and Only NATed traffic into tunnels, links to this page, then the tunnel list. The list is a standard OPNsense grid with one row per managed tunnel: its device and interface, endpoint, bound WAN, MTU and MSS clamp, IPv4 and IPv6 gateways with live status (drawn as on core's gateway page), monitor IPs, outbound NAT sources, gateway groups and findings. Every name links to the core page that owns it, and a gateway link opens that gateway's own edit dialog.

The Upstream tunnels list: four managed tunnels, two on each WAN, with endpoint, bound WAN, MTU and MSS clamp, IPv4 and IPv6 gateways up, monitors, outbound NAT sources, gateway groups and no findings
The tunnel list in service: four tunnels, two bound to each WAN, every IPv4 and IPv6 gateway up and no findings. From a live firewall, with names and addresses replaced by illustrative ones; the monitor IPs are real public resolvers. Select the image for full size.

Create

Paste or load the provider's wg-quick file, the .conf every provider offers for download. Only five values are read from it: PrivateKey and Address from [Interface], PublicKey, PresharedKey and Endpoint from its single [Peer]. DNS, MTU, AllowedIPs, keepalive and hook lines are ignored. The file is read in your browser and sent in the request itself; the private key never reaches a command line, configd or a log.

Give it a name and, optionally, a Peer label: the WireGuard peer's name, for the server the config connects to. Load file fills it from the file's name (without .conf, anything but letters, digits, ., _ and - becoming -, at most 64 characters); left empty, the peer takes the tunnel's name. Then the WAN it should leave by, and a monitor IP (an address nothing else uses; dpinger routes it through the tunnel) and, with IPv6, an IPv6 monitor IP (also an address nothing else uses; the plugin routes it through the tunnel). Pick an IPv6 monitor that answers ping through that tunnel: an address can answer from one exit server and not another, and one that never answers keeps the IPv6 gateway down. Optionally choose a template tunnel, whose gateway thresholds and outbound NAT rules are copied, or pick NAT sources. Create then builds, in one save:

Its apply runs in the order that works: template reload (writes wgN.conf), routes (the endpoint route exists before the first handshake), WireGuard, interface registration, routes again (gateways and dpinger on the new device), filter reload. The MTU is measured unless given: a don't-fragment ping bisection from the bound WAN's own address to the endpoint, minus WireGuard's overhead (60 bytes over IPv4, 80 over IPv6), kept within 1280–1420.

Name it for its use on your firewall, not its endpoint

Providers retire servers, and a slow or blocked exit is fixed by loading another server's config. A tunnel named for the server it started on then forces a choice: keep a name that is now wrong, or rename, which core makes expensive. The name is on the instance, both gateways (NAME and NAME-ipv6), the endpoint route's description (wireguard - NAME) and, without "-" and "_", the interface description; the WireGuard peer takes it too when Peer label is left empty. Core cannot rename a gateway, so a rename means taking both gateways out of every gateway group and rule that uses them, deleting them, adding them again under the new name and putting them back.

Name the tunnel for what it does on your firewall, which a new config does not change: its WAN and its position there. Name the peer for its server with Peer label, in Create and in Edit: Load file fills it from the config file's name, so a server swap renames the peer in the same save. Replacing the config is then Edit with the new file, and no gateway, group or rule needs renaming.

For two WANs with two tunnels on each:

TunnelBound WANGatewaysInterfaceInstead of
vpn-primary-1Primaryvpn-primary-1, vpn-primary-1-ipv6vpnprimary1us-west-12
vpn-primary-2Primaryvpn-primary-2, vpn-primary-2-ipv6vpnprimary2us-west-31
vpn-secondary-1Secondaryvpn-secondary-1, vpn-secondary-1-ipv6vpnsecondary1eu-north-08
vpn-secondary-2Secondaryvpn-secondary-2, vpn-secondary-2-ipv6vpnsecondary2eu-north-23

Illustrative names.

Conventions, by instance number N (device wgN): listen port 51820+N, far gateway 10.2.0.(3+N), IPv6 next hop fd00::N:2, and with unique addressing the tunnel address fd00::N:1/128. Unique addressing exists because providers often hand every key the same IPv6 address and FreeBSD refuses a duplicate address on two interfaces.

A new tunnel carries nothing until a rule sends traffic to it: see After tunnel setup for groups, policy rules, failing closed, kill states and DNS.

Edit and server swap

Edit opens the same dialog, prefilled. The tunnel's identity (name, instance number, device, interface, gateway names) never changes, so gateway groups and rules that name it keep working. What it edits:

Only the differences are written, and only changed values are judged, so an odd but unchanged value never blocks another edit. The apply follows the change: NAT alone reloads the filter without touching routing; a new peer label, with or without NAT, has WireGuard reread this tunnel's file and reloads the filter, with no restart; a monitor change rereads the file too and reconfigures routes; an MTU, WAN, IPv6 or server change runs Create's apply and then restarts the tunnel. The lighter applies touch this tunnel's WireGuard instance only. On a tunnel whose interface MTU overrides a set instance MTU (mtu-override), the applies that only reread WireGuard's file run as the tunnel apply instead: the reread alone would put the instance MTU on the device while the MSS clamp follows the interface's.

If an apply does not complete, the tunnel shows apply-pending and the record remembers which apply it still needs. The row's Apply button runs that apply (Create's own reruns as the tunnel apply, restart included, and an interface MTU override raises the lighter ones to it), and an Edit made meanwhile runs it too when it is the stronger one. Only a complete apply of at least that kind, started against that record, clears it.

Rebind, Adopt, Remove

Rebind repairs a tunnel whose endpoint changed on the core pages so its route no longer matches (unbound): it writes a /32 or /128 to the current endpoint via the chosen WAN, optionally deletes the stale route with its kernel route, and restarts the tunnel.

Adopt brings an existing WireGuard instance under management without changing it. Findings then show what, if anything, differs from what Create would have built.

Remove deletes everything a tunnel owns, but refuses, changing nothing, while any gateway group, rule, port forward, NAT, static route, interface, interface group, bridge, GRE/GIF tunnel, virtual IP or system DNS server setting still references its gateways or interface.

What it enforces

These are rendered by the plugin at every filter reload, derived from the managed tunnels; none is stored as a rule in config, so a restored backup or a changed tunnel never leaves a stale copy behind.

Two firewall rules, and how to write them yourself

The WAN pins and the NAT-only block below are firewall rules that the plugin writes, and a plugin writing firewall rules is unusual. The OPNsense maintainers' guidance for plugins is that a plugin creates no rules of its own and documents the rules its users need. This plugin writes these two because they are derived from each tunnel and must follow it: the WAN pins name every tunnel's endpoint, which changes with each new config, and the plugin rewrites them at the next filter reload. A hand-made copy has to be kept up to date by you.

Both are block rules only: neither passes, redirects nor tags anything, and neither ever lets traffic through that would otherwise be blocked. Each has its own switch under Settings, WAN pins and Only NATed traffic into tunnels. With a switch off, the plugin writes no rule of that kind, and you can write the equivalent yourself on Firewall: Rules, as described under each. Place a hand-made rule above every rule that could pass the same traffic; the plugin puts its own ahead of all user rules.

WAN pins

What it writes. For each WAN that tunnels are bound to, and each IP version: block, quick, logged, outbound, on every interface except that WAN, UDP to the endpoints of the tunnels bound to it. In pf terms, block out log quick on ! <WAN> proto udp to { endpoints }.

Why. The endpoint route alone is not enough: a route to a disabled gateway is skipped, and when a WAN loses its address the kernel drops the route, so the handshake follows the default out of the other WAN. The reply received there sets WireGuard's source address, and core's generated route-to rules then hold the tunnel on the wrong WAN indefinitely. With the wrong WAN blocked no reply can arrive, and the tunnel returns by itself when its WAN does. A tunnel whose bound WAN cannot be resolved is blocked on every interface rather than left unpinned: it fails closed.

By hand. One rule per WAN and IP version: Action Block, Quick, Interface the WAN with Invert interface (rule) checked (an advanced field), Direction out, Version IPv4 or IPv6, Protocol UDP, Destination a host alias holding the endpoints of that WAN's tunnels, Log on. Update the alias whenever a tunnel gets a new config or moves to the other WAN.

Only NATed traffic into tunnels

What it writes. For each tunnel: block, quick, logged, outbound, on the tunnel's interface, IPv4 and IPv6, any protocol, from any source except the tunnel's own address. In pf terms, block out log quick on <tunnel> from ! (<tunnel>), the tunnel's own address.

Why. Outbound NAT runs first, so only traffic translated to the tunnel's own address passes; a LAN or delegated IPv6 source that reaches a tunnel untranslated is dropped instead of being handed to the provider. The source is the tunnel's own address, not the firewall's (self): every tunnel's address belongs to the firewall, so self would let one tunnel's translated traffic out of another, and a provider that learns the client address from traffic would then send that tunnel's replies to the wrong address.

By hand. One rule per tunnel: Action Block, Quick, Interface the tunnel, Direction out, Version any, Protocol any, Source the tunnel's address (for example vpnprimary1 address) with Invert Source checked, Log on. It follows the tunnel's address by itself, so a new config does not make it stale.

What it leaves open. It does not keep a policy rule's traffic off the WANs: a rule that loses its gateway (a lone tunnel gateway that is disabled, or a group whose tier 1 is disabled while the others are down) sends its traffic out by the default route. A VPN-only tag closes that.

The plugin's rules of both kinds are described WireGuard Upstream Tunnels: … and labelled with a stable 32-hex hash so the live firewall log can name them. On Firewall > Rules they appear in the Automatically generated rules group, which the page keeps collapsed until you open it.

If a filter reload cannot build these rules, the firewall keeps enforcing the pins it last put in place, and the tunnel shows render-fallback until a reload succeeds and replaces them. The pins never simply vanish.

Default-route exclusion

Core's default-gateway election returns the first gateway that is not disabled, defunct or forced down (or down, with Gateway switching on), ordered by the Upstream Gateway flag, then priority, then position in config.xml. Priority 255 is the floor, so tunnels can be ordered last but never excluded. When the WANs are forced down, or down with Gateway switching on, a tunnel wins, and the whole network's default route quietly becomes the VPN. It does not blackhole, the provider NATs it, so everything keeps working and every status page reads up, which is exactly what makes it easy to miss. A default installed that way also outlives the tunnel being forced down: the reconfigure never deletes a stale default.

The rule, for both families: a tunnel is never the default. Enforced in two halves:

MTU and the MSS clamp

Providers announce an MSS that assumes a 1420-byte tunnel MTU. On a WAN with a smaller path MTU (mobile links are the usual case) a tunnel sized correctly at, say, 1376 drops the 1420-byte packets hosts send, and the packet-too-big notice goes to the NATed tunnel address, never to the LAN host. TLS handshakes hang.

The plugin clamps TCP MSS on every enabled, assigned tunnel whose MTU is in range (an unbound tunnel and one with a blocking finding included) to its effective MTU, MTU−40 for IPv4 and MTU−60 for IPv6, in both directions, with one match on wgN … scrub (max-mss …) rule per family in a dedicated head anchor. The effective MTU is the instance MTU, or the interface MTU when one is set there (core applies it last, and the tunnel shows mtu-override; every apply that would only reread WireGuard's file then runs as the tunnel apply, so the interface MTU stays on the device). A change made through Edit applies at once; a change made on core's pages is picked up by the config-save reconcile, which reloads just the anchor. Setting an MSS by hand on the tunnel interface is unnecessary and shows as legacy-mss.

Health mirror

Four times a minute, in two passes and one save:

  1. Underlay. Each tunnel's IPv4 gateway is forced down while its bound WAN is disabled, forced down, absent, or reading down, loss or delay+loss: exactly what a gateway group treats as down. The mirror records which gateways it holds, outside the settings where the settings API cannot change the record, and only ever releases those, so a force-down you set by hand is left alone. A restored backup's holds are pruned, not released: a gateway that was held when the backup was taken stays forced down until you untick it.
  2. IPv6. Each tunnel's IPv6 gateway follows its IPv4 tunnel: the mirror forces it down when the tunnel's loss crosses its high threshold (back at the low one), when its monitor is missing, or when the IPv4 gateway is forced down. IPv6 rides inside the IPv4 tunnel, so the native WAN's IPv6 being down does not take tunnel IPv6 down. Each IPv6 gateway also has its own monitor, pinged through the tunnel and judged by core, not by the mirror, so an IPv6 failure inside a tunnel whose IPv4 still works takes only the IPv6 gateway down; the IPv4 and IPv6 groups may then leave by different servers until it recovers.

A settle guard keeps restarts from deciding anything: every routing reconfigure, including any gateway Apply, restarts all monitors, and a monitor that has just started has no samples yet, so it reads 0% or 100% loss, up or down, whatever the path is doing. While a monitor is younger than its gateway's time period its reading changes nothing in either direction and the last decision stands, so a gateway is never released in the middle of an outage and a gateway change elsewhere never takes a healthy WAN's tunnels down. A WAN that is disabled or forced down in configuration still acts at once.

The mirror also replays the gateway alarm it causes. Core's alarm action takes the gateway lock non-blockingly, so an alarm raised while the mirror held it would be dropped and the firewall would keep routing into the tunnel it just forced down. After releasing the lock the mirror waits for gateway status to show what it wrote, then runs the alarm itself.

Core adds no IPv6 far-gateway host routes, so the plugin also keeps each tunnel's IPv6 address and the routes to its IPv6 next hop and its IPv6 monitor in place: at boot, after every routing reconfigure, on a new WAN address, and once a minute.

Settings

The plugin's Settings pane with every switch on and its help shown, including the links to this page under WAN pins and Only NATed traffic into tunnels
The Settings pane with each switch's help open: WAN pins and Only NATed traffic into tunnels link their sections of this page. Select the image for full size.
SwitchWhat it doesNormally
EnableMaster switch. Off stops everything on the page and removes the tunnels' firewall pins and MSS clamp; the tunnels themselves keep running, since they are core configuration.On
Health mirrorHolds tunnels down with their WAN, and IPv6 gateways with their IPv4 health. Off freezes whatever is forced down at that moment.On
IPv6 addresses and routesKeeps each tunnel's IPv6 address, next-hop route and monitor route. Off: IPv6 through the tunnels breaks at the next tunnel restart or reboot.On when any tunnel has IPv6
Default-route guardRemoves a default route whose next hop belongs only to a tunnel or other non-default gateway, both families.On if the router uses one or more WANs as route defaults
WAN pinsBlocks UDP to each tunnel's endpoint on every interface but its bound WAN, so a handshake never leaves by another one.On
Only NATed traffic into tunnelsBlocks packets entering a tunnel from any address but that tunnel's own, i.e. traffic outbound NAT did not translate to it.On
MSS clampClamps TCP MSS to each tunnel's MTU, both directions.On

Findings

Each tunnel is re-derived from core configuration on every view, and anything that does not match the design becomes a finding in its row, with a tooltip naming the page that fixes it. A blocking finding takes the tunnel out of the health mirror and the route upkeep, and refuses edits, until it is resolved there. Its WAN pins, inner-source block and MSS clamp stay in place.

FindingMeaning and fix
instance-missing blockingThe managed WireGuard instance was deleted. Remove drops it from the managed list.
not-assigned blockingThe wgN device has no interface assignment. Interfaces > Assignments.
interface-disabled blockingThe tunnel's interface is disabled; core renders no rules on it. Enable it.
not-single-peer blockingThe instance needs exactly one peer.
endpoint-unsupported blockingThe endpoint is a hostname or not a global IP address; a swap to an IPv4 or global IPv6 endpoint resolves it.
ambiguous-gateway blockingMore than one gateway per family on the tunnel interface.
unboundNo /32 or /128 route to the endpoint, so no WAN to pin it to. Rebind.
stale-routeA route still points at a previous endpoint. Rebind offers to delete it with its kernel route.
wan-unavailableThe bound WAN is disabled or gone; the tunnel is blocked on every interface until it returns.
ipv6-incompleteAn IPv6 tunnel address without an IPv6 gateway, or the reverse.
mtu-overrideThe interface sets its own MTU, which wins over the instance MTU. While it is set, an Edit or Apply that would only reread WireGuard's file restarts the tunnel instead.
mtu-too-smallThe MTU is too small to clamp TCP MSS; at least 1280.
legacy-mssAn MSS is set by hand on the tunnel interface; the plugin's clamp replaces it.
nat-missingNo outbound NAT on the tunnel interface for a family, so the inner-source block drops everything a LAN sends into it.
monitor-sharedThe monitor IP is also used by something else.
ipv6-unmonitoredThe IPv6 gateway has no monitor of its own, so an IPv6-only failure inside the tunnel goes unseen. Edit: set an IPv6 monitor.
ipv6-monitor-configThe IPv6 monitor is set up in a way that can misread: core may route it, its thresholds are tighter than the IPv4 gateway's, or the plugin's IPv6 routes are switched off. Saving the monitor again in Edit repairs the first two.
sentinel-missingThe default-route exclusion's sentinel gateways are missing. Check default-route exclusion creates them.
render-failedThe last filter reload could not build the plugin's rules, and there are no earlier pins to keep; they are missing until the next reload succeeds. The reason is in VPN > WireGuard > Log File.
render-fallbackThe last filter reload could not build the plugin's rules, so the firewall keeps the pins it last put in place; the next reload that succeeds replaces them. The reason is in VPN > WireGuard > Log File.
apply-pendingA Create or Edit saved but its apply did not complete. The row's Apply runs what is still needed.
core-value-invalidA setting the tunnel depends on holds a value core would not accept (a restored or hand-edited configuration). The plugin ignores the value until it is corrected or deleted on its core page.
core-contractA core update changed a core internal the plugin copies (the gateway lock and routing alarm, the sentinels' gateway election, the gateway watcher's reload, the peer-name rule and others), so the part of the plugin that copies it may not match core. VPN > WireGuard > Log File names which. Install a plugin update that matches this core.

Design principles

Core traps it works around

Each of these was found the hard way on a live firewall.

Command line

Everything the page does is also available on the firewall as tunnel.php; write actions take --dry, and requests that carry a key are JSON on stdin so the key never reaches the process list.

T=/usr/local/opnsense/scripts/OPNsense/WGClientTunnels/tunnel.php
php $T list                                   # managed tunnels, then unmanaged instances
php $T status                                 # findings only
php $T measure-mtu WAN_B 198.51.100.10         # path MTU for a WAN and endpoint

# create: JSON on stdin (the config text carries the private key)
jq -n --rawfile c provider.conf \
  '{config: $c, name: "vpn-a", peer_label: "us-west-12", wan: "WAN_B", monitor: "192.0.2.53", monitor6: "2001:db8::53", template: "vpn-b"}' \
  | php $T --dry create                       # then without --dry; with no IPv6 Address in the file, leave out monitor6

# edit: the uuid and only what changes
echo '{"uuid": "<uuid>", "mtu": 1376}' | php $T --dry edit
echo '{"uuid": "<uuid>", "peer_label": "us-west-31"}' | php $T --dry edit   # rename the peer: the peer apply
jq -n --rawfile c new-server.conf '{uuid: "<uuid>", config: $c}' | php $T edit

php $T --dry rebind <uuid> WAN_B [<stale route uuid>]
php $T --dry adopt <uuid>
php $T --dry remove <uuid>
php $T apply <uuid>                            # the apply a pending change still needs, else the tunnel apply
php $T apply <uuid> peer                       # one apply by name: filter, peer, routes, first or tunnel
php $T --dry ensure-sentinel                  # check the default-route exclusion
php $T --selftest                             # decision-logic tests, no config access

Limits