Skip to content

wireguard ​

The wireguard endpoint (the endpoints section, as in sing-box 1.11+): its own WireGuard interface, which routes see as an outbound named after the endpoint, while connections opened by peers arrive in routing as if from an inbound with the same name.

Crateours-mod-wireguard, modules/protocols/wireguard
Binary featurewireguard (in default)
Crate featuresawg (→ ours-wireguard/awg), ciphers (→ ours-wireguard/ciphers); both in default

requires ​

dial: the endpoint's dial block — the socket to the peers (interface, fwmark, detour). In kernel mode the peers' connections are captured by nftables tproxy and accepted by ours_relay::tproxy::{accept, receive}, which the tproxy inbound uses too; the tproxy module itself is not needed.

provides ​

  • Provide::Endpoint { key: "wireguard" } — the factory returns an ours_api::Endpoint: both sides are one WireGuard object (Inbound and outbound).
  • Provide::Blocks { section: "endpoints", key: "wireguard", blocks: ["dial"] }.
  • Provide::Schema { name: "endpoints.wireguard" }.

Dependencies ​

ours-wireguard (the protocol without I/O), ours-tun-sys (TUN ioctls), ours-net-info (link: creating the interface, addresses, routes, bringing it up over rtnetlink; genl/wireguard: configuring the kernel module; nft, policy: capture in kernel mode), ours-net-sys, ours-relay (UdpNat, tproxy: accept/receive of tproxy sockets), ours-bufpool, ours-api, ours-codec, ours-json.

Modes ​

mode (an ours extension): userspace (the default), kernel, auto. The configuration is the same for all of them.

  • userspace — our own implementation on TUN (below).
  • kernel — the kernel module's interface (src/kernel.rs, below). Only the official modules: wireguard (Linux, kmod-wireguard) for plain WireGuard and amneziawg (amnezia-vpn/amneziawg-linux-kernel-module, kmod-amneziawg in OpenWrt) for AWG, or for plain WireGuard when there is no wireguard. Neither wg nor awg is needed.
  • auto — kernel if the needed module is present and the configuration does not require what the modules lack; otherwise userspace. The choice and the reason are logged (mode auto: kernel, module wireguard or mode auto: userspace, <reason>).

The module is looked up by its generic netlink family (wireguard/amneziawg); a query for a missing family itself makes the kernel load the module, and if that did not work — a trial ip link add of its kind (which also loads the module) and a repeated query. This is done while the configuration is built, so the errors are configuration errors.

kernel configuration errors (for auto — the reasons to choose userspace):

  • ciphers is set and is not exactly [chacha20-poly1305] — the modules know only ChaCha20-Poly1305 (the AES-GCM kernel module of the amneziawg fork is not supported);
  • an awg block with non-zero parameters (or a peer's keepalive range) without the amneziawg module;
  • what the amneziawg 3.1.20261113 module lacks and amneziawg-go has: the tags <d>, <ds>, <dz> and <b> without 0x in i1–i5, an argument for <t>/<c>, timers, content_padding_addition and a keepalive larger than 65535 (the module has 16 bits);
  • a peer's reserved is not zeros — the modules do not write the reserved bytes;
  • dial.interface — the module's socket cannot be bound to an interface (dial.fwmark is passed to the module as fwmark);
  • dial.detour — the kernel modules send from a socket of their own.

Without ciphers the module fits: it does not negotiate, and peers, as with vanilla WireGuard, end up with ChaCha20-Poly1305.

config_file (src/conf.rs) ​

The file is read in decode, not in build: the endpoint's options (and their fingerprint in the reload plan) are already merged with the file, so a changed file rebuilds the endpoint on an ordinary reload. Warnings (skipped keys, fields the file also set) are kept in warnings (#[config(skip)]) and logged at build time. Errors are <file>:<line>: …; errors of the awg block (awg.h2: …) refer to the line of their key. append_peer/remove_peer change only the peer's section (the comments above a section belong to it), the rest of the text is kept byte for byte; writing is done by the clients module.

listen (src/listen.rs) ​

The socket to the peers listens on all addresses (with the kernel module it cannot be otherwise, and in userspace there is one dual-stack socket per shard, and the data path does not know which address to reply from), so listen is a filter: the table inet ours-wg-listen-<interface>, the chain input (the input hook, priority 0): not UDP or a different port — return, iifname/ip daddr/ip6 daddr of an allowed one — return, the rest — drop. It is installed by the first shard once the port is known (in kernel mode without listen_port the port is read from the module). resolve is a pure function of Listen and the WAN from net-info::wan; for auto a task waits on wan::Monitor, rereads the WAN 300 ms after a burst of messages and rewrites the table if the set of addresses has changed. Reload builds the new endpoint before closing the old one: the table is owned by the last one (OWNERS, a generation per interface name), and the old one does not touch it when closing.

Design (userspace) ​

Like wireguard-go: a TUN device and the kernel's TCP/IP stack, not our own stack.

  • src/tun.rs — the device IFF_TUN | IFF_NO_PI | IFF_VNET_HDR | IFF_MULTI_QUEUE, one queue per shard. Offloads: TUN_F_CSUM | TSO4 | TSO6 | TSO_ECN | USO4 | USO6 (without USO if the kernel is older than 6.2). Addresses from address, the MTU, bringing it up and routes to the peers' allowed_ips with the metric 0x7fff0000 — below any system routes, so that replies through the tunnel are not cut by a loose rp_filter and an IPv6 socket bound to the device finds a route; the device's own rp_filter is 0. The name is name or wg-<tag>.
  • src/io.rs — a shard's data path:
    • reading the TUN queue: the kernel's super-packet (up to 64 KiB, TSO/USO) is cut into segments with ready checksums (offload::split) right into the send buffer at an offset leaving room for the WireGuard header, the segments are sealed in place (ring ChaCha20-Poly1305) with consecutively taken counters and leave in one sendmsg with UDP_SEGMENT (GSO, up to 64 segments and ~64 KiB);
    • receiving UDP with UDP_GRO: a batch of datagrams from one source, each opened in place; the TCP segments of one flow are merged back into a super-packet (offload::Coalescer) and written to TUN in one writev (the virtio header + the head + pieces of the payload, without copying); the checksum is NEEDS_CSUM with a pseudo-header: the stack does not check it again, AEAD has already checked the packet;
    • there are no per-packet allocations: the shard's read/send buffers live as long as the task.
  • The socket to the peers — one per shard, SO_REUSEPORT on one port (listen_port or the one chosen by the kernel for the first shard), dual-stack [::]; TUN spreads flows across queues by the flow hash, so encryption of one direction goes on all shards.
  • Receiving: all datagrams of one peer arrive at one socket (one 4-tuple), so with several shards the socket only reads batches (receive_into), while all shards open them (Pipeline, open_from): a batch gets a number when received, and opened batches are written to TUN strictly in order of their numbers — the flow is not reordered. No more than 2 × shards + 2 batches are in flight (the 64 KiB buffers are reused). With one shard a batch is opened where it was received.
  • src/detour.rs — dial.detour: each peer gets a loopback socket that relays its datagrams through the detour's packet connection.
  • Timers (timers) — a task of the first shard, 10 times a second: handshake retries, keepalive, persistent keepalive, rekey by time and message count, zeroing keys, computing "under load" (more than 64 handshakes a second — a cookie reply).

Outbound ​

connect_stream/connect_packet — a Dialer from the dial factory with bind_interface = the device and inet4_bind_address/inet6_bind_address = the endpoint's first addresses: an ordinary kernel socket, SO_BINDTODEVICE. Domains are resolved by the configuration's DNS. The stream is a Stream::Tcp, so the relay can pump it with splice. The host policy is kept separate: the host's network strategy must not replace the device.

Inbound (src/nat.rs) ​

What peers open to foreign addresses enters routing the way sing-tun's system stack does it: a peer's TCP/UDP packet to an address that does not belong to the endpoint is rewritten to the endpoint's listener (the family's first address, the listener's port), and the source port — to a port from the NAT table; the listener (accept/receive in lib.rs, sockets with SO_BINDTODEVICE) finds the original addresses by the source port and hands the stream to the dispatcher with Metadata (type wireguard, the endpoint's tag). The listener's replies on the way to TUN are rewritten back (Nat::outbound). Checksums — incrementally (RFC 1624). Neither nftables nor policy routing is needed. Packets to the endpoint's own addresses go as they are (replies to its own outbound connections and direct requests to the endpoint); other protocols (ICMP) to foreign addresses are dropped. Table entries live as in sing-tun's system stack: udp_timeout without packets, and TCP after an RST or a FIN from both sides — another 10 s. UDP flows are spread by UdpNat (udp_mapping/udp_filtering/udp_nat_max); a reply leaves from the address the peer sent to. A datagram larger than the MTU comes in pieces, and only the first carries the ports: its rewrite is kept by the datagram's identification, protocol and ends for 30 s (as the kernel's ipfrag_time), and the later pieces, IPv4 or IPv6, take the same addresses; a later piece that comes before its first is dropped.

Design (kernel, src/kernel.rs) ​

  • The interface: ip link add <name> type wireguard|amneziawg over rtnetlink, WG_CMD_SET_DEVICE (the key, listen_port, fwmark from dial, peers with REPLACE_PEERS, the AWG parameters), addresses, the MTU, bringing it up and routes to allowed_ips with the metric 0x7fff0000 — as in userspace; the interface's rp_filter is 0. An interface of the same name left by a crashed process (of the kind wireguard/amneziawg) is recreated; an interface of a different kind with this name is an error.

  • Outbound — the same Dialer as in userspace: a kernel socket with SO_BINDTODEVICE on the interface and the endpoint's address.

  • Inbound. The rewriting of nat.rs lives in the userspace packet path, which the kernel module does not have, so what peers open to foreign addresses is taken by nftables tproxy:

    table inet ours-wg-<name> {
      chain prerouting {
        type filter hook prerouting priority mangle;
        iifname != "<name>" return
        fib daddr type local return
        meta nfproto ipv4 meta l4proto tcp meta mark set mark | 0x04000000 tproxy to :<TCP port>
        ... udp, and the same for ipv6
      }
    }
    ip rule add iif <name> fwmark 0x04000000/0x04000000 lookup 0x7767 priority 103   (and -6)
    ip route add local default dev lo table 0x7767                                   (and -6)

    The listeners are tproxy sockets (IP_TRANSPARENT, SO_BINDTODEVICE) on the endpoint's first address of each family, one per shard (SO_REUSEPORT, the kernel chooses the port for the first one); what is accepted is handed to ours_relay::tproxy::{accept, receive} with the type wireguard: TCP — with the original destination address in the socket's local address, UDP — from IP_ORIGDSTADDR, and UDP replies leave from a socket bound to the original destination address. Without IPv6 on lo the kernel does not accept the IPv6 local route, and IPv6 is not captured.

  • A difference from userspace: the peers' connections to the host's own addresses (any interface, not only the endpoint) reach the host as they are, bypassing routing: a reply to them would have to be sent from a port held by a host service. Other protocols (ICMP) to foreign addresses go through the kernel's ordinary routing (forwarding, if enabled), instead of being dropped.

  • Reload. The rebuilt endpoint starts while the old one is still running, so the interfaces live in the process's table (name → generation, holders): the new endpoint takes over the running interface and changes only the difference — SET_DEVICE without REPLACE_PEERS, all its peers with REPLACE_ALLOWEDIPS (psk and keepalive explicitly, zeros to remove), vanished ones with REMOVE_ME; addresses and routes — by difference. The sessions of the remaining peers survive (enabling keepalive — that is the kernel itself — sends a keepalive and may start a handshake). The new endpoint writes the nftables table anew (its own ports), and the old one only releases the interface when closing. A change of module (wireguard ↔ amneziawg) recreates the interface. The last holder, when closing, removes the interface, the table and its ip rules; the local routes of table 0x7767 — when the process has no interfaces left.

What changes on the host in kernel mode ​

The interface, its routes, the nftables table and the rules shown above. The mark bit 0x04000000 and the table 0x7767 (30567) are constants (kernel::MARK, ROUTE_TABLE, RULE_PRIORITY): the bit is above the default auto_nft mask (0x3000000). All of this is removed on stop; after kill -9 what remains is the interface (recreated on the next start), the table and the rules. The kernel encrypts (kworkers on all CPUs), and its CPU is not counted in the process's CPU.

Extension points (awg, ciphers) ​

Both are Cargo features of the crate (awg, ciphers, in default; in the binary — wireguard-awg, wireguard-ciphers, also in default), and they enable the features of the same name in ours-wireguard. Without awg, an awg block with non-zero fields and a persistent_keepalive_interval range are a configuration error (awg: this build has no AmneziaWG (cargo feature awg); the parsing is src/plain.rs instead of src/awg.rs). Without ciphers only an empty ciphers or [chacha20-poly1305] is accepted, otherwise an error (ciphers: this build negotiates no transport cipher ...). Silently falling back to plain WireGuard is not allowed: a peer with AWG would not see a single packet it understands.

See ours-wireguard for the Wire and Negotiation extension points.

Cipher negotiation (ciphers) ​

The scheme is the AES-GCM extension of the amneziawg-go fork (janeblower/amneziawg-go), byte for byte; see ours-wireguard. The module (src/lib.rs parse_ciphers) parses the list (names case- and space-insensitive, as in the fork), without it takes Ciphers::default_for(aes_accelerated()) ([chacha20-poly1305, aes-gcm-256] with AES instructions, otherwise [chacha20-poly1305]) and warns in the log if an explicit list has AES but there are no instructions. Handled::derived carries the chosen AEAD, and io.rs logs it (debug).

AmneziaWG in userspace ​

src/awg.rs parses the awg block into awg::Params (the wire), device::Timings (timers) and the module's parameters; the checks are as in amneziawg-go (the H ranges do not overlap, jmin ≤ jmax, S ≥ 12 with header protection). Without awg the device gets Plain, and the data path does no extra per-packet work.

With awg the data path stays batched and allocation-free; batches with unequal lengths leave as runs of UDP GSO. Details: ours-wireguard.

reserved ​

A sing-box peer's reserved — three bytes written into the reserved bytes of every sent message after the MAC; when receiving plain WireGuard these bytes are zeroed before checking MAC1.

Limitations ​

  • workers, on_demand, system are read and have no effect.
  • Userspace: a reload that changes the endpoint rebuilds it: sessions are lost, a new handshake (kernel mode changes peers in place, see above).
  • Replies of a UDP flow opened by a peer always come to the peer from the original destination address.
  • ICMP from peers to foreign addresses (ping through the tunnel) is dropped: the NAT rewrites only TCP and UDP to the endpoint's listener. Forwarding echo would require an ICMP socket of its own on the outgoing side and routing of non-flows; a ping of the endpoint's own addresses is answered by the kernel.

Tests ​

  • Unit tests: src/conf.rs (wg/awg/Ciphers keys, warnings, file:line, appending and removing a peer while keeping the text), src/lib.rs (decode rereads the file), src/listen.rs (parsing, choosing addresses from WAN snapshots before and after a change, the table's rules); src/nat.rs (rewriting there and back, checksums, expiry); src/kernel.rs (the peer difference on reload, the awg parameters, the capture table); src/lib.rs (what prevents the module, kernel — an error, auto — userspace, parsing ciphers and the default).
  • Interop: tests/e2e/netns/wireguard.sh — ours against kernel WireGuard, wireguard-go, sing-box and ours in userspace (both directions, TCP and UDP, a handshake after a peer restart, with OURS_WG_REKEY=1 — rekey by time), without root. OURS_WG_MODE=kernel|auto — the same in kernel/auto mode, plus reload (the same interface, the session alive, a peer added/removed, keepalive set/removed) and an empty host after stopping. OURS_WG_AWG=v1|v2|v3 — the AWG 1.x, 2.0 and 3.1 sets (header protection, padding, trailers, timers, the keepalive range) on both sides, an amneziawg-go peer (AMNEZIAWG_GO, configured over UAPI) and an ours peer in OURS_WG_PEER_MODE (kernel on the amneziawg module by default); additionally ours is restarted and starts the handshake itself, and tcpdump checks that there is not a single plain WireGuard message on the wire.
  • Unit tests of ours-wireguard's awg.rs: datagrams assembled by amneziawg-go (header protection, all four kinds), parsing tags, checks, the padding window.
  • Unit tests of ours-wireguard's ciphers.rs: the vectors of a Go harness over the fork (ciphers/vectors.rs): handshakes with different lists are reproduced byte for byte (the initiation, the response with the index), the fork's transport is opened with our keys; the decoding table of all 12-bit tags and the choice for all pairs of lists match by hash; flipping an index bit breaks the handshake.
  • OURS_WG_CIPHERS / OURS_WG_PEER_CIPHERS / OURS_WG_CIPHER in wireguard.sh: the cipher lists of ours and the peer (amneziawg-go — a build of the fork, ours) and the expected cipher (A, A/B depending on who started the handshake, or none); the ours log, the fork's cipher= over UAPI and the ours peer's log are checked.
  • OURS_WG_V6=1 in wireguard.sh: the tunnel has IPv6 addresses next to IPv4, TCP and UDP over IPv6 inside the tunnel in both directions (the peers talk to each other over IPv4).
  • Benchmarks: see benchmarks.

GPL-3.0-or-later