Commit graph

1056 commits

Author SHA1 Message Date
Leadaxe
37bc7b9f55 test(awg): pin IpcGet introspection parity for all 16 obfuscation params
i1..i5 are emitted by an `i%d=` loop rather than literal per-key sendf calls,
which made a grep-based audit conclude they were missing from the get path.
Live IpcSet -> IpcGet round-trip proves all 16 are reported; unset I-slots
(i2/i4) stay absent. See SPECS/TASKS/031-AWG_PARITY_AUDIT_ADVANCED_SECURITY.
2026-08-05 16:55:41 +03:00
Leadaxe
9a23f36748 lx: re-graft egress-provider API onto AWG2 base (upstream 6f5e8b1947)
Upstream wireguard-go added an EgressProvider hook to StdNetBind (egress
anchoring for TUN auto-redirect): EgressProvider interface, egressProvider
field, SetEgressProvider, plus egress branches in Open/Send/Close and a
standardEndpoint cast hoist in Send. sing-box's endpoint-listen refactor
now calls StdNetBind.SetEgressProvider, so our AWG2 fork (which was one
wireguard-go revision behind) failed to build.

Applied the upstream delta to conn/bind_std.go verbatim, then re-applied
SPEC 026: gate BOTH reserved-clear sites behind hasReserved() —

  - main receiveIP path (msg.N > 3 && s.hasReserved())    [existing]
  - NEW egress receive path (dataLength > 3 && s.hasReserved())

Upstream's egress hook re-introduced an UNCONDITIONAL common.ClearArray(
bufs[0][1:4]) — the exact anti-pattern SPEC 026 fixed. Gating it keeps a
small-padding AmneziaWG magic (bytes 1-3) intact when no WARP reserved
value is set, and STILL fires for WARP-over-egress: the egress bind is
only created on the isUDPListener path, where SetReservedForEndpoint is
called for every peer, so hasReserved() is true in that scenario. Verified:
WARP egress unaffected, AWG magic survives, conn tests green.

reservedForEndpoint is populated before receive goroutines start and never
mutated after (same lock-free invariant SPEC 026 already relies on).
2026-08-05 16:55:31 +03:00
Leadaxe
1e787bb3e0 lx: gate reserved-byte clear on receive so AmneziaWG magic survives
The Cloudflare "reserved" bytes (1-3) were zeroed unconditionally on
every received datagram across all StdNetBind/WinRingBind receive paths.
AmneziaWG reads its magic header as LittleEndian.Uint32(packet[padding:])
where padding is s1/s2/s4; with small padding (0-3) the magic overlaps
bytes 1-3, so clearing them collapses it out of the ranged h1-h4 window
and every packet is dropped (handshake included) — the AWG endpoint
never comes up. Plain WG (types 1-4, bytes 1-3 already zero) and large
padding are unaffected, which is why it went unnoticed.

Gate all five receive clears (bind_std receiveIP, msgx_darwin
receiveSingle + makeReceiveMsgX, bind_windows receiveIPv4/v6) behind a
new hasReserved() so bytes 1-3 are only touched when a WARP reserved
value is actually configured. Send paths already gate on a per-endpoint
loaded/non-zero check, so they are left unchanged. The reserved map is
populated before the receive goroutines start and never mutated after,
so the lock-free read is safe.

Tests: awg_stdnetbind_reserved_lx_test.go brings up two Devices over
StdNetBind with zero padding (magic in bytes 0-3) and asserts delivery
(red before the fix, green after); reserved_gate_lx_test.go pins the
hasReserved() gate.
2026-08-05 16:55:02 +03:00
Leadaxe
ee7ff1b77f lx: fix transport padding buffer overrun + harden AWG config guards
Transport padding (s4) crashed the whole process with
"index out of range" in RoutineSequentialSender on the first data
packet: InputPacket/InputPackets sized elem.buffer without headroom
for the in-buffer right-shift that prepends the random prefix.

- send.go: reserve paddings.transport in both injection-path
  allocLength computations; replace the manual backward byte loop
  with an overlap-safe copy; defensively grow the buffer (pool-backed)
  if it still lacks headroom, dropping packets that cannot fit a
  single WG message instead of overrunning.
- receive.go: drop the rxBytes/timers block duplicated by the AWG
  re-graft (rx accounting was doubled, keepKeyFreshReceiving fired
  twice per batch).
- send.go: swap jmin/jmax when configured inverted (UAPI validates
  the fields only individually; a swapped pair panicked rand.Int
  with a non-positive bound on the first handshake).
- obf*.go: bound obfuscator length args to [0, MaxMessageSize]
  (negative panicked slice bounds, huge ones OOMed the handshake).
- magic-header.go: widen to int64 before end-start+1 so a full-range
  header cannot wrap to a zero rand.Int bound.

Tests: transport_padding_test.go reproduces the on-device crash
byte-for-byte (red on the previous commit, green now) across both
injection paths and the tun path; obf_guards_test.go pins the
config-value guards.
2026-08-05 16:55:02 +03:00
Leadaxe
831d483366 lx: re-graft AmneziaWG 2.0 obfuscation onto sagernet/wireguard-go v0.0.5
Rebase of the AWG obf graft (was e5feca7 on v0.0.3) onto v0.0.5
(2c27bbf4f9, 'Add L3 forwarding support'). 15 of 16 graft files
applied clean via 3-way; only send.go conflicted, on a single line
(upstream queuedOutboundPackets backpressure decrement vs a graft
blank line — took upstream).

Key invariant preserved: MessageEncapsulatingTransportSize=0 (graft
zeroes the sagernet encapsulating headroom; AWG obfuscation composes
the prefix itself via SendBuffers, not Bind.Send prepend). Upstream's
InputPacket/InputPackets and the new size-based outbound buffer pool
(GetOutboundBuffer/PutOutboundBuffer) are taken verbatim; the graft's
RoutineEncryption (header at buffer start) and transport-padding shift
in RoutineSequentialSender re-woven around them.

Builds clean on linux/android/windows/darwin (device/conn/tun).
2026-08-05 16:53:12 +03:00
世界
f39689ad35
Fix input packets peer lookup
InputPacket/InputPackets used the deprecated trie-only AllowedIPs.Lookup. With tailscale v1.102 a PeerByIPPacketFunc is installed and the trie is no longer populated, so every injected packet was unmatched. Use LookupFromPacket, and size the sequential sender scratch for full input batches instead of capping containers at the device batch size.
2026-08-05 12:29:41 +08:00
世界
da8671622b
Fix InputPackets exceeding device batch size 2026-08-05 10:47:57 +08:00
Jordan Whited
7a66fbee4a
device: add priority message transmission around session establishment
Add SetPriorityMessageOnEstablishmentFunc, which registers a
PeerPriorityMessageFunc callback invoked when a peer's session keypair
is established or re-keyed for forward data transmission. The bytes it
returns are transmitted to the peer as a transport message.

The message is "priority" in two senses: it bypasses the staged packet
queue entirely, so it cannot be evicted by TUN-sourced packets, and it
is enqueued ahead of the keepalive/staged packets that follow keypair
establishment.

Updates tailscale/tailscale#20081

Signed-off-by: Jordan Whited <jordan@tailscale.com>
2026-08-04 19:18:01 +08:00
Alex Valiushko
15b912c1c0
device: fix TOCTOU race during session state update (#77)
API introduced in a927a66e has two cases of state determination
happening out of critical section for the state value:

(1) expiredSession loads sessionExpiresNano, then releases all locks
and calls noteSessionState(Expired). So a concurrent refresh that
lands in that gap gets clobbered by a stale Expired -- and sticks
until the next re-key.

(2) Likewise in noteSessionHandshakeStopped, hasKeyMaterial check
happens out of the session state lock and races with ZeroAndFlushAll.

Both lead to a wrong state emitted via the device.sessionState.fn,
but are otherwise benign.

This moves the expiry timestamp under a lock to address the former,
and provides a noteSessionStateLocked helper for the latter.
Also changes API semantics to serialize events per-peer, to avoid
sharing a single lock for all timestamps.

Updates tailscale/corp#42874

Signed-off-by: Alex Valiushko <alexvaliushko@tailscale.com>
Change-Id: Iee2cdf135375519e58a8e84362349d966a6a6964
2026-08-04 19:18:01 +08:00
Alex Valiushko
35a60acb84
device: set peer to expire unconditionally (#73)
e3ac4a0afb4e introduced a lightweight API that can be used instead of UAPI
to reconfigure peers. Peer state created via the new PeerLookupFunc
is not set to expire until the handshake succeeds, making device leak two
goroutines and a set of buffers for each failed handshake.

This change arms the expiry timer before the handshake gets to proceed.

Updates tailscale/tailscale#20183

Change-Id: Ibc0abb6eec97aca0a10f50515dea9e0d6a6a6964
Signed-off-by: Alex Valiushko <alexvaliushko@tailscale.com>
2026-08-04 19:18:01 +08:00
Simon Law
cd7ac13b86
device: convert runtime.SetFinalizer to AddCleanup (#71)
In PR #66, we tried to address a memory leak by avoiding
runtime.SetFinalizer for autodrainingInboundQueue and
autodrainingOutboundQueue unless there was something to do.

However, when there is work to be done, these finalizers still leak
memory because they’re still holding on to a cyclical reference to q.
This applies to any platform that relies on a bounded device.WaitPool,
like Android and iOS which both declare PreallocatedBuffersPerPool.

This patch converts this logic to runtime.AddCleanup which is designed
to avoid this problem.

Updates tailscale/corp#42776

Signed-off-by: Simon Law <sfllaw@tailscale.com>
2026-08-04 19:18:01 +08:00
Brad Fitzpatrick
2ad9837e6c
device: refactor container locking for lock-order clarity
Device-side portion of upstream tailscale/wireguard-go e3ac4a0
(device, cmd/check-lockorder: add static analysis tool for lock
ordering); the analyzer itself is not carried in this fork.
2026-08-04 19:18:01 +08:00
Brad Fitzpatrick
7c3a736cbe
device: add peer session state callback
Add a minimal callback API for observing WireGuard peer session state
changes.

Updates tailscale/corp#42874
2026-08-04 19:18:01 +08:00
Brad Fitzpatrick
09268b375c
device: avoid cycle-leaky runtime.SetFinalizer when unnecessary
In tailscale/wireguard-go#65, @lkosewsk reproduced a memory leak seen
in prod with lots of wireguard-go instances being created and
destroyed, where they were still being retained forever due to cycles
in the runtime.SetFinalizer reference graph.

Really we shouldn't be using runtime.SetFinalizer anywhere. But we
still use it on mobile platforms in WaitPool. But those platforms
don't have thousands of tsnet.Server instances coming & going, so this
is a half fix: avoid the finalizer registration on Linux, etc where
the queue doesn't need to be drained and there's no WaitPool
accounting. Just let GC handle it, without adding finalizer cycle
complexity.

Updates tailscale/corp#42776

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2026-08-04 19:18:01 +08:00
Brad Fitzpatrick
010dd5c6f2
device: fix some lock ordering violations, add a test for a deadlock we hit
Discovered by a tool + test that will come in a future change.

Updates tailscale/tailscale#19513

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2026-08-04 19:18:01 +08:00
Brad Fitzpatrick
f69b24781e
device: further add, revise API for on-demand configuration of peers
Updates tailscale/tailscale#17858
Updates tailscale/corp#35603

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2026-08-04 19:18:01 +08:00
Brad Fitzpatrick
e924a91e99
device: add API for on-demand configuration of peers
Updates tailscale/tailscale#17858

Signed-off-by: Brad Fitzpatrick <brad@danga.com>
2026-08-04 19:06:30 +08:00
Brad Fitzpatrick
70b09a6edd
device: put AllowedIPs mutex before what it guards, unexport fields
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2026-08-04 19:04:35 +08:00
世界
6f5e8b1947
Add EgressProvider 2026-07-17 10:48:47 +08:00
世界
2c27bbf4f9
FIx batched InputPackets 2026-07-06 23:38:56 +08:00
世界
57baac9504
Add batched UDP I/O on Darwin via sendmsg_x/recvmsg_x
On a connected socket sendmsg_x sends a whole batch in one syscall;
msg_name is unsupported there, so batched sends require connecting to
the peer, which loses roaming and is therefore opt-in via
SetSinglePeerMode for single fixed-peer binds. recvmsg_x fills in
per-message source addresses, so batched receive works on unconnected
sockets too. Any unexpected errno permanently falls back to the generic
paths. iOS is excluded: in the Network Extension recvmsg_x on
unconnected UDP sockets delivers no data, and connected sockets stop
passing traffic after a rebind.
2026-07-06 21:06:55 +08:00
世界
fcbb7c473b
Coalesce UDP GSO segments as iovecs
coalesceMessages copied every additional datagram into the spare
capacity of the first buffer, which no longer exists now that element
buffers are sized to their packet; append the datagrams as iovecs
instead, which also removes the copy.
2026-07-06 21:06:45 +08:00
世界
8403cdb937
Rework outbound buffer management
Outbound element buffers now come from the sing allocator sized to the
actual packet instead of the bounded MaxMessageSize pool, element and
container pools become plain sync.Pools, and the bounded message buffer
pool serves only the receive path. Packets injected via
InputPacket/InputPackets are dropped before they are copied once a peer
has 2048 packets queued: injection runs on the caller's read loop, which
must never block on pool exhaustion, and the queues are bounded in
containers, so a flood was buffered instead of dropped.
2026-07-06 21:05:53 +08:00
世界
9de6dc32df
Add batched InputPackets 2026-07-06 14:17:42 +08:00
世界
19b0d35877
Fix reserved bytes offset in StdNetBind.Send 2026-05-17 20:36:46 +08:00
世界
fa73d0f1ae
Fix input packet 2026-05-17 20:36:46 +08:00
世界
73f8c6542b
Export std net bind 2026-05-17 20:36:46 +08:00
世界
a71256d250
Add device.InputPacket 2026-05-17 20:36:46 +08:00
世界
7be452de15
Add pause support 2026-05-17 20:36:45 +08:00
世界
b4db0692d3
Add custom worker size params
(cherry picked from commit 7c2acadba17cadf8a1df957c49e1333130d460ad)
(cherry picked from commit a7bac1754e7717e1d4009d1ffd2d13330067d631)
(cherry picked from commit 7a2f11c693b49e784318bbf987173095c67b563d)
2026-05-17 20:36:35 +08:00
世界
824e7573c0
Apply Tailscale TUN offload APIs 2026-05-17 20:36:35 +08:00
世界
414291f6d6
Apply Tailscale endpoint awareness 2026-05-17 20:36:35 +08:00
世界
749db0015c
Apply Tailscale bind send headroom 2026-05-17 20:36:35 +08:00
世界
45cd03b8a1
Downgrade dependencies 2026-05-17 20:36:34 +08:00
世界
75d0f348d5
Rename module 2026-05-17 20:09:28 +08:00
世界
f853bfc5c5
Remove unused 2026-05-17 20:04:34 +08:00
世界
e620c55272
Add module rename script 2026-05-17 20:02:24 +08:00
世界
680e63a4f8
Add remove unused script 2026-05-17 20:02:24 +08:00
世界
905a805bc6
Update .gitignore 2026-05-17 20:02:24 +08:00
Jason A. Donenfeld
f333402bd9 version: bump snapshot
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2025-05-22 01:45:02 +02:00
Jason A. Donenfeld
c92064f1ce conn: don't enable GRO on Linux < 5.12
Kernels below 5.12 are missing this:

    commit 98184612aca0a9ee42b8eb0262a49900ee9eef0d
    Author: Norman Maurer <norman_maurer@apple.com>
    Date:   Thu Apr 1 08:59:17 2021

        net: udp: Add support for getsockopt(..., ..., UDP_GRO, ..., ...);

        Support for UDP_GRO was added in the past but the implementation for
        getsockopt was missed which did lead to an error when we tried to
        retrieve the setting for UDP_GRO. This patch adds the missing switch
        case for UDP_GRO

        Fixes: e20cf8d3f1f7 ("udp: implement GRO for plain UDP sockets.")
        Signed-off-by: Norman Maurer <norman_maurer@apple.com>
        Reviewed-by: David Ahern <dsahern@kernel.org>
        Signed-off-by: David S. Miller <davem@davemloft.net>

That means we can't set the option and then read it back later. Given
how buggy UDP_GRO is in general on odd kernels, just disable it on older
kernels all together.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2025-05-22 01:43:39 +02:00
Alexander Yastrebov
264889f0bb device: optimize message encoding
Optimize message encoding by eliminating binary.Write (which internally
uses reflection) in favour of hand-rolled encoding.

This is companion to 9e7529c3d2.

Synthetic benchmark:

    var packetSink []byte
    func BenchmarkMessageInitiationMarshal(b *testing.B) {
        var msg MessageInitiation
        b.Run("binary.Write", func(b *testing.B) {
            b.ReportAllocs()
            for range b.N {
                var buf [MessageInitiationSize]byte
                writer := bytes.NewBuffer(buf[:0])
                _ = binary.Write(writer, binary.LittleEndian, msg)
                packetSink = writer.Bytes()
            }
        })
        b.Run("binary.Encode", func(b *testing.B) {
            b.ReportAllocs()
            for range b.N {
                packet := make([]byte, MessageInitiationSize)
                _, _ = binary.Encode(packet, binary.LittleEndian, msg)
                packetSink = packet
            }
        })
        b.Run("marshal", func(b *testing.B) {
            b.ReportAllocs()
            for range b.N {
                packet := make([]byte, MessageInitiationSize)
                _ = msg.marshal(packet)
                packetSink = packet
            }
        })
    }

Results:
                                             │      -      │
                                             │   sec/op    │
    MessageInitiationMarshal/binary.Write-8    1.337µ ± 0%
    MessageInitiationMarshal/binary.Encode-8   1.242µ ± 0%
    MessageInitiationMarshal/marshal-8         53.05n ± 1%

                                             │     -      │
                                             │    B/op    │
    MessageInitiationMarshal/binary.Write-8    368.0 ± 0%
    MessageInitiationMarshal/binary.Encode-8   160.0 ± 0%
    MessageInitiationMarshal/marshal-8         160.0 ± 0%

                                             │     -      │
                                             │ allocs/op  │
    MessageInitiationMarshal/binary.Write-8    3.000 ± 0%
    MessageInitiationMarshal/binary.Encode-8   1.000 ± 0%
    MessageInitiationMarshal/marshal-8         1.000 ± 0%

Signed-off-by: Alexander Yastrebov <yastrebov.alex@gmail.com>
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2025-05-21 00:09:36 +02:00
Jason A. Donenfeld
256bcbd70d device: add support for removing allowedips individually
This pairs with the recent change in wireguard-tools.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2025-05-20 23:03:06 +02:00
Jason A. Donenfeld
1571e0fbae version: bump snapshot
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2025-05-15 16:54:03 +02:00
Jason A. Donenfeld
842888ac5c device: make unmarshall length checks exact
This is already enforced in receive.go, but if these unmarshallers are
to have error return values anyway, make them as explicit as possible.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2025-05-15 16:48:14 +02:00
Alexander Yastrebov
9e7529c3d2 device: reduce RoutineHandshake allocations
Reduce allocations by eliminating byte reader, hand-rolled decoding and
reusing message structs.

Synthetic benchmark:

    var msgSink MessageInitiation
    func BenchmarkMessageInitiationUnmarshal(b *testing.B) {
        packet := make([]byte, MessageInitiationSize)
        reader := bytes.NewReader(packet)
        err := binary.Read(reader, binary.LittleEndian, &msgSink)
        if err != nil {
            b.Fatal(err)
        }
        b.Run("binary.Read", func(b *testing.B) {
            b.ReportAllocs()
            for range b.N {
                reader := bytes.NewReader(packet)
                _ = binary.Read(reader, binary.LittleEndian, &msgSink)
            }
        })
        b.Run("unmarshal", func(b *testing.B) {
            b.ReportAllocs()
            for range b.N {
                _ = msgSink.unmarshal(packet)
            }
        })
    }

Results:
                                         │      -      │
                                         │   sec/op    │
MessageInitiationUnmarshal/binary.Read-8   1.508µ ± 2%
MessageInitiationUnmarshal/unmarshal-8     12.66n ± 2%

                                         │      -       │
                                         │     B/op     │
MessageInitiationUnmarshal/binary.Read-8   208.0 ± 0%
MessageInitiationUnmarshal/unmarshal-8     0.000 ± 0%

                                         │      -       │
                                         │  allocs/op   │
MessageInitiationUnmarshal/binary.Read-8   2.000 ± 0%
MessageInitiationUnmarshal/unmarshal-8     0.000 ± 0%

Signed-off-by: Alexander Yastrebov <yastrebov.alex@gmail.com>
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2025-05-15 16:42:06 +02:00
Kurnia D Win
436f7fdc16 rwcancel: fix wrong poll event flag on ReadyWrite
It should be POLLIN because closeFd is read-only file.

Signed-off-by: Kurnia D Win <kurnia.d.win@gmail.com>
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2025-05-05 15:10:08 +02:00
Tom Holford
0e4482a086 device: use rand.NewSource instead of rand.Seed
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2025-05-05 15:10:08 +02:00
Tom Holford
77b6c824a8 global: replaced unused function params with _
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2025-05-05 15:10:08 +02:00
ruokeqx
bc30fee374 tun: darwin: fetch flags and mtu from if_msghdr directly
Signed-off-by: ruokeqx <ruokeqx@gmail.com>
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
2025-05-05 15:10:08 +02:00