Skip to main content

ts_dataplane/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use std::{collections::HashMap, sync::Arc, time::Instant};
4
5use ts_bart::RoutingTable;
6use ts_overlay_router as or;
7use ts_packet::PacketMut;
8use ts_packetfilter::{FilterExt, IpProto};
9use ts_time::{Handle, Scheduler};
10use ts_transport::{OverlayTransportId, PeerId, UnderlayTransportId};
11use ts_tunnel::{Endpoint, NodeKeyPair};
12use ts_underlay_router as ur;
13
14pub mod async_tokio;
15
16/// The single link-local destination Go's filter `pre()` exempts from the link-local drop: the
17/// cloud-metadata address `169.254.169.254` (Go `isAllowedLinkLocal`).
18const ALLOWED_LINK_LOCAL_V4: std::net::Ipv4Addr = std::net::Ipv4Addr::new(169, 254, 169, 254);
19
20/// Whether an inbound packet to destination `dst` must be dropped BEFORE consulting the ACL rules,
21/// mirroring Go's filter `pre()`: drop multicast destinations (`ReasonMulticast`) and link-local
22/// unicast destinations that are not the allowlisted cloud-metadata address (`ReasonLinkLocalUnicast`).
23/// Returning `true` means drop. This runs ahead of `can_access` so a permissive ACL cannot admit the
24/// multicast / link-local traffic Go rejects unconditionally.
25///
26/// Go's `isAllowedLinkLocal` is `dst == gcpDNSAddr || any(LinkLocalAllowHooks)`; only the static
27/// `gcpDNSAddr` arm is modeled here. The dynamic `LinkLocalAllowHooks` slice is empty in a plain
28/// engine/tsnet embedding (its only upstream producer is the GCP metadata path), so the omission is
29/// behaviorally equivalent for this fork; a feature that needs a dynamic link-local allowlist would
30/// have to extend this. Like Go's `netip.Addr` predicates, an IPv4-mapped-IPv6 destination (e.g.
31/// `::ffff:224.0.0.1`) matches NEITHER arm and falls through to the ACL — we deliberately do not
32/// canonicalize/unmap, to stay byte-faithful to Go (see the mapped-v6 test cases).
33fn drop_before_rules(dst: std::net::IpAddr) -> bool {
34    if dst.is_multicast() {
35        return true;
36    }
37    match dst {
38        // IPv4 link-local is 169.254.0.0/16; allow only the cloud-metadata address (Go parity).
39        std::net::IpAddr::V4(v4) => v4.is_link_local() && v4 != ALLOWED_LINK_LOCAL_V4,
40        // IPv6 unicast link-local is fe80::/10. (`Ipv6Addr::is_unicast_link_local` is unstable, so
41        // test the prefix directly.) This fork is IPv4-only by default, but match Go for any v6.
42        std::net::IpAddr::V6(v6) => (v6.segments()[0] & 0xffc0) == 0xfe80,
43    }
44}
45
46/// IPv4 fragment state read from the base header (Go `net/packet.decode4` reads `b[6:8]`): the
47/// fragment offset in 8-byte blocks and the more-fragments flag. A non-first fragment carries no L4
48/// header, so it needs its own verdict path rather than the (always-port-0) ACL match.
49#[derive(Debug, Clone, Copy)]
50struct Ipv4Fragment {
51    /// Fragment offset in 8-byte blocks (the 13-bit IPv4 field), 0 for the first/only fragment.
52    offset_blocks: u16,
53    /// The "more fragments" (MF) flag.
54    more_fragments: bool,
55}
56
57/// Minimum fragment offset (in 8-byte blocks) Go permits for a non-first fragment — Go
58/// `net/packet.minFragBlks = (60 + 20) / 8 = 10` (max IPv4 header + a basic TCP header). A later
59/// fragment starting before this could overlap a transport header (the RFC 1858 overlapping-fragment
60/// evasion), so Go demotes it to `unknown` and drops it; only fragments at or beyond this offset are
61/// allowed to "slide through".
62///
63/// Upstream reuses this one bound for IPv6 too (Go `net/packet` `26b2ed0a6` documents the reuse):
64/// it is sized for IPv4 and is therefore *conservative* for IPv6, whose fragments carry no
65/// per-fragment IP header — so on the v6 side it only ever rejects more later fragments as
66/// `unknown`, never fewer. Keep the single constant for both, exactly as Go does.
67const MIN_FRAG_BLKS: u16 = (60 + 20) / 8;
68
69/// Minimum IPv4 base header length (Go `net/packet.ip4HeaderLength`). A buffer shorter than this
70/// is not a decodable IPv4 packet at all (Go `decode4` returns `unknown`).
71const IP4_HEADER_LEN: usize = 20;
72
73/// Fixed IPv6 base header length (Go `net/packet.ip6HeaderLength`).
74const IP6_HEADER_LEN: usize = 40;
75
76/// IANA protocol number of the IPv6 Fragment extension header, "IPv6-Frag" (Go
77/// `net/packet.ip6FragHeader`). It appears as the **base** header's Next Header on a
78/// source-fragmented IPv6 packet, and is distinct from Go's internal `ipproto.Fragment` sentinel
79/// (0xff), which marks a non-first fragment whose sub-protocol header is not present.
80const IP6_FRAG_HEADER: u8 = 44;
81
82/// Length of the IPv6 Fragment extension header (Go `net/packet.ip6FragHeaderLength`): Next Header,
83/// Reserved, a 13-bit Fragment Offset in 8-byte blocks plus two reserved bits and the
84/// More-Fragments flag, then a 32-bit Identification.
85const IP6_FRAG_HEADER_LEN: usize = 8;
86
87/// How an IPv6 packet whose base header's Next Header is the Fragment extension header classifies —
88/// the port of Go `net/packet.Parsed.decode6Fragment` plus the sub-protocol switch `decode6` runs
89/// when it reports `continueDecode` (upstream `4c4ec3d46`, clarified by `26b2ed0a6`).
90///
91/// This is the IPv6 half of the RFC 1858 fragment rules [`Ipv4Fragment`] already carries. It only
92/// matters on the opt-in `Config::enable_ipv6` path — the tailnet is IPv4-only by default — but
93/// without it a source-fragmented IPv6 datagram reaches the ACL with no sub-protocol and port 0,
94/// so an allow-all rule admits the very low-offset fragments upstream drops, and a port-scoped rule
95/// blackholes the later fragments upstream passes through.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97enum Ipv6Fragment {
98    /// Go's `unknown`, which filter `pre()` drops outright: a Fragment header truncated by the
99    /// packet, a *first* fragment too short to hold its own transport header, a later fragment at
100    /// an offset small enough to overlap that transport header on reassembly (RFC 1858), the
101    /// on-the-wire use of Go's internal `ipproto.Fragment` sentinel, or a Fragment header reached
102    /// through a chained extension header rather than as the base header's immediate Next Header
103    /// ([`fragment_header_is_chained`]).
104    Unknown,
105    /// Go's `ipproto.Fragment`: a later fragment at a safe offset. It carries no sub-protocol
106    /// header, so there is nothing for a rule to match on and filter `pre()` passes it through
107    /// ahead of the ACL — statelessly, exactly as for IPv4. RFC 8200 §4.5 requires the receiver to
108    /// reassemble, and its kernel drops the pieces if the head fragment never arrives.
109    Later,
110    /// Go's `continueDecode == true`: the first fragment. `decode6` steps over the 8-byte Fragment
111    /// header and parses the real sub-protocol's header, so the ACL matches this datagram on the
112    /// same rule it would match unfragmented.
113    First {
114        /// The Fragment header's Next Header — the real sub-protocol (Go `q.IPProto = nextHdr`).
115        proto: IpProto,
116        /// The destination port read from that sub-protocol's header, 0 for a protocol Go does not
117        /// port-match (Go `withPort(q.Dst, ...)`).
118        dst_port: u16,
119    },
120}
121
122/// Classify a whole IPv6 packet `b` whose base header's Next Header is [`IP6_FRAG_HEADER`], as Go
123/// `net/packet.Parsed.decode6` does when it dispatches to `decode6Fragment`.
124///
125/// Callers must have already checked that immediate Next Header byte: Go parses the Fragment header
126/// **only** as the base header's immediate next header (upstream `26b2ed0a6` added a test locking
127/// that scoping in). No other extension header, and no IPSec AH/ESP header, is parsed here either —
128/// same as Go. A Fragment header reached through a chained extension header is *not* this
129/// function's business; it is [`fragment_header_is_chained`]'s, which classifies it
130/// [`Ipv6Fragment::Unknown`] so it is dropped.
131fn decode6_fragment(b: &[u8]) -> Ipv6Fragment {
132    // Go `q.length = BE16(b[4:6]) + ip6HeaderLength; if len(b) < q.length` — a packet cut off before
133    // its declared payload is `unknown`.
134    if b.len() < IP6_HEADER_LEN {
135        return Ipv6Fragment::Unknown;
136    }
137    let length = usize::from(u16::from_be_bytes([b[4], b[5]])) + IP6_HEADER_LEN;
138    if b.len() < length {
139        return Ipv6Fragment::Unknown;
140    }
141
142    // Go `if len(b) < q.subofs+ip6FragHeaderLength` with `q.subofs == 40`.
143    let Some(frag) = b.get(IP6_HEADER_LEN..) else {
144        return Ipv6Fragment::Unknown;
145    };
146    if frag.len() < IP6_FRAG_HEADER_LEN {
147        return Ipv6Fragment::Unknown;
148    }
149
150    let next_header = frag[0];
151    // Go `fragOfs := binary.BigEndian.Uint16(frag[2:4]) >> 3`: the top 13 bits are the offset in
152    // 8-byte blocks; the low 3 are two reserved bits and the More-Fragments flag. Go reads no MF
153    // flag here at all — unlike `decode4`, `decode6` has no more-fragments guard on the first
154    // fragment, so a first IPv6 fragment is decoded exactly like an unfragmented packet (TSMP
155    // included, where `decode4` instead demotes a fragmented first packet to `unknown`).
156    let frag_ofs = u16::from_be_bytes([frag[2], frag[3]]) >> 3;
157
158    // Go steps `q.subofs += ip6FragHeaderLength` before branching; `sub` is what follows.
159    let sub = &frag[IP6_FRAG_HEADER_LEN..];
160
161    if frag_ofs == 0 {
162        return decode6_first_fragment(IpProto::new(i64::from(next_header)), sub);
163    }
164    if frag_ofs < MIN_FRAG_BLKS {
165        // RFC 1858: this fragment's bytes could land on top of the transport header the ACL matched
166        // the head fragment on. Go `q.IPProto = unknown`, same guard as `decode4`.
167        return Ipv6Fragment::Unknown;
168    }
169    Ipv6Fragment::Later
170}
171
172/// The sub-protocol switch Go `decode6` runs on a first fragment once `decode6Fragment` has stepped
173/// over the Fragment header. `sub` is the buffer from the sub-protocol's header onwards (Go's
174/// `sub := b[q.subofs:]`, measured against the buffer, not the IPv6 length field).
175///
176/// Each arm's bounds check is Go's, and each failure is Go's `unknown`: a first fragment too short
177/// to hold the transport header must be **dropped**, never guessed at, or a follow-up fragment
178/// supplying the rest of that header would carry the flow past a rule the filter never really
179/// matched (RFC 1858, the same reason `decode4` rejects a short first fragment).
180fn decode6_first_fragment(proto: IpProto, sub: &[u8]) -> Ipv6Fragment {
181    /// Go `net/packet.icmp6HeaderLength`.
182    const ICMP6_HEADER_LEN: usize = 4;
183    /// Go `net/packet.tcpHeaderLength`.
184    const TCP_HEADER_LEN: usize = 20;
185    /// Go `net/packet.udpHeaderLength`.
186    const UDP_HEADER_LEN: usize = 8;
187    /// Go `net/packet.sctpHeaderLength`.
188    const SCTP_HEADER_LEN: usize = 12;
189    /// Go `net/packet.minTSMPSize` — the shortest TSMP body (a 7-byte rejected-connection message).
190    const MIN_TSMP_SIZE: usize = 7;
191    /// Go's internal `ipproto.Fragment` sentinel. Seeing it as a real Next Header is suspicious, so
192    /// Go maps it back to `unknown`.
193    const IPPROTO_FRAGMENT_SENTINEL: IpProto = IpProto::new(0xff);
194
195    // Go's port-ful arms: bounds-check, then read the destination port from `sub[2:4]`.
196    let ported = |min_len: usize| {
197        if sub.len() < min_len {
198            return Ipv6Fragment::Unknown;
199        }
200        Ipv6Fragment::First {
201            proto,
202            dst_port: u16::from_be_bytes([sub[2], sub[3]]),
203        }
204    };
205    // Go's portless arms: bounds-check only, both ports left at 0.
206    let portless = |min_len: usize| {
207        if sub.len() < min_len {
208            return Ipv6Fragment::Unknown;
209        }
210        Ipv6Fragment::First { proto, dst_port: 0 }
211    };
212
213    match proto {
214        IpProto::ICMPV6 => portless(ICMP6_HEADER_LEN),
215        IpProto::TCP => ported(TCP_HEADER_LEN),
216        IpProto::UDP => ported(UDP_HEADER_LEN),
217        IpProto::SCTP => ported(SCTP_HEADER_LEN),
218        IpProto::TSMP => portless(MIN_TSMP_SIZE),
219        IPPROTO_FRAGMENT_SENTINEL => Ipv6Fragment::Unknown,
220        // Go's switch has no default arm: any other protocol keeps its number and port 0, and the
221        // ACL matches it IPs-only (`IpProto::is_port_ful`).
222        _ => Ipv6Fragment::First { proto, dst_port: 0 },
223    }
224}
225
226/// Whether `ipv6` carries a Fragment extension header somewhere in its extension-header chain
227/// *other than* as the base header's immediate Next Header — the case [`decode6_fragment`] is
228/// deliberately not scoped to, and which must therefore fail closed here.
229///
230/// Callers must only ask this when the base header's Next Header is **not** [`IP6_FRAG_HEADER`];
231/// otherwise the leading Fragment header itself answers `true` and would shadow its own
232/// classification.
233///
234/// Why a drop and not a pass. Go's `decode6` sets `q.IPProto` from the base header's Next Header
235/// and steps over *only* a leading Fragment header, so a hop-by-hop-chained fragment leaves
236/// `q.IPProto == 0 == ipproto.Unknown` and filter `pre()` drops it before the ACL ever runs. This
237/// tree instead reads the sub-protocol out of etherparse's extension-header walk, which resolves
238/// straight through the chain to the real transport number — so without this check the packet
239/// reaches the ACL looking like an ordinary TCP/UDP datagram whose port merely happens to be 0
240/// (etherparse refuses to descend into a fragmenting payload), and a permissive "allow the whole
241/// tailnet" rule *admits* it. That re-opens the entire RFC 1858 hole this classification exists to
242/// close: prepend an 8-byte Hop-by-Hop Options header and a low-offset later fragment — the one
243/// whose bytes can land on top of the transport header the head fragment was matched on — slides
244/// past, as does a first fragment truncated before its own transport header. The fragment rules
245/// must not be defeatable by an extension header the attacker chooses to prepend, so anything
246/// carrying a chained Fragment header is [`Ipv6Fragment::Unknown`].
247///
248/// This drops a strict subset of what Go drops here (Go rejects the whole chained-extension-header
249/// class, fragmenting or not), so it cannot admit anything upstream refuses and cannot break a real
250/// Tailscale, `wireguard-go` or kernel-WireGuard peer: upstream would discard such a packet too, so
251/// no peer can already be relying on one being delivered.
252fn fragment_header_is_chained(ipv6: &etherparse::Ipv6Slice<'_>) -> bool {
253    ipv6.extensions()
254        .clone()
255        .into_iter()
256        .any(|ext| matches!(ext, etherparse::Ipv6ExtensionSlice::Fragment(_)))
257}
258
259/// Which address family's fragment rules apply to a packet, so [`inbound_filter_verdict`] can run
260/// Go's `decode4` and `decode6` fragment classifications on the packets each actually governs.
261#[derive(Debug, Clone, Copy)]
262enum Fragment {
263    /// IPv4: the offset and MF flag straight out of the base header (Go `decode4`).
264    V4(Ipv4Fragment),
265    /// IPv6: the already-resolved classification of a Fragment extension header (Go `decode6`).
266    V6(Ipv6Fragment),
267}
268
269/// The inbound packet-filter verdict for an already-parsed packet (`true` = admit). This is the
270/// proto-switch of Go's filter `runIn4`/`runIn6`, applied after `pre()` and after this fork's
271/// source-attribution and local-destination routing (the analogues of Go's `local4`/`local6`
272/// precondition) have run:
273///
274/// 1. `drop_before_rules` — Go `pre()`'s unconditional multicast / link-local-unicast drops.
275/// 2. **Fragment classification** (Go `net/packet.decode4`/`decode6` + filter `pre()`): a non-first
276///    fragment carries no L4 header, so it cannot be port-matched. Go classifies it by offset — a
277///    fragment at offset `>= MIN_FRAG_BLKS` is mapped to `ipproto.Fragment` and `pre()` **accepts**
278///    it (stateless pass-through; the receiver's kernel discards it if the head fragment was
279///    dropped), while a fragment at a smaller offset is dropped (RFC 1858). On IPv4 a *fragmented*
280///    TSMP is additionally disallowed (`moreFrags` on a first TSMP fragment → drop). Without this,
281///    etherparse leaves the transport `None` and the port reads as 0, so a normal ACL rule would
282///    silently drop every valid later fragment — breaking large/fragmented inbound traffic on the
283///    1280-MTU overlay. The IPv6 half ([`Ipv6Fragment`], Go `decode6Fragment`) additionally folds in
284///    the sub-protocol decode of a *first* fragment, so `proto`/`dst_port` here are already the ones
285///    read past the Fragment extension header, and `Ipv6Fragment::Unknown` — a truncated or
286///    short-first fragment, or one whose Fragment header sits behind a chained extension header
287///    ([`fragment_header_is_chained`]) — is dropped where Go's `pre()` drops `ipproto.Unknown`.
288/// 3. TSMP (proto 99) is always admitted, bypassing the ACL — Go `case ipproto.TSMP: return Accept`.
289///    TSMP carries in-band control messages between nodes, so it must reach the local stack
290///    regardless of the ACL rules.
291/// 4. Everything else consults the control-derived ACL via `can_access` — Go's `matches4.match`.
292fn inbound_filter_verdict(
293    filter: &(dyn ts_packetfilter::Filter + Send + Sync),
294    proto: IpProto,
295    src: std::net::IpAddr,
296    dst: std::net::IpAddr,
297    dst_port: u16,
298    frag: Option<Fragment>,
299) -> bool {
300    if drop_before_rules(dst) {
301        tracing::trace!(?dst, "dropping multicast/link-local dst (pre-rule)");
302        return false;
303    }
304
305    match frag {
306        Some(Fragment::V4(frag)) => {
307            if frag.offset_blocks > 0 {
308                // A non-first fragment (Go `decode4`'s `fragOfs != 0` branch). It has no transport
309                // header to match, so the verdict is decided purely by offset:
310                if frag.offset_blocks < MIN_FRAG_BLKS {
311                    // Potentially overlaps a transport header (RFC 1858); Go demotes to `unknown` → drop.
312                    tracing::trace!(?dst, "dropping low-offset IPv4 fragment (RFC 1858)");
313                    return false;
314                }
315                // A valid later fragment — Go maps it to `ipproto.Fragment`, which `pre()` accepts
316                // ahead of the ACL. Stateless: if the head fragment was filtered the receiver's kernel
317                // drops this on reassembly timeout. Accepting here is what large fragmented inbound
318                // traffic relies on.
319                tracing::trace!(
320                    ?dst,
321                    "accepting later IPv4 fragment (Go pre() pass-through)"
322                );
323                return true;
324            }
325            // `frag.offset_blocks == 0`: the first fragment (or an unfragmented packet). Go disallows a
326            // *fragmented* TSMP (a first fragment with MF set) — without the whole message it can't be a
327            // valid inter-node control packet. Fall through to the normal proto-switch for everything
328            // else; the first fragment of TCP/UDP carries its L4 header, so `dst_port` was parsed above.
329            if proto == IpProto::TSMP && frag.more_fragments {
330                tracing::trace!(?dst, "dropping fragmented TSMP (Go parity)");
331                return false;
332            }
333        }
334        // The IPv6 Fragment extension header (Go `decode6Fragment`, upstream `4c4ec3d46`). Only
335        // reachable on the opt-in `Config::enable_ipv6` path; the classification itself already ran
336        // Go's offset and bounds checks, so all that is left is Go's `pre()` disposition of the
337        // three protocol values `decode6` can end up with.
338        Some(Fragment::V6(Ipv6Fragment::Unknown)) => {
339            // Go `pre()`: `if q.IPProto == ipproto.Unknown { return Drop }`. This is the
340            // security-relevant arm — a short first fragment, an RFC 1858 low-offset later
341            // fragment, or a Fragment header hidden behind a chained extension header must never
342            // reach the ACL, where an allow-all rule would admit it.
343            tracing::trace!(
344                ?dst,
345                "dropping IPv6 fragment classified unknown (Go pre() drop)"
346            );
347            return false;
348        }
349        Some(Fragment::V6(Ipv6Fragment::Later)) => {
350            // Go `pre()`: `case ipproto.Fragment: return Accept`, same stateless pass-through as
351            // IPv4 — and required by RFC 8200 §4.5, which puts reassembly on the receiver.
352            tracing::trace!(
353                ?dst,
354                "accepting later IPv6 fragment (Go pre() pass-through)"
355            );
356            return true;
357        }
358        // A first IPv6 fragment: `proto` and `dst_port` were read past the Fragment header, so it
359        // takes the ordinary proto switch below and matches the rule an unfragmented datagram would.
360        // Note the deliberate asymmetry with IPv4: `decode6` has no more-fragments guard at all, so
361        // — unlike `decode4` — upstream does not demote a fragmented first TSMP packet to `unknown`.
362        Some(Fragment::V6(Ipv6Fragment::First { .. })) | None => {}
363    }
364
365    if proto == IpProto::TSMP {
366        tracing::trace!(?dst, "accepting TSMP inbound (bypasses ACL, Go parity)");
367        return true;
368    }
369
370    let info = ts_packetfilter::PacketInfo {
371        ip_proto: proto,
372        port: dst_port,
373        src,
374        dst,
375    };
376    // TODO(npry): wire in nodecaps
377    let caps = [];
378    let verdict = filter.can_access(&info, caps);
379    tracing::trace!(?info, ?caps, verdict);
380    verdict
381}
382
383/// Apply the inbound packet filter to one peer's already-source-attributed batch of decrypted
384/// packets, in place, and harvest any TSMP disco-key advertisements it carried.
385///
386/// This is the body of Go's `tstun.Wrapper.filterPacketInboundFromWireGuard`, in Go's order:
387///
388/// 1. **TSMP consumption.** Go inspects TSMP *before* running the ACL filter and returns
389///    `filter.DropSilently` for the messages it consumes itself. The one consumed here is the
390///    disco-key advertisement (Go `packet.TSMPDiscoKeyAdvertisement`, upstream capability version
391///    144): a peer announces its disco public key right after an eligible WireGuard session comes
392///    up, so the receiver learns it without waiting for a netmap update or restarting WireGuard.
393///    A real Go peer sends this unprompted. Every *other* TSMP message (ping, pong,
394///    rejected-connection) is left in the batch and falls through to step 2, which admits it —
395///    exactly as Go's filter does for the TSMP types it does not consume.
396/// 2. **The ACL verdict**, [`inbound_filter_verdict`] (Go `runIn4`/`runIn6`).
397///
398/// `learned_disco_keys` is appended to, never cleared, so one batch can carry advertisements from
399/// several peers. A learned key is attributed to `peer_id` — the WireGuard peer whose session
400/// decrypted the packet, and whose source addresses the caller's source filter has already bound.
401/// Go reaches the same peer the long way round, looking the advertisement's source IP up in the
402/// netmap (`wgengine.userspaceEngine.peerForIP`). Either way a peer can only advertise a key for
403/// *itself*: it cannot speak for another peer.
404fn filter_inbound_from_peer(
405    filter: &(dyn ts_packetfilter::Filter + Send + Sync),
406    peer_id: PeerId,
407    packets: &mut Vec<PacketMut>,
408    learned_disco_keys: &mut Vec<(PeerId, ts_packet::tsmp::DiscoKeyAdvertisement)>,
409) {
410    packets.retain(|packet| {
411        let bytes = packet.as_ref();
412        let Ok(pkt) = etherparse::SlicedPacket::from_ip(bytes) else {
413            tracing::trace!("does not look like ip packet");
414            return false;
415        };
416
417        let (proto, src, dst, frag) = match pkt.net {
418            Some(etherparse::NetSlice::Ipv4(ipv4)) => {
419                // IPv4 fragment state (Go `net/packet.decode4` reads `b[6:8]`): a
420                // non-first fragment carries no L4 header, so etherparse leaves
421                // `transport == None` and the port would read as 0 below — which a normal
422                // ACL rule never admits. Without classifying the fragment that silently
423                // drops valid later fragments Go *accepts* (breaking large/fragmented
424                // inbound traffic on the 1280-MTU overlay). Capture the offset (in 8-byte
425                // blocks) + the more-fragments bit so the verdict can mirror Go's
426                // `decode4`/`pre()` fragment handling.
427                let hdr = ipv4.header();
428                (
429                    IpProto::new(ipv4.payload().ip_number.0 as _),
430                    hdr.source_addr().into(),
431                    hdr.destination_addr().into(),
432                    Some(Fragment::V4(Ipv4Fragment {
433                        offset_blocks: hdr.fragments_offset().value(),
434                        more_fragments: hdr.more_fragments(),
435                    })),
436                )
437            }
438            Some(etherparse::NetSlice::Ipv6(ipv6)) => {
439                let hdr = ipv6.header();
440                // IPv6 fragmentation is carried in a Fragment extension header, not the
441                // base header. Go `decode6` parses that header — and *only* when it is the
442                // base header's immediate Next Header. `next_header()` is exactly that
443                // immediate byte, so testing it here reproduces upstream's scoping. Only
444                // reachable under the opt-in `Config::enable_ipv6`; the tailnet is IPv4-only
445                // by default.
446                //
447                // A Fragment header reached through a *chained* hop-by-hop / routing /
448                // destination-options / AH header is outside that scope, and must fail
449                // closed rather than fall through to the ACL: Go drops it (the base Next
450                // Header leaves `q.IPProto` at `ipproto.Unknown`, which `pre()` refuses),
451                // whereas etherparse resolves the real sub-protocol through the chain, so an
452                // allow-all rule would otherwise admit exactly the RFC 1858 fragments this
453                // classification exists to reject. See `fragment_header_is_chained`.
454                let frag = if hdr.next_header().0 == IP6_FRAG_HEADER {
455                    Some(decode6_fragment(bytes))
456                } else if fragment_header_is_chained(&ipv6) {
457                    Some(Ipv6Fragment::Unknown)
458                } else {
459                    None
460                };
461                let proto = match frag {
462                    // Go `q.IPProto = nextHdr`: the first fragment's real sub-protocol, read
463                    // past the 8-byte Fragment header.
464                    Some(Ipv6Fragment::First { proto, .. }) => proto,
465                    // A later or malformed fragment has no sub-protocol at all (Go's
466                    // `ipproto.Fragment` / `unknown`); the verdict decides on the
467                    // classification alone and never consults this.
468                    Some(Ipv6Fragment::Later | Ipv6Fragment::Unknown) => IpProto::new(0),
469                    None => IpProto::new(ipv6.payload().ip_number.0 as _),
470                };
471                (
472                    proto,
473                    hdr.source_addr().into(),
474                    hdr.destination_addr().into(),
475                    frag.map(Fragment::V6),
476                )
477            }
478            _ => {
479                // A packet that parsed as IP but is neither IPv4 nor IPv6 (e.g. a
480                // future/odd `NetSlice` shape). These bytes are attacker-controlled
481                // post-decrypt, so fail closed — drop it — rather than `unreachable!`,
482                // which would panic the single-threaded dataplane on a crafted packet.
483                // Go's filter `pre()` likewise returns Drop/"not-ip" here, never panics.
484                tracing::trace!("parsed packet is neither IPv4 nor IPv6; dropping");
485                return false;
486            }
487        };
488
489        // Go `decode6` reads a *first* IPv6 fragment's transport ports past the Fragment
490        // extension header, so a fragmented datagram matches the same rule as an
491        // unfragmented one. etherparse deliberately refuses to descend into a fragmenting
492        // payload and leaves `transport == None`, so that port comes from the
493        // classification above instead.
494        let dst_port = match frag {
495            Some(Fragment::V6(Ipv6Fragment::First { dst_port, .. })) => dst_port,
496            _ => match pkt.transport {
497                Some(etherparse::TransportSlice::Udp(udp)) => udp.destination_port(),
498                Some(etherparse::TransportSlice::Tcp(tcp)) => tcp.destination_port(),
499                _ => 0,
500            },
501        };
502
503        // TSMP disco-key advertisement (Go `packet.TSMPDiscoKeyAdvertisement`,
504        // upstream capability version 144). Go handles TSMP in
505        // `tstun.filterPacketInboundFromWireGuard` *before* the ACL filter runs, and
506        // returns `filter.DropSilently` for an advertisement: it is an inter-node
507        // control message consumed here, never delivered to the local stack. Mirror
508        // both the position (after source attribution, before the ACL) and the drop.
509        //
510        if proto == IpProto::TSMP
511            && let Some(advert) = ts_packet::tsmp::DiscoKeyAdvertisement::parse(bytes)
512        {
513            if advert.key_is_zero() {
514                // Go publishes only `if !discoKeyAdvert.Key.IsZero()`. Still a
515                // well-formed advertisement, so it is still dropped.
516                tracing::debug!(
517                    ?peer_id,
518                    "TSMP disco-key advertisement carried the zero key; ignoring"
519                );
520            } else {
521                tracing::debug!(?peer_id, %src, "learned peer disco key over TSMP");
522                learned_disco_keys.push((peer_id, advert));
523            }
524            return false;
525        }
526
527        // The inbound proto-switch (Go `runIn4`/`runIn6`): Go `pre()` multicast/link-local
528        // drops, then the fragment classification (Go `decode4` + `pre()`), then
529        // unconditional TSMP accept, then the control-derived ACL. The caller's source
530        // attribution and `or_in.route` bound this to attributable peers and local
531        // destinations (Go's `local4`/`local6` precondition).
532        inbound_filter_verdict(filter, proto, src, dst, dst_port, frag)
533    });
534}
535
536/// Where this node sends a TSMP disco-key advertisement, and what it puts in one.
537///
538/// The send half of Go's capability version 144 (`packet.TSMPDiscoKeyAdvertisement`): when a
539/// WireGuard session with a peer is established, this node announces its own disco public key to
540/// that peer over TSMP, so the peer can learn (or re-learn) the key without waiting for a netmap
541/// update from control. It is the mirror image of the receive half in
542/// [`filter_inbound_from_peer`], and both are unconditional — a real Go peer sends us one whether
543/// or not we send one back.
544///
545/// This is the netmap state Go's [`magicsock.Conn.PriorityMessageForPeer`] reads, snapshotted into
546/// the dataplane so building the message stays a cheap, synchronous, allocation-only step on the
547/// datapath. wireguard-go requires the same of its callback: "must be cheap and must not call back
548/// into the [`Device`]". The runtime refreshes the snapshot whenever the netmap changes.
549///
550/// [`magicsock.Conn.PriorityMessageForPeer`]: https://github.com/tailscale/tailscale/blob/main/wgengine/magicsock/magicsock.go
551/// [`Device`]: https://github.com/tailscale/wireguard-go/blob/main/device/device.go
552#[derive(Debug, Clone, Default)]
553pub struct DiscoAdvertisementState {
554    /// This node's own disco public key, raw (Go `Conn.DiscoPublicKey()`). The all-zero key means
555    /// "no disco key", and nothing is ever advertised — Go's first refusal.
556    pub disco_key: [u8; ts_packet::tsmp::DISCO_KEY_LEN],
557    /// This node's own tailnet addresses, in the order control sent them (Go `self.Addresses()`,
558    /// already narrowed to the single-IP prefixes `selfIPMatchingFamily` accepts). The
559    /// advertisement's source is the first entry matching the destination's family.
560    pub self_addrs: Vec<std::net::IpAddr>,
561    /// Where to send an advertisement, per peer. A peer absent from this map is never advertised
562    /// to — Go's `endpointForNodeKey` miss.
563    pub peers: HashMap<PeerId, AdvertisementTarget>,
564}
565
566/// One peer's advertisement destination, as [`DiscoAdvertisementState`] holds it.
567#[derive(Debug, Clone, Copy, PartialEq, Eq)]
568pub struct AdvertisementTarget {
569    /// The peer's first tailnet address (Go `endpoint.nodeAddr`), which is the advertisement's
570    /// destination address.
571    pub node_addr: std::net::IpAddr,
572    /// Whether this is a plain WireGuard peer rather than a Tailscale node (Go
573    /// `endpoint.isWireguardOnly`). Such a peer speaks no TSMP, so Go never sends it one — and a
574    /// kernel-WireGuard or `wireguard-go` peer would hand the advertisement straight to its host
575    /// network stack as an unknown-protocol packet.
576    pub wireguard_only: bool,
577}
578
579impl DiscoAdvertisementState {
580    /// The marshalled TSMP disco-key advertisement to send `peer` on session establishment, or
581    /// `None` if this node must not advertise to it.
582    ///
583    /// Go [`magicsock.Conn.PriorityMessageForPeer`], refusal for refusal — every one of these is a
584    /// silent "send nothing", never a fallback to some other message:
585    ///
586    /// 1. **No disco key of our own** (`disco.IsZero()`): there is nothing to advertise.
587    /// 2. **Unknown peer** (`endpointForNodeKey` miss, or `!self.Valid()`): the netmap snapshot has
588    ///    no destination address for this WireGuard peer, so any address we invented would be a
589    ///    guess.
590    /// 3. **A WireGuard-only peer** (`ep.isWireguardOnly`): "Do not send TSMP messages to peers
591    ///    that only speaks wireguard."
592    /// 4. **No source address in the destination's family** (`selfIPMatchingFamily` returning the
593    ///    zero `Addr`): an IPv4-only node has nothing to put in the source field of a packet to a
594    ///    peer's IPv6 address.
595    /// 5. A marshal refusal, which by construction of (4) cannot happen — see
596    ///    [`ts_packet::tsmp::DiscoKeyAdvertisement::marshal`].
597    ///
598    /// [`magicsock.Conn.PriorityMessageForPeer`]: https://github.com/tailscale/tailscale/blob/main/wgengine/magicsock/magicsock.go
599    pub fn advertisement_for(&self, peer: PeerId) -> Option<Vec<u8>> {
600        if self.disco_key == [0u8; ts_packet::tsmp::DISCO_KEY_LEN] {
601            tracing::debug!(?peer, "no disco key of our own; not advertising");
602            return None;
603        }
604
605        let target = self.peers.get(&peer)?;
606
607        if target.wireguard_only {
608            return None;
609        }
610
611        let src = self_ip_matching_family(&self.self_addrs, target.node_addr)?;
612
613        ts_packet::tsmp::DiscoKeyAdvertisement {
614            src,
615            dst: target.node_addr,
616            key: self.disco_key,
617        }
618        .marshal()
619        .inspect_err(|e| tracing::debug!(?peer, error = %e, "not advertising our disco key"))
620        .ok()
621    }
622}
623
624/// This node's first tailnet address whose family matches `want`, or `None`.
625///
626/// Go `magicsock.selfIPMatchingFamily`, which walks `self.Addresses()` and returns the first
627/// single-IP prefix with `Addr().BitLen() == want.BitLen()`. `addrs` is already narrowed to
628/// single IPs by the caller that builds the snapshot, so only the family test remains.
629fn self_ip_matching_family(
630    addrs: &[std::net::IpAddr],
631    want: std::net::IpAddr,
632) -> Option<std::net::IpAddr> {
633    addrs
634        .iter()
635        .copied()
636        .find(|addr| addr.is_ipv4() == want.is_ipv4())
637}
638
639/// The `tstun_out_to_wg_drop_tsmp` counter (Go `metricPacketOutDropTSMP`), registered into the
640/// process-global registry on first use and exported by `ts_metrics::write_prometheus`. This is the
641/// durable signal for [`outbound_packet_carries_tsmp`] firing: the datapath log below it is
642/// `debug!`, because a local process can write these as fast as it likes and this tree has no
643/// rate-limited logger to put behind Go's `limitedLogf`.
644fn metric_out_to_wg_drop_tsmp() -> &'static ts_metrics::Metric {
645    static M: std::sync::OnceLock<&'static ts_metrics::Metric> = std::sync::OnceLock::new();
646    M.get_or_init(|| ts_metrics::Metric::new_counter("tstun_out_to_wg_drop_tsmp"))
647}
648
649/// Whether the IP packet `b`, written into the TUN by a local host process, carries TSMP and must
650/// therefore be dropped before it reaches WireGuard.
651///
652/// Go `tstun.filterPacketOutboundToWireGuard`: "TSMP traffic should only originate from tailscaled,
653/// not from the host itself." TSMP is the inter-node control channel — capability version 144's
654/// disco-key advertisement rides it — so a TSMP packet the host writes is either a confused
655/// networking stack or a local process forging a control message in this node's name. A peer cannot
656/// tell a forged advertisement from one this node meant to send: both arrive inside this node's
657/// WireGuard session, from this node's tailnet address. It would bind whatever disco key the forger
658/// chose.
659///
660/// The advertisements this node legitimately sends never pass through here. They are built in
661/// [`DiscoAdvertisementState::advertisement_for`] and injected straight into the WireGuard session
662/// by [`DataPlane::process_inbound`] (the priority-message path), which is *below* this check —
663/// the same relationship Go has, where `injectedRead` bypasses the outbound filter entirely.
664///
665/// # Where this is a superset of Go's classification, and why
666///
667/// Go tests the decoded `p.IPProto`, so a *malformed* proto-99 packet decodes to `ipproto.Unknown`
668/// rather than TSMP and slips past this particular check — only to be dropped one step later by the
669/// outbound ACL, whose `pre()` refuses `ipproto.Unknown` outright. This tree has no outbound ACL at
670/// all, so there is no second refusal to fall through to; testing the header's protocol byte
671/// reaches Go's *net* verdict (nothing carrying proto 99 leaves the host) in one step instead of
672/// two. Concretely, three shapes are dropped here that Go's TSMP arm alone would not:
673///
674/// - an IPv4 TSMP packet that is fragmented, truncated, or shorter than `minTSMPSize`;
675/// - an IPv6 packet whose Fragment extension header names TSMP but whose first fragment is too
676///   short to hold a TSMP body;
677/// - a *later* IPv6 fragment of a TSMP datagram (Go classifies it `ipproto.Fragment` and does put
678///   it on the wire). This is the one shape Go sends and we do not, and it is unreachable in
679///   practice: its head fragment is dropped by Go and by us alike, so no peer could ever reassemble
680///   the datagram, and nothing in a Tailscale node ever emits a fragmented TSMP message in the
681///   first place. No real peer can be relying on one arriving.
682///
683/// A Fragment header reached through a *chained* extension header (hop-by-hop, routing, destination
684/// options) is deliberately not chased: Go's `decode6` only steps over a Fragment header that is the
685/// base header's immediate Next Header, so such a packet decodes to `ipproto.Unknown` at every
686/// Tailscale receiver — including [`ts_packet::tsmp::DiscoKeyAdvertisement::parse`] here — and is
687/// discarded rather than read as a control message. It is not a forgery vector.
688fn outbound_packet_carries_tsmp(b: &[u8]) -> bool {
689    match b.first().map(|first| first >> 4) {
690        // Go `decode4`: `q.IPProto = ipproto.Proto(b[9])`.
691        Some(4) => b.len() >= IP4_HEADER_LEN && b[9] == ts_packet::tsmp::IP_PROTO_TSMP,
692        Some(6) => {
693            if b.len() < IP6_HEADER_LEN {
694                return false;
695            }
696            // Go `decode6`: `q.IPProto = ipproto.Proto(b[6])`, then step over a leading Fragment
697            // extension header and take its Next Header instead. Every fragment of one datagram
698            // repeats that Next Header, so this catches the head fragment (which is what Go's TSMP
699            // arm catches) and its followers alike.
700            match b[6] {
701                ts_packet::tsmp::IP_PROTO_TSMP => true,
702                IP6_FRAG_HEADER => b
703                    .get(IP6_HEADER_LEN)
704                    .is_some_and(|next| *next == ts_packet::tsmp::IP_PROTO_TSMP),
705                _ => false,
706            }
707        }
708        // Not an IP packet at all: `or_out.route` drops it a moment later for want of a
709        // destination address. Nothing to classify.
710        _ => false,
711    }
712}
713
714/// A data plane subsystem that can be the subject of timer events.
715pub enum Subsystem {
716    /// The wireguard component.
717    Wireguard,
718}
719
720/// The direction/path of a captured packet, mirroring Go Tailscale's `capture.Path`. The numeric
721/// values are the on-wire path codes written into each pcap record's Tailscale preamble.
722#[derive(Debug, Clone, Copy, PartialEq, Eq)]
723pub enum CapturePath {
724    /// A packet from the local device, heading out to a peer (pre-encrypt).
725    FromLocal = 0,
726    /// A packet received from a peer, decrypted, heading to the local device.
727    FromPeer = 1,
728    /// A packet synthesized by us toward the local device. Retained for Go `capture.Path` on-wire
729    /// code parity (so captured pcap path codes match Go's, and a future synthesized-packet tee
730    /// point can emit it); not currently emitted — the tee only produces `FromLocal`/`FromPeer`.
731    SynthesizedToLocal = 2,
732    /// A packet synthesized by us toward a peer. Retained for Go `capture.Path` on-wire code parity
733    /// (see [`Self::SynthesizedToLocal`]); not currently emitted.
734    SynthesizedToPeer = 3,
735}
736
737impl CapturePath {
738    /// The on-wire path code (the `uint16` written into the pcap record preamble).
739    pub fn code(self) -> u16 {
740        self as u16
741    }
742}
743
744/// A debug packet-capture hook. When installed on a [`DataPlane`], it is invoked with the path and
745/// the raw IP packet bytes for every plaintext packet crossing the datapath. It must be cheap and
746/// non-blocking — it runs inline on the single-threaded dataplane step, so a slow hook backs up the
747/// datapath. Wrapped in `Arc` so it is cheap to clone and `Send + Sync` for the actor that installs
748/// it.
749pub type CaptureHook = std::sync::Arc<dyn Fn(CapturePath, &[u8]) + Send + Sync>;
750
751/// Transforms packets to make tailscale happen.
752pub struct DataPlane {
753    /// Wireguard encryption/decryption.
754    pub wireguard: Endpoint,
755
756    /// Outbound overlay router.
757    pub or_out: or::outbound::Router,
758    /// Outbound underlay router.
759    pub ur_out: ur::outbound::Router,
760
761    /// Inbound source filter.
762    pub src_filter_in: Arc<ts_bart::Table<PeerId>>,
763    /// Inbound overlay router.
764    pub or_in: or::inbound::Router,
765
766    /// The packet filter.
767    pub packet_filter: Arc<dyn ts_packetfilter::Filter + Send + Sync>,
768
769    /// Events queued for future processing.
770    pub events: Scheduler<Subsystem>,
771
772    /// Next event for the wireguard subsystem.
773    pub wg_next: Option<Handle<Subsystem>>,
774
775    /// Optional debug packet-capture hook (Go `tstun.Wrapper` capture hook). `None` (the default)
776    /// means no capture and zero datapath overhead. Installed/cleared at runtime by the dataplane
777    /// actor; see [`DataPlane::process_outbound`]/[`DataPlane::process_inbound`] for the tee points.
778    pub capture: Option<CaptureHook>,
779
780    /// Netmap snapshot for the TSMP disco-key advertisement this node sends on session
781    /// establishment (Go capability version 144). `None` (the default) advertises nothing at all,
782    /// which is what an embedder that never populates it gets — the same position this fork was in
783    /// before the send side existed, and still fully interoperable, since a peer's own
784    /// advertisement is unsolicited. Refreshed from the netmap by the runtime's dataplane actor.
785    pub disco_advertisement: Option<Arc<DiscoAdvertisementState>>,
786}
787
788impl DataPlane {
789    /// Creates a new data plane for a wireguard node key.
790    pub fn new(my_key: NodeKeyPair) -> Self {
791        DataPlane {
792            wireguard: Endpoint::new(my_key),
793            or_out: Default::default(),
794            ur_out: Default::default(),
795            src_filter_in: Default::default(),
796            or_in: Default::default(),
797            events: Default::default(),
798            packet_filter: Arc::new(ts_packetfilter::DropAllFilter),
799            wg_next: None,
800            capture: None,
801            disco_advertisement: None,
802        }
803    }
804
805    /// Processes packets originating from the local device.
806    ///
807    /// Packets carrying TSMP are refused here (Go `tstun.filterPacketOutboundToWireGuard`): the
808    /// inter-node control channel must only ever carry messages this node built, never bytes a host
809    /// process handed us. See `outbound_packet_carries_tsmp` for why, and for the one shape Go
810    /// forwards that this refuses.
811    #[tracing::instrument(skip_all, fields(n_packets = packets.len()))]
812    pub fn process_outbound(&mut self, mut packets: Vec<PacketMut>) -> OutboundResult {
813        // The capture tee runs first, and so still sees the packets dropped just below — Go tees to
814        // its capture hook in `Wrapper.Read` before calling the outbound filter, so a pcap taken on
815        // either implementation shows the refused packet.
816        if let Some(hook) = &self.capture {
817            for p in &packets {
818                hook(CapturePath::FromLocal, p.as_ref());
819            }
820        }
821
822        packets.retain(|p| {
823            if outbound_packet_carries_tsmp(p.as_ref()) {
824                tracing::debug!("[unexpected] TSMP packet written into the tun; dropping");
825                metric_out_to_wg_drop_tsmp().inc();
826                return false;
827            }
828            true
829        });
830
831        let or::outbound::Result {
832            to_wireguard,
833            loopback,
834        } = self.or_out.route(packets);
835
836        let to_wireguard = to_wireguard
837            .into_iter()
838            .map(|(k, v)| (ts_tunnel::PeerId(k.0), v))
839            .collect::<Vec<_>>();
840
841        let ts_tunnel::SendResult {
842            to_peers: encrypted,
843        } = self.wireguard.send(to_wireguard);
844
845        let to_peers = self
846            .ur_out
847            .route(encrypted.into_iter().map(|(k, v)| (PeerId(k.0), v)));
848
849        if let Some(next) = self.wireguard.next_event()
850            && let Some(prev) = self
851                .wg_next
852                .replace(self.events.add(next, Subsystem::Wireguard))
853        {
854            prev.cancel();
855        }
856
857        OutboundResult { to_peers, loopback }
858    }
859
860    /// Processes packets received from elsewhere, with no information about which peer sent them.
861    ///
862    /// Equivalent to [`DataPlane::process_inbound_from`] with no attribution; see there for what
863    /// the attribution buys.
864    pub fn process_inbound(
865        &mut self,
866        packets: impl IntoIterator<Item = PacketMut>,
867    ) -> InboundResult {
868        self.process_inbound_from(None, packets)
869    }
870
871    /// Processes packets an underlay transport received and attributed to peer `from`.
872    ///
873    /// The attribution is what lets the WireGuard layer answer a handshake initiation with a
874    /// cookie while it is under load: the reply has to go back where the initiation came from, and
875    /// in this stack that origin is a peer, not a source address. See
876    /// [`ts_tunnel::Endpoint::recv_from`].
877    pub fn process_inbound_from(
878        &mut self,
879        from: Option<PeerId>,
880        packets: impl IntoIterator<Item = PacketMut>,
881    ) -> InboundResult {
882        let ts_tunnel::RecvResult {
883            to_local,
884            to_peers,
885            sessions_established,
886        } = self
887            .wireguard
888            .recv_from(from.map(|p| ts_tunnel::PeerId(p.0)), packets);
889
890        if let Some(hook) = &self.capture {
891            for packets in to_local.values() {
892                for p in packets {
893                    hook(CapturePath::FromPeer, p.as_ref());
894                }
895            }
896        }
897
898        // TSMP disco-key advertisements learned from this batch (Go `tstun.Wrapper`'s
899        // `discoKeyAdvertisementPub` publisher). Filled in by the packet-filter stage below, which
900        // is the point at which a packet has both been attributed to a peer and decoded far enough
901        // to know it is TSMP.
902        let mut learned_disco_keys: Vec<(PeerId, ts_packet::tsmp::DiscoKeyAdvertisement)> =
903            Vec::new();
904
905        let to_local = to_local
906            .into_iter()
907            .map(|(peer_id, mut packets)| -> (PeerId, Vec<PacketMut>) {
908                let _span = tracing::trace_span!(
909                    "src_filter_inbound",
910                    peer_id = ?peer_id,
911                    n_packet = packets.len(),
912                )
913                .entered();
914
915                packets.retain(|packet| {
916                    let Some(src) = packet.get_src_addr() else {
917                        tracing::trace!("does not look like ip packet");
918                        return false;
919                    };
920                    let verdict = if let Some(allowed_peer) = self.src_filter_in.lookup(src) {
921                        *allowed_peer == PeerId(peer_id.0)
922                    } else {
923                        tracing::trace!(remote_ip = %src, "unknown peer address");
924                        false
925                    };
926                    tracing::trace!(?src, verdict);
927                    verdict
928                });
929
930                (PeerId(peer_id.0), packets)
931            })
932            .map(|(peer_id, mut v)| {
933                let _span = tracing::trace_span!(
934                    "packet_filter_inbound",
935                    peer_id = ?peer_id,
936                    n_packet = v.len()
937                )
938                .entered();
939
940                filter_inbound_from_peer(
941                    self.packet_filter.as_ref(),
942                    peer_id,
943                    &mut v,
944                    &mut learned_disco_keys,
945                );
946
947                v
948            });
949
950        // TSMP disco-key advertisement, send side (Go capability version 144). wireguard-go calls
951        // `peer.SendPriorityMessage()` the moment a keypair becomes current for forward
952        // transmission — on the initiator when the handshake response lands, and on the responder
953        // when the first transport packet authenticates on the new keypair (`device/receive.go`).
954        // `sessions_established` is exactly those two moments; the message is Go's
955        // `magicsock.Conn.PriorityMessageForPeer` return value. A peer we must not advertise to
956        // (see [`DiscoAdvertisementState::advertisement_for`]) simply gets nothing, and the fresh
957        // session is otherwise untouched.
958        let mut to_peers = to_peers;
959        if let Some(advert) = self.disco_advertisement.clone() {
960            // Held apart from what `recv` already queued for these peers so it can be spliced in
961            // FRONT of it below, rather than appended behind it.
962            let mut priority: HashMap<ts_tunnel::PeerId, Vec<PacketMut>> = HashMap::new();
963            for peer in sessions_established {
964                let Some(msg) = advert.advertisement_for(PeerId(peer.0)) else {
965                    continue;
966                };
967                tracing::debug!(peer_id = ?peer, "advertising our disco key over TSMP");
968                for (peer, packets) in self.wireguard.send_priority_message(peer, &msg).to_peers {
969                    priority.entry(peer).or_default().extend(packets);
970                }
971            }
972            // A priority message leads the traffic the same establishment released. wireguard-go
973            // hands it straight to the peer's *outbound* queue (`SendPriorityMessage` →
974            // `queueOutboundIfRunning`), never to the staged queue, and both call sites run it
975            // before the flush that follows — `peer.SendPriorityMessage()` ahead of
976            // `peer.SendKeepalive()` on the initiator and ahead of `peer.SendStagedPackets()` on
977            // the responder (`device/receive.go`). Here the flush has already happened inside
978            // [`Endpoint::recv`] (`activate` encrypts whatever was queued), so restoring Go's wire
979            // order means splicing the advertisement in front of it.
980            //
981            // Only the wire order is restored, not Go's nonce order: those flushed packets were
982            // sealed first and so hold the lower nonces, where Go would have numbered the priority
983            // message first. That is invisible to the peer. A WireGuard receiver accepts an
984            // earlier counter after a later one by construction, and the inversion is bounded by
985            // the send queue a session flushes on activation (`MAX_QUEUED_PER_PEER`, 32 packets) —
986            // two orders of magnitude inside the 8128-packet anti-replay window WireGuard
987            // receivers carry (`ts_tunnel`'s `ReplayWindow::WINDOW_SIZE`, wireguard-go parity).
988            for (peer, mut packets) in priority {
989                let queued = to_peers.entry(peer).or_default();
990                packets.append(queued);
991                *queued = packets;
992            }
993        }
994
995        let to_peers = to_peers
996            .into_iter()
997            .map(|(k, v)| (ts_transport::PeerId(k.0), v));
998
999        let to_local = self.or_in.route(to_local.flatten());
1000        let to_peers = self.ur_out.route(to_peers);
1001
1002        if let Some(next) = self.wireguard.next_event()
1003            && let Some(prev) = self
1004                .wg_next
1005                .replace(self.events.add(next, Subsystem::Wireguard))
1006        {
1007            prev.cancel();
1008        }
1009
1010        InboundResult {
1011            to_local,
1012            to_peers,
1013            learned_disco_keys,
1014        }
1015    }
1016
1017    /// Return the next time at which [`DataPlane::process_events`] must be called.
1018    ///
1019    /// [`DataPlane::process_outbound`], [`DataPlane::process_inbound`] and
1020    /// [`DataPlane::process_events`] may all update the next event time. Callers should prefer
1021    /// calling `next_event` as needed to get a correct result, rather than store the returned
1022    /// value.
1023    pub fn next_event(&self) -> Option<Instant> {
1024        self.events.next_dispatch()
1025    }
1026
1027    /// Process all queued events that are due for processing.
1028    ///
1029    /// Must be called at least as often as dictated by [`DataPlane::next_event`] for the
1030    /// data plane to function correctly. It is harmless to call it more frequently.
1031    pub fn process_events(&mut self) -> EventResult {
1032        let mut to_peers = HashMap::new();
1033        let now = Instant::now();
1034        for event in self.events.dispatch(now) {
1035            match event {
1036                Subsystem::Wireguard => {
1037                    let res = self.wireguard.dispatch_events(now);
1038                    to_peers.extend(
1039                        res.to_peers
1040                            .into_iter()
1041                            .map(|(id, pkts)| (ts_transport::PeerId(id.0), pkts)),
1042                    );
1043                }
1044            }
1045        }
1046        let to_peers = self.ur_out.route(to_peers);
1047
1048        if let Some(next) = self.wireguard.next_event()
1049            && let Some(prev) = self
1050                .wg_next
1051                .replace(self.events.add(next, Subsystem::Wireguard))
1052        {
1053            prev.cancel();
1054        }
1055
1056        EventResult { to_peers }
1057    }
1058}
1059
1060/// The result of processing outbound packets.
1061pub struct OutboundResult {
1062    /// Packets to be sent into underlay transports for transmission.
1063    pub to_peers: HashMap<(UnderlayTransportId, PeerId), Vec<PacketMut>>,
1064    /// Packets to be looped back and delivered to overlay transports.
1065    pub loopback: HashMap<OverlayTransportId, Vec<PacketMut>>,
1066}
1067
1068/// The result of processing inbound packets.
1069pub struct InboundResult {
1070    /// Decrypted packets to be delivered to overlay transports.
1071    pub to_local: HashMap<OverlayTransportId, Vec<PacketMut>>,
1072    /// Encrypted packets to be sent to wireguard peers by the underlay.
1073    pub to_peers: HashMap<(UnderlayTransportId, PeerId), Vec<PacketMut>>,
1074    /// Disco keys peers advertised over TSMP in this batch, each paired with the WireGuard peer
1075    /// whose session carried it (Go `tstun.Wrapper` publishing `events.PeerDiscoKeyUpdate`, which
1076    /// `wgengine` turns into a `magicsock.Conn.HandleDiscoKeyAdvertisement` call).
1077    ///
1078    /// The advertisement packets themselves are dropped: they are inter-node control messages, not
1079    /// traffic for the local stack. Zero keys are already filtered out. Empty for a batch that
1080    /// carried none, which is the overwhelmingly common case.
1081    pub learned_disco_keys: Vec<(PeerId, ts_packet::tsmp::DiscoKeyAdvertisement)>,
1082}
1083
1084/// The result of processing an event.
1085#[derive(Default)]
1086pub struct EventResult {
1087    /// Encrypted packets to be sent to wireguard peers by the underlay.
1088    pub to_peers: HashMap<(UnderlayTransportId, PeerId), Vec<PacketMut>>,
1089}
1090
1091#[cfg(test)]
1092mod tests {
1093    use std::sync::Mutex;
1094
1095    use super::*;
1096
1097    /// Records `(path, bytes)` for each capture-hook invocation in a test.
1098    type CaptureLog = Arc<Mutex<Vec<(CapturePath, Vec<u8>)>>>;
1099
1100    #[test]
1101    fn capture_path_codes() {
1102        assert_eq!(CapturePath::FromLocal.code(), 0);
1103        assert_eq!(CapturePath::FromPeer.code(), 1);
1104        assert_eq!(CapturePath::SynthesizedToLocal.code(), 2);
1105        assert_eq!(CapturePath::SynthesizedToPeer.code(), 3);
1106    }
1107
1108    /// The pre-rule destination screen (Go filter `pre()`): multicast and non-allowlisted link-local
1109    /// destinations are dropped before the ACL; ordinary unicast and the cloud-metadata link-local
1110    /// exception pass through to the rules.
1111    #[test]
1112    fn pre_rule_drop_matches_go() {
1113        let ip = |s: &str| s.parse::<std::net::IpAddr>().unwrap();
1114        // Dropped pre-rules:
1115        assert!(drop_before_rules(ip("224.0.0.1")), "IPv4 multicast dropped");
1116        assert!(
1117            drop_before_rules(ip("239.255.255.250")),
1118            "IPv4 multicast (SSDP) dropped"
1119        );
1120        assert!(
1121            drop_before_rules(ip("169.254.1.1")),
1122            "IPv4 link-local dropped"
1123        );
1124        assert!(drop_before_rules(ip("ff02::1")), "IPv6 multicast dropped");
1125        assert!(drop_before_rules(ip("fe80::1")), "IPv6 link-local dropped");
1126        assert!(
1127            drop_before_rules(ip("febf:ffff::1")),
1128            "top of fe80::/10 dropped (locks the 0xffc0/0xfe80 mask)"
1129        );
1130        // Passed through to the rules:
1131        assert!(
1132            !drop_before_rules(ip("fec0::1")),
1133            "just past fe80::/10 passes (locks the 0xffc0/0xfe80 mask)"
1134        );
1135        // IPv4-mapped-IPv6 destinations match NEITHER arm and fall through to the ACL, exactly as
1136        // Go's `netip.Addr` predicates do (no unmap/canonicalize). Pinning this guards against a
1137        // future "canonicalize to be safe" refactor silently diverging from Go.
1138        assert!(
1139            !drop_before_rules(ip("::ffff:224.0.0.1")),
1140            "4in6-mapped multicast falls through to the ACL, matching Go"
1141        );
1142        assert!(
1143            !drop_before_rules(ip("::ffff:169.254.1.1")),
1144            "4in6-mapped link-local falls through to the ACL, matching Go"
1145        );
1146        assert!(
1147            !drop_before_rules(ip("100.64.0.5")),
1148            "ordinary tailnet unicast passes"
1149        );
1150        assert!(
1151            !drop_before_rules(ip("8.8.8.8")),
1152            "ordinary public unicast passes"
1153        );
1154        assert!(
1155            !drop_before_rules(ip("169.254.169.254")),
1156            "the cloud-metadata link-local address is the Go-allowlisted exception"
1157        );
1158        assert!(
1159            !drop_before_rules(ip("fd7a:115c:a1e0::1")),
1160            "IPv6 ULA (tailnet) passes"
1161        );
1162    }
1163
1164    /// A filter that drops everything (returns `None` for every packet). Lets a test prove that TSMP
1165    /// is admitted by bypassing the ACL — not by the ACL happening to allow it.
1166    struct DenyAll;
1167    impl ts_packetfilter::Filter for DenyAll {
1168        fn match_for(
1169            &self,
1170            _info: &ts_packetfilter::PacketInfo,
1171            _caps: ts_packetfilter::filter::CapIter,
1172        ) -> Option<&str> {
1173            None
1174        }
1175    }
1176
1177    /// The inbound proto-switch (Go `runIn4`/`runIn6`): TSMP is always admitted, bypassing the ACL;
1178    /// `pre()` drops still win over TSMP; non-TSMP defers to the ACL.
1179    #[test]
1180    fn tsmp_bypasses_acl_matches_go() {
1181        let ip = |s: &str| s.parse::<std::net::IpAddr>().unwrap();
1182        let src = ip("100.64.0.9");
1183        let dst = ip("100.64.0.1");
1184        let tsmp = IpProto::new(99);
1185
1186        // TSMP is accepted even though the ACL denies everything — Go `case TSMP: return Accept`.
1187        assert!(
1188            inbound_filter_verdict(&DenyAll, tsmp, src, dst, 0, None),
1189            "TSMP admitted by bypassing the (deny-all) ACL"
1190        );
1191        // A non-TSMP proto under the same deny-all ACL is dropped — proves the bypass is TSMP-specific.
1192        assert!(
1193            !inbound_filter_verdict(&DenyAll, IpProto::TCP, src, dst, 443, None),
1194            "TCP still consults the ACL (deny-all → dropped)"
1195        );
1196        // `pre()` drops outrank the TSMP accept: TSMP to a multicast/link-local dst is still dropped,
1197        // exactly as Go runs `pre()` before the proto switch.
1198        assert!(
1199            !inbound_filter_verdict(&DenyAll, tsmp, src, ip("224.0.0.1"), 0, None),
1200            "TSMP to a multicast dst is still dropped (pre() before the switch)"
1201        );
1202        assert!(
1203            !inbound_filter_verdict(&DenyAll, tsmp, src, ip("169.254.1.1"), 0, None),
1204            "TSMP to a link-local dst is still dropped (pre() before the switch)"
1205        );
1206        // IpProto::TSMP is the named constant for proto 99.
1207        assert_eq!(IpProto::TSMP, tsmp, "IpProto::TSMP == 99");
1208    }
1209
1210    /// IPv4 fragment handling, mirroring Go `net/packet.decode4` + filter `pre()`:
1211    /// - a valid later fragment (offset ≥ `MIN_FRAG_BLKS`) is ACCEPTED ahead of the ACL (Go maps it
1212    ///   to `ipproto.Fragment`, which `pre()` admits) — even under a deny-all ACL and even though its
1213    ///   parsed port is 0, which a normal rule would never match;
1214    /// - a low-offset later fragment (offset < `MIN_FRAG_BLKS`) is DROPPED (RFC 1858);
1215    /// - a first fragment (offset 0) defers to the normal proto-switch/ACL on its real port;
1216    /// - a *fragmented* TSMP first fragment (offset 0, MF set) is DROPPED (Go disallows it), unlike a
1217    ///   non-fragmented TSMP which bypasses the ACL.
1218    #[test]
1219    fn ipv4_fragment_handling_matches_go_decode4() {
1220        let ip = |s: &str| s.parse::<std::net::IpAddr>().unwrap();
1221        let src = ip("100.64.0.9");
1222        let dst = ip("100.64.0.1");
1223        let frag = |offset_blocks: u16, more_fragments: bool| {
1224            Some(Fragment::V4(Ipv4Fragment {
1225                offset_blocks,
1226                more_fragments,
1227            }))
1228        };
1229
1230        // A valid later fragment is accepted under a DENY-ALL ACL with port 0 — proves the accept is
1231        // the Go `pre()` Fragment pass-through, not the ACL happening to allow it.
1232        assert!(
1233            inbound_filter_verdict(
1234                &DenyAll,
1235                IpProto::TCP,
1236                src,
1237                dst,
1238                0,
1239                frag(MIN_FRAG_BLKS, false)
1240            ),
1241            "a valid later fragment (offset >= MIN_FRAG_BLKS) is accepted ahead of the ACL"
1242        );
1243        assert!(
1244            inbound_filter_verdict(
1245                &DenyAll,
1246                IpProto::UDP,
1247                src,
1248                dst,
1249                0,
1250                frag(MIN_FRAG_BLKS + 50, true)
1251            ),
1252            "a later fragment well past the floor (MF set) is also accepted"
1253        );
1254
1255        // A low-offset later fragment (could overlap a transport header) is dropped — RFC 1858.
1256        assert!(
1257            !inbound_filter_verdict(
1258                &DenyAll,
1259                IpProto::TCP,
1260                src,
1261                dst,
1262                0,
1263                frag(MIN_FRAG_BLKS - 1, false)
1264            ),
1265            "a low-offset later fragment is dropped (RFC 1858)"
1266        );
1267        assert!(
1268            !inbound_filter_verdict(&DenyAll, IpProto::TCP, src, dst, 0, frag(1, false)),
1269            "the smallest non-zero offset is dropped"
1270        );
1271
1272        // A first fragment (offset 0) defers to the normal ACL on its real port: deny-all drops a
1273        // TCP first fragment, exactly as it drops a non-fragmented TCP packet.
1274        assert!(
1275            !inbound_filter_verdict(&DenyAll, IpProto::TCP, src, dst, 443, frag(0, true)),
1276            "a first fragment defers to the ACL (deny-all -> dropped) on its parsed port"
1277        );
1278
1279        // A fragmented TSMP first fragment (offset 0, MF set) is dropped — Go disallows it — even
1280        // though a non-fragmented TSMP bypasses the ACL.
1281        assert!(
1282            !inbound_filter_verdict(&DenyAll, IpProto::TSMP, src, dst, 0, frag(0, true)),
1283            "a fragmented TSMP first fragment is dropped (Go parity)"
1284        );
1285        assert!(
1286            inbound_filter_verdict(&DenyAll, IpProto::TSMP, src, dst, 0, frag(0, false)),
1287            "a non-fragmented TSMP (offset 0, MF clear) still bypasses the ACL"
1288        );
1289
1290        // A *later* TSMP fragment (offset >= MIN_FRAG_BLKS) is accepted via the offset-based
1291        // fragment pass-through, NOT dropped by the fragmented-TSMP rule — that rule is offset-0
1292        // only (a first fragment with MF). This proves the later-fragment branch is proto-independent
1293        // and wins over the TSMP-specific logic (Go maps any offset>=minFragBlks to ipproto.Fragment
1294        // regardless of the L4 proto byte), locking the branch ordering against regression.
1295        assert!(
1296            inbound_filter_verdict(
1297                &DenyAll,
1298                IpProto::TSMP,
1299                src,
1300                dst,
1301                0,
1302                frag(MIN_FRAG_BLKS, true)
1303            ),
1304            "a later TSMP fragment is accepted via the fragment path (proto-independent)"
1305        );
1306    }
1307
1308    /// An ACL that admits everything, the shape a permissive "allow the whole tailnet" policy has.
1309    /// Under it, a DROP can only have come from a rule the filter applies *ahead* of the ACL — which
1310    /// is exactly what makes it the right control for the fragment classification's negative cases.
1311    struct AllowAll;
1312    impl ts_packetfilter::Filter for AllowAll {
1313        fn match_for(
1314            &self,
1315            _info: &ts_packetfilter::PacketInfo,
1316            _caps: ts_packetfilter::filter::CapIter,
1317        ) -> Option<&str> {
1318            Some("allow-all")
1319        }
1320    }
1321
1322    /// An ACL that admits exactly one destination port. An admitted packet therefore proves the
1323    /// filter read that port off the wire — the point of Go `decode6` reaching past the Fragment
1324    /// extension header to the first fragment's real transport header.
1325    struct AllowPort(u16);
1326    impl ts_packetfilter::Filter for AllowPort {
1327        fn match_for(
1328            &self,
1329            info: &ts_packetfilter::PacketInfo,
1330            _caps: ts_packetfilter::filter::CapIter,
1331        ) -> Option<&str> {
1332            (info.port == self.0).then_some("allow-port")
1333        }
1334    }
1335
1336    /// Source/destination for the IPv6 fixtures: RFC 3849 documentation addresses, standing in for
1337    /// the real ones upstream's `udp6*FragmentBuffer` fixtures use. Neither is multicast or
1338    /// link-local, so `drop_before_rules` never fires and every verdict below is the fragment
1339    /// classification's own.
1340    const IPV6_FIXTURE_SRC: std::net::Ipv6Addr =
1341        std::net::Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 5);
1342    const IPV6_FIXTURE_DST: std::net::Ipv6Addr =
1343        std::net::Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1);
1344
1345    /// The IPv6 packet a source-fragmenting host puts on the wire, in the shape of upstream's
1346    /// `udp6FirstFragmentBuffer` / `udp6NonFirstFragmentBuffer` fixtures (Go
1347    /// `net/packet/packet_test.go`): a 40-byte base header whose Next Header is the Fragment
1348    /// extension header (44), the 8-byte Fragment header itself, then `rest` — the real
1349    /// sub-protocol header on a first fragment, or continued payload on a later one.
1350    fn ipv6_fragment_packet(
1351        next_header: u8,
1352        offset_blocks: u16,
1353        more_fragments: bool,
1354        rest: &[u8],
1355    ) -> Vec<u8> {
1356        let mut buf = vec![0u8; IP6_HEADER_LEN + IP6_FRAG_HEADER_LEN + rest.len()];
1357        buf[0] = 0x60; // version 6, traffic class/flow label 0
1358        let payload_len = u16::try_from(IP6_FRAG_HEADER_LEN + rest.len()).unwrap();
1359        buf[4..6].copy_from_slice(&payload_len.to_be_bytes());
1360        buf[6] = IP6_FRAG_HEADER;
1361        buf[7] = 64; // hop limit
1362        buf[8..24].copy_from_slice(&IPV6_FIXTURE_SRC.octets());
1363        buf[24..40].copy_from_slice(&IPV6_FIXTURE_DST.octets());
1364        // Fragment extension header: Next Header, Reserved, offset<<3 | MF, Identification.
1365        buf[40] = next_header;
1366        let offset_field = (offset_blocks << 3) | u16::from(more_fragments);
1367        buf[42..44].copy_from_slice(&offset_field.to_be_bytes());
1368        buf[44..48].copy_from_slice(&[0xde, 0xad, 0xbe, 0xef]);
1369        buf[48..].copy_from_slice(rest);
1370        buf
1371    }
1372
1373    /// A plain, unfragmented IPv6/UDP packet: the same 40-byte base header the fragment fixtures
1374    /// use, but with UDP as its immediate Next Header. The control for the chained-extension-header
1375    /// fixtures below.
1376    fn ipv6_udp_packet(udp: &[u8]) -> Vec<u8> {
1377        let mut buf = vec![0u8; IP6_HEADER_LEN + udp.len()];
1378        buf[0] = 0x60; // version 6, traffic class/flow label 0
1379        buf[4..6].copy_from_slice(&u16::try_from(udp.len()).unwrap().to_be_bytes());
1380        buf[6] = 17; // Next Header = UDP
1381        buf[7] = 64; // hop limit
1382        buf[8..24].copy_from_slice(&IPV6_FIXTURE_SRC.octets());
1383        buf[24..40].copy_from_slice(&IPV6_FIXTURE_DST.octets());
1384        buf[IP6_HEADER_LEN..].copy_from_slice(udp);
1385        // Unlike a fragment fixture, this datagram is actually parsed as UDP, so its Length field
1386        // has to agree with the bytes present or etherparse rejects the packet outright.
1387        let udp_len = u16::try_from(udp.len()).unwrap();
1388        buf[IP6_HEADER_LEN + 4..IP6_HEADER_LEN + 6].copy_from_slice(&udp_len.to_be_bytes());
1389        buf
1390    }
1391
1392    /// Push one 8-byte extension header of protocol `ext_proto` in front of `inner`'s payload, so
1393    /// whatever `inner`'s base header pointed at directly is now reached through a *chain*. The
1394    /// generic Next-Header / Hdr-Ext-Len-0 / six-bytes-of-body shape is the on-the-wire layout of
1395    /// Hop-by-Hop Options (0), Routing (43) and Destination Options (60) alike.
1396    ///
1397    /// Those six body bytes are chosen so the header is well formed under *every* one of those
1398    /// three readings, not merely one etherparse happens not to look at:
1399    ///
1400    /// - as Options (0 / 60) they are a TLV stream — `1, 0` is a zero-length PadN, and the four
1401    ///   trailing zeros are four Pad1s, filling the 8-byte header exactly;
1402    /// - as Routing (43) they are Routing Type 1, **Segments Left 0**, and four bytes of
1403    ///   type-specific data. Segments Left must stay 0: `Hdr Ext Len` is 0, so there is no room
1404    ///   for a single 16-byte segment, and RFC 8200 §4.4 has a receiver that meets a non-zero
1405    ///   Segments Left on an unrecognized Routing Type discard the packet and answer ICMP
1406    ///   Parameter Problem. etherparse walks a Routing header as a raw ext header and never reads
1407    ///   the field, so a non-zero value parses here today — but a fixture that only survives
1408    ///   because the parser is lenient is one parser release away from turning the negative
1409    ///   assertions below into vacuous passes.
1410    fn ipv6_with_prepended_ext_header(ext_proto: u8, inner: &[u8]) -> Vec<u8> {
1411        let mut buf = Vec::with_capacity(inner.len() + 8);
1412        buf.extend_from_slice(&inner[..IP6_HEADER_LEN]);
1413        // The header we are displacing becomes the extension header's Next Header.
1414        let displaced = buf[6];
1415        buf[6] = ext_proto;
1416        let payload_len = u16::try_from(inner.len() - IP6_HEADER_LEN + 8).unwrap();
1417        buf[4..6].copy_from_slice(&payload_len.to_be_bytes());
1418        buf.extend_from_slice(&[displaced, 0, 1, 0, 0, 0, 0, 0]);
1419        buf.extend_from_slice(&inner[IP6_HEADER_LEN..]);
1420        buf
1421    }
1422
1423    /// An 8-byte UDP header carrying `dst_port`, as a first fragment's `rest`.
1424    fn udp_header(dst_port: u16) -> Vec<u8> {
1425        let mut hdr = vec![0u8; 8];
1426        hdr[0..2].copy_from_slice(&54276u16.to_be_bytes());
1427        hdr[2..4].copy_from_slice(&dst_port.to_be_bytes());
1428        hdr[4..6].copy_from_slice(&16u16.to_be_bytes());
1429        hdr
1430    }
1431
1432    /// The IPv6 Fragment extension-header classification, mirroring Go
1433    /// `net/packet.Parsed.decode6Fragment` plus the sub-protocol switch `decode6` runs when it
1434    /// reports `continueDecode` (upstream `4c4ec3d46`, clarified by `26b2ed0a6`). Cases are
1435    /// upstream's own `TestDecode` fixtures: `ipv6_frag_first`, `ipv6_frag_nonfirst`,
1436    /// `ipv6_frag_short_first` and `ipv6_frag_small_offset`.
1437    #[test]
1438    fn ipv6_fragment_classification_matches_go_decode6() {
1439        // `ipv6_frag_first`: offset 0 with MF set, and a whole UDP header behind the fragment
1440        // header — Go steps over the 8 bytes and reads the ports, so the ACL matches this datagram
1441        // on the same rule it would match unfragmented.
1442        assert_eq!(
1443            decode6_fragment(&ipv6_fragment_packet(17, 0, true, &udp_header(443))),
1444            Ipv6Fragment::First {
1445                proto: IpProto::UDP,
1446                dst_port: 443,
1447            },
1448            "a first fragment is decoded past the Fragment header, ports and all"
1449        );
1450
1451        // `ipv6_frag_nonfirst`: a later fragment at offset 185 blocks has no transport header at
1452        // all, so Go marks it `ipproto.Fragment` for `pre()` to pass through.
1453        assert_eq!(
1454            decode6_fragment(&ipv6_fragment_packet(17, 185, false, &[0x61; 8])),
1455            Ipv6Fragment::Later,
1456            "a later fragment at a safe offset classifies as a pass-through fragment"
1457        );
1458        // The floor itself is safe; one block below it is not. `MIN_FRAG_BLKS` is the IPv4-sized
1459        // bound upstream deliberately reuses for IPv6 (Go `26b2ed0a6`).
1460        assert_eq!(
1461            decode6_fragment(&ipv6_fragment_packet(17, MIN_FRAG_BLKS, false, &[0x61; 8])),
1462            Ipv6Fragment::Later,
1463            "offset == MIN_FRAG_BLKS is the first accepted later fragment"
1464        );
1465
1466        // `ipv6_frag_small_offset`: a later fragment whose bytes could land on top of the transport
1467        // header the head fragment was matched on — RFC 1858. Go rejects it as `unknown`.
1468        assert_eq!(
1469            decode6_fragment(&ipv6_fragment_packet(17, 1, false, &[0x61; 8])),
1470            Ipv6Fragment::Unknown,
1471            "a later fragment at offset 1 block is rejected (RFC 1858)"
1472        );
1473        assert_eq!(
1474            decode6_fragment(&ipv6_fragment_packet(
1475                17,
1476                MIN_FRAG_BLKS - 1,
1477                false,
1478                &[0x61; 8]
1479            )),
1480            Ipv6Fragment::Unknown,
1481            "one block below the floor is still rejected (RFC 1858)"
1482        );
1483
1484        // `ipv6_frag_short_first`: a first fragment truncated before its full transport header. Go
1485        // refuses to guess at the ports, because a follow-up fragment supplying the rest of that
1486        // header would otherwise carry the flow past a rule the filter never really matched.
1487        assert_eq!(
1488            decode6_fragment(&ipv6_fragment_packet(17, 0, true, &udp_header(443)[..4])),
1489            Ipv6Fragment::Unknown,
1490            "a first fragment with only half a UDP header is rejected"
1491        );
1492        assert_eq!(
1493            decode6_fragment(&ipv6_fragment_packet(6, 0, true, &[0u8; 19])),
1494            Ipv6Fragment::Unknown,
1495            "a first fragment one byte short of a TCP header is rejected"
1496        );
1497        // ...and the same header one byte longer is accepted, so the rejection is the bounds check
1498        // and not the protocol.
1499        let mut tcp = vec![0u8; 20];
1500        tcp[2..4].copy_from_slice(&443u16.to_be_bytes());
1501        assert_eq!(
1502            decode6_fragment(&ipv6_fragment_packet(6, 0, true, &tcp)),
1503            Ipv6Fragment::First {
1504                proto: IpProto::TCP,
1505                dst_port: 443,
1506            },
1507            "a complete TCP header in the first fragment is read normally"
1508        );
1509
1510        // A Fragment header truncated by the packet itself (Go's `len(b) < q.subofs+8` guard).
1511        let mut short = ipv6_fragment_packet(17, 0, true, &[]);
1512        short.truncate(IP6_HEADER_LEN + 4);
1513        short[4..6].copy_from_slice(&4u16.to_be_bytes());
1514        assert_eq!(
1515            decode6_fragment(&short),
1516            Ipv6Fragment::Unknown,
1517            "a truncated Fragment extension header is rejected"
1518        );
1519        // A packet cut off before its declared payload length (Go `len(b) < q.length`).
1520        let mut cut = ipv6_fragment_packet(17, 0, true, &udp_header(443));
1521        cut.truncate(cut.len() - 1);
1522        assert_eq!(
1523            decode6_fragment(&cut),
1524            Ipv6Fragment::Unknown,
1525            "a packet cut off before its declared IPv6 length is rejected"
1526        );
1527
1528        // Go's portless arms bounds-check but leave the port at 0, and the on-the-wire use of Go's
1529        // internal `ipproto.Fragment` sentinel (0xff) maps back to `unknown`.
1530        assert_eq!(
1531            decode6_fragment(&ipv6_fragment_packet(58, 0, true, &[0u8; 4])),
1532            Ipv6Fragment::First {
1533                proto: IpProto::ICMPV6,
1534                dst_port: 0,
1535            },
1536            "a first ICMPv6 fragment keeps port 0 and is matched IPs-only"
1537        );
1538        assert_eq!(
1539            decode6_fragment(&ipv6_fragment_packet(58, 0, true, &[0u8; 3])),
1540            Ipv6Fragment::Unknown,
1541            "a first ICMPv6 fragment shorter than the ICMPv6 header is rejected"
1542        );
1543        assert_eq!(
1544            decode6_fragment(&ipv6_fragment_packet(0xff, 0, true, &[0u8; 8])),
1545            Ipv6Fragment::Unknown,
1546            "Go's internal Fragment sentinel seen on the wire maps back to unknown"
1547        );
1548    }
1549
1550    /// The verdict Go's filter `pre()` reaches for each IPv6 fragment classification, asserted
1551    /// against an ACL that would otherwise decide the packet the other way — so each assertion can
1552    /// only be the fragment rule, never the ACL:
1553    ///
1554    /// - `Unknown` is DROPPED under an ALLOW-ALL ACL (Go `pre()`: `IPProto == Unknown → Drop`).
1555    ///   This is the security-relevant direction: an allow-all tailnet policy must not admit a
1556    ///   short-first or RFC-1858 low-offset fragment.
1557    /// - `Later` is ACCEPTED under a DENY-ALL ACL (Go `pre()`: `case ipproto.Fragment: Accept`).
1558    /// - `First` consults the ACL normally on the port read past the Fragment header.
1559    #[test]
1560    fn ipv6_fragment_verdict_matches_go_pre() {
1561        let src = std::net::IpAddr::V6(IPV6_FIXTURE_SRC);
1562        let dst = std::net::IpAddr::V6(IPV6_FIXTURE_DST);
1563        let v6 = |class| Some(Fragment::V6(class));
1564
1565        // The negative case, stated explicitly: allow-all cannot rescue an `unknown` fragment.
1566        assert!(
1567            !inbound_filter_verdict(
1568                &AllowAll,
1569                IpProto::new(0),
1570                src,
1571                dst,
1572                0,
1573                v6(Ipv6Fragment::Unknown)
1574            ),
1575            "an unknown IPv6 fragment is dropped even under an allow-all ACL"
1576        );
1577        // The control: the same allow-all ACL admits an ordinary non-fragment packet, so the drop
1578        // above is the classification and not the harness.
1579        assert!(
1580            inbound_filter_verdict(&AllowAll, IpProto::UDP, src, dst, 443, None),
1581            "the allow-all ACL does admit an ordinary packet"
1582        );
1583
1584        // A safe later fragment slides through ahead of the ACL, with nothing but port 0 to match.
1585        assert!(
1586            inbound_filter_verdict(
1587                &DenyAll,
1588                IpProto::new(0),
1589                src,
1590                dst,
1591                0,
1592                v6(Ipv6Fragment::Later)
1593            ),
1594            "a later IPv6 fragment is accepted ahead of a deny-all ACL"
1595        );
1596
1597        // A first fragment is an ordinary packet again: admitted on the port the ACL allows,
1598        // dropped on one it does not.
1599        let first = |dst_port| {
1600            v6(Ipv6Fragment::First {
1601                proto: IpProto::UDP,
1602                dst_port,
1603            })
1604        };
1605        assert!(
1606            inbound_filter_verdict(&AllowPort(443), IpProto::UDP, src, dst, 443, first(443)),
1607            "a first IPv6 fragment is matched on the port behind the Fragment header"
1608        );
1609        assert!(
1610            !inbound_filter_verdict(&AllowPort(443), IpProto::UDP, src, dst, 444, first(444)),
1611            "a first IPv6 fragment on a disallowed port is dropped by the ACL"
1612        );
1613        // Control: the same ACL decides an unfragmented packet the same way, so the two results
1614        // above are the ACL being consulted on a real port and not a fragment-specific shortcut.
1615        assert!(
1616            inbound_filter_verdict(&AllowPort(443), IpProto::UDP, src, dst, 443, None),
1617            "control: the port-scoped ACL admits an unfragmented packet to 443"
1618        );
1619        assert!(
1620            !inbound_filter_verdict(&AllowPort(443), IpProto::UDP, src, dst, 0, None),
1621            "control: port 0 - what a v6 fragment used to read as - is not admitted"
1622        );
1623
1624        // `pre()`'s multicast/link-local drops still outrank the fragment pass-through, exactly as
1625        // Go runs them before `case ipproto.Fragment`.
1626        assert!(
1627            !inbound_filter_verdict(
1628                &AllowAll,
1629                IpProto::new(0),
1630                src,
1631                "ff02::1".parse().unwrap(),
1632                0,
1633                v6(Ipv6Fragment::Later)
1634            ),
1635            "a later fragment to a multicast dst is still dropped by pre()"
1636        );
1637        assert!(
1638            !inbound_filter_verdict(
1639                &AllowAll,
1640                IpProto::new(0),
1641                src,
1642                "fe80::1".parse().unwrap(),
1643                0,
1644                v6(Ipv6Fragment::Later)
1645            ),
1646            "a later fragment to a link-local dst is still dropped by pre()"
1647        );
1648    }
1649
1650    /// The whole inbound path on real IPv6 bytes — parse, classify, verdict — which is the shape
1651    /// the bypass had: before the Fragment extension header was classified, every source-fragmented
1652    /// IPv6 datagram reached the ACL with no sub-protocol and port 0, so an allow-all rule admitted
1653    /// the RFC 1858 fragments upstream drops and a port-scoped rule blackholed the later fragments
1654    /// upstream passes through.
1655    #[test]
1656    fn ipv6_fragments_are_filtered_end_to_end() {
1657        let keep = |filter: &(dyn ts_packetfilter::Filter + Send + Sync), packet: Vec<u8>| {
1658            let mut packets = vec![PacketMut::from(packet)];
1659            let mut learned = Vec::new();
1660            filter_inbound_from_peer(filter, PeerId(3), &mut packets, &mut learned);
1661            assert!(
1662                learned.is_empty(),
1663                "no TSMP advertisement in these fixtures"
1664            );
1665            !packets.is_empty()
1666        };
1667
1668        // Under an ALLOW-ALL ACL — the permissive policy the bypass needs — the RFC 1858 fragment
1669        // must still be dropped, while the legitimate later fragment must still be delivered.
1670        assert!(
1671            !keep(&AllowAll, ipv6_fragment_packet(17, 1, false, &[0x61; 8])),
1672            "a low-offset later IPv6 fragment is dropped even by an allow-all ACL (RFC 1858)"
1673        );
1674        assert!(
1675            !keep(
1676                &AllowAll,
1677                ipv6_fragment_packet(17, 0, true, &udp_header(443)[..4])
1678            ),
1679            "a first IPv6 fragment too short to hold its UDP header is dropped by an allow-all ACL"
1680        );
1681        assert!(
1682            keep(&AllowAll, ipv6_fragment_packet(17, 185, false, &[0x61; 8])),
1683            "a legitimate later IPv6 fragment is delivered"
1684        );
1685
1686        // ...and the later fragment is delivered even under a DENY-ALL ACL, which is the Go
1687        // `pre()` pass-through and not the ACL agreeing.
1688        assert!(
1689            keep(&DenyAll, ipv6_fragment_packet(17, 185, false, &[0x61; 8])),
1690            "a legitimate later IPv6 fragment slides through a deny-all ACL (Go pre())"
1691        );
1692        assert!(
1693            !keep(&DenyAll, ipv6_fragment_packet(17, 1, false, &[0x61; 8])),
1694            "a low-offset later IPv6 fragment is dropped under a deny-all ACL too"
1695        );
1696
1697        // A first fragment is matched on the port that lives behind the Fragment extension header,
1698        // which is the whole point of stepping over it: 443 is admitted, 444 is not, under the same
1699        // port-scoped ACL. Before the port was read past the header both read as port 0 and both
1700        // were dropped.
1701        assert!(
1702            keep(
1703                &AllowPort(443),
1704                ipv6_fragment_packet(17, 0, true, &udp_header(443))
1705            ),
1706            "a first IPv6 fragment to an allowed port is delivered"
1707        );
1708        assert!(
1709            !keep(
1710                &AllowPort(443),
1711                ipv6_fragment_packet(17, 0, true, &udp_header(444))
1712            ),
1713            "a first IPv6 fragment to a disallowed port is dropped"
1714        );
1715
1716        // Scoping (Go `26b2ed0a6`): the Fragment header is parsed here ONLY as the base header's
1717        // immediate Next Header. What happens to one reached through a chained extension header —
1718        // it must fail closed, not fall through to the ACL — is
1719        // `chained_extension_header_cannot_bypass_the_ipv6_fragment_rules`.
1720    }
1721
1722    /// Prepending an extension header must not defeat the fragment rules.
1723    ///
1724    /// [`decode6_fragment`] is scoped exactly as Go scopes it: the Fragment header is parsed only
1725    /// as the base header's immediate Next Header. Go can afford that narrow scope because
1726    /// everything it does not parse *keeps the base header's Next Header* as `q.IPProto`, so a
1727    /// hop-by-hop-chained fragment is `ipproto.Unknown` and filter `pre()` drops it before the ACL
1728    /// ever runs. This tree reads the sub-protocol out of etherparse's extension-header walk
1729    /// instead, which resolves straight through the chain to the real transport number — so the
1730    /// same packet reached the ACL looking like an ordinary UDP datagram that merely happened to
1731    /// carry port 0, and a permissive "allow the whole tailnet" rule ADMITTED it. Eight bytes of
1732    /// Hop-by-Hop Options were enough to walk every RFC 1858 fragment straight past the rules the
1733    /// rest of this file exists to enforce.
1734    ///
1735    /// Every assertion is against an ALLOW-ALL ACL, so a drop can only be the fragment rule and
1736    /// never the ACL — and each extension type carries its own control that proves it: the same
1737    /// chain shape with no Fragment header in it is still delivered, on the port read past the
1738    /// extension header. That control is per-type rather than once at the end because `keep`
1739    /// cannot tell a fragment-rule drop from a parser rejection, so a fixture malformed for only
1740    /// one of the three protocols would otherwise turn that protocol's four drops into vacuous
1741    /// passes with the suite still green.
1742    #[test]
1743    fn chained_extension_header_cannot_bypass_the_ipv6_fragment_rules() {
1744        let keep = |filter: &(dyn ts_packetfilter::Filter + Send + Sync), packet: Vec<u8>| {
1745            let mut packets = vec![PacketMut::from(packet)];
1746            let mut learned = Vec::new();
1747            filter_inbound_from_peer(filter, PeerId(4), &mut packets, &mut learned);
1748            assert!(
1749                learned.is_empty(),
1750                "no TSMP advertisement in these fixtures"
1751            );
1752            !packets.is_empty()
1753        };
1754
1755        // Hop-by-Hop Options (0), Routing (43) and Destination Options (60): the fragment rules
1756        // must not depend on which header the sender chose to hide behind.
1757        for ext in [0u8, 43, 60] {
1758            // The RFC 1858 evasion itself: a later fragment whose bytes can land on top of the
1759            // transport header the head fragment was matched on.
1760            assert!(
1761                !keep(
1762                    &AllowAll,
1763                    ipv6_with_prepended_ext_header(
1764                        ext,
1765                        &ipv6_fragment_packet(17, 1, false, &[0x61; 8])
1766                    )
1767                ),
1768                "a low-offset later fragment behind extension header {ext} is dropped (RFC 1858)"
1769            );
1770            // A first fragment truncated before its own transport header, which a follow-up
1771            // fragment can then complete.
1772            assert!(
1773                !keep(
1774                    &AllowAll,
1775                    ipv6_with_prepended_ext_header(
1776                        ext,
1777                        &ipv6_fragment_packet(17, 0, true, &udp_header(443)[..4])
1778                    )
1779                ),
1780                "a short first fragment behind extension header {ext} is dropped"
1781            );
1782            // A *well-formed* chained fragment is dropped too — Go drops this whole class, so
1783            // failing closed here can never admit something upstream refuses.
1784            assert!(
1785                !keep(
1786                    &AllowAll,
1787                    ipv6_with_prepended_ext_header(
1788                        ext,
1789                        &ipv6_fragment_packet(17, 185, false, &[0x61; 8])
1790                    )
1791                ),
1792                "a chained later fragment behind extension header {ext} gets no pass-through"
1793            );
1794            assert!(
1795                !keep(
1796                    &AllowAll,
1797                    ipv6_with_prepended_ext_header(
1798                        ext,
1799                        &ipv6_fragment_packet(17, 0, true, &udp_header(443))
1800                    )
1801                ),
1802                "a chained first fragment behind extension header {ext} is dropped"
1803            );
1804
1805            // Control for THIS extension type. Every assertion above is a `!keep`, and `keep`
1806            // reports a packet the parser rejected exactly as it reports a packet the fragment
1807            // rule dropped — so on its own the block above would also pass if this builder simply
1808            // produced eight bytes etherparse refuses to walk. The same chain shape with no
1809            // Fragment header behind it is still parsed, still admitted, and still matched on the
1810            // port read past the extension header, which pins the drops to the fragment rule.
1811            let plain = ipv6_with_prepended_ext_header(ext, &ipv6_udp_packet(&udp_header(443)));
1812            assert!(
1813                keep(&AllowAll, plain.clone()),
1814                "an unfragmented packet behind extension header {ext} is still delivered"
1815            );
1816            assert!(
1817                keep(&AllowPort(443), plain),
1818                "...and is still matched on the port read past extension header {ext}"
1819            );
1820        }
1821
1822        // Contrast: the very same later fragment, reached as the base header's immediate Next
1823        // Header, is still delivered. Only the 8 prepended bytes separate this from the third
1824        // assertion above, so the drops really are the chain and not the fragment fixtures.
1825        assert!(
1826            keep(&AllowAll, ipv6_fragment_packet(17, 185, false, &[0x61; 8])),
1827            "an unchained later fragment is still delivered"
1828        );
1829    }
1830
1831    /// Build the IPv4 packet a Go peer puts on the wire for a TSMP message: a 20-byte IPv4
1832    /// header with proto 99 and `body` appended (Go `packet.Generate(IP4Header{...}, body)`,
1833    /// which is what `TSMPDiscoKeyAdvertisement.Marshal` calls). The header checksum is left
1834    /// zero — nothing on this path verifies it, and neither does Go's decoder.
1835    fn tsmp_packet4(src: [u8; 4], dst: [u8; 4], body: &[u8]) -> PacketMut {
1836        let mut buf = vec![0u8; 20 + body.len()];
1837        buf[20..].copy_from_slice(body);
1838        buf[0] = 0x45;
1839        let total_len = buf.len() as u16;
1840        buf[2..4].copy_from_slice(&total_len.to_be_bytes());
1841        buf[8] = 64;
1842        buf[9] = 99;
1843        buf[12..16].copy_from_slice(&src);
1844        buf[16..20].copy_from_slice(&dst);
1845        PacketMut::from(buf)
1846    }
1847
1848    /// A body a real Go peer sends: `'a'` then its 32-byte disco key.
1849    fn advertisement_body(key: [u8; 32]) -> Vec<u8> {
1850        let mut body = vec![ts_packet::tsmp::TSMP_TYPE_DISCO_ADVERTISEMENT];
1851        body.extend_from_slice(&key);
1852        body
1853    }
1854
1855    /// The receive side of the TSMP disco-key advertisement, at the point Go handles it: a
1856    /// well-formed advertisement is CONSUMED — the peer's key is learned and the packet is
1857    /// dropped rather than delivered to the local stack (Go `filter.DropSilently`) — while every
1858    /// other TSMP body is left alone and still admitted by the TSMP ACL bypass.
1859    ///
1860    /// The ACL here denies everything, so an admitted packet can only have come through the
1861    /// TSMP bypass, and a learned key can only have come from the advertisement path.
1862    #[test]
1863    fn tsmp_disco_key_advertisement_is_learned_and_dropped() {
1864        let peer = PeerId(7);
1865        let src = [100, 64, 0, 2];
1866        let dst = [100, 64, 0, 1];
1867        let key = [0xa5u8; 32];
1868
1869        let mut packets = vec![tsmp_packet4(src, dst, &advertisement_body(key))];
1870        let mut learned = Vec::new();
1871        filter_inbound_from_peer(&DenyAll, peer, &mut packets, &mut learned);
1872
1873        assert!(
1874            packets.is_empty(),
1875            "a consumed advertisement must not be delivered to the local stack"
1876        );
1877        assert_eq!(learned.len(), 1, "the advertisement must be harvested");
1878        assert_eq!(
1879            learned[0].0, peer,
1880            "attributed to the sending wireguard peer"
1881        );
1882        assert_eq!(learned[0].1.key, key, "the advertised disco key is learned");
1883        assert_eq!(learned[0].1.src, std::net::IpAddr::from(src));
1884
1885        // A TSMP message that is NOT an advertisement stays in the batch (Go leaves the types it
1886        // does not consume to the filter, which accepts TSMP) and teaches us nothing.
1887        let mut ping = vec![ts_packet::tsmp::TSMP_TYPE_PING];
1888        ping.extend_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8]);
1889        let mut packets = vec![tsmp_packet4(src, dst, &ping)];
1890        let mut learned = Vec::new();
1891        filter_inbound_from_peer(&DenyAll, peer, &mut packets, &mut learned);
1892        assert_eq!(packets.len(), 1, "a TSMP ping still bypasses the ACL");
1893        assert!(learned.is_empty(), "a ping advertises no disco key");
1894    }
1895
1896    /// The negative case, at the dataplane boundary: a TSMP body that is *nearly* an
1897    /// advertisement must not be half-parsed into a learned key. None of these may put anything
1898    /// in `learned` — a truncated key that was zero-padded, or a zero key that was accepted,
1899    /// would be a wrong disco key bound to a real peer.
1900    #[test]
1901    fn malformed_tsmp_disco_key_advertisements_teach_nothing() {
1902        let peer = PeerId(7);
1903        let src = [100, 64, 0, 2];
1904        let dst = [100, 64, 0, 1];
1905
1906        // A truncated advertisement: the type byte and only 31 of 32 key bytes.
1907        let mut truncated = advertisement_body([0xa5u8; 32]);
1908        truncated.truncate(32);
1909
1910        for (name, body, still_delivered) in [
1911            ("truncated advertisement", truncated, true),
1912            (
1913                "unknown TSMP type byte",
1914                {
1915                    let mut b = advertisement_body([0xa5u8; 32]);
1916                    b[0] = b'Z';
1917                    b
1918                },
1919                true,
1920            ),
1921            // A well-formed advertisement of the zero key: Go parses it but publishes only
1922            // `if !discoKeyAdvert.Key.IsZero()`, so it teaches nothing — and it is still a TSMP
1923            // message we consumed, so it is still dropped.
1924            (
1925                "zero-key advertisement",
1926                advertisement_body([0u8; 32]),
1927                false,
1928            ),
1929        ] {
1930            let mut packets = vec![tsmp_packet4(src, dst, &body)];
1931            let mut learned = Vec::new();
1932            filter_inbound_from_peer(&DenyAll, peer, &mut packets, &mut learned);
1933
1934            assert!(
1935                learned.is_empty(),
1936                "a {name} must not be half-parsed into a learned disco key"
1937            );
1938            assert_eq!(
1939                packets.len(),
1940                usize::from(still_delivered),
1941                "a {name} must {} be delivered",
1942                if still_delivered { "still" } else { "not" }
1943            );
1944        }
1945    }
1946
1947    /// Our own disco key, the one this node advertises. Asymmetric so a reversed or offset slice
1948    /// would be visible in the marshalled bytes.
1949    const SELF_DISCO_KEY: [u8; 32] = [
1950        0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff,
1951        0x00, 0x9c, 0x5f, 0x3a, 0x01, 0x7d, 0xe2, 0x44, 0xb8, 0x0f, 0x1e, 0x2d, 0x3c, 0x4b, 0x5a,
1952        0x69, 0x78,
1953    ];
1954
1955    /// An advertisement state with one peer, a v4 and a v6 address of our own, and a real disco key.
1956    fn advertisement_state(peer: PeerId, target: AdvertisementTarget) -> DiscoAdvertisementState {
1957        DiscoAdvertisementState {
1958            disco_key: SELF_DISCO_KEY,
1959            self_addrs: vec![
1960                std::net::IpAddr::from([100, 64, 0, 1]),
1961                std::net::IpAddr::from([
1962                    0xfd, 0x7a, 0x11, 0x5c, 0xa1, 0xe0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1963                ]),
1964            ],
1965            peers: HashMap::from([(peer, target)]),
1966        }
1967    }
1968
1969    /// What this node advertises, and to whom (Go `magicsock.Conn.PriorityMessageForPeer`): the
1970    /// happy path emits the exact bytes `TSMPDiscoKeyAdvertisement.Marshal` emits, and each of Go's
1971    /// refusals emits nothing at all.
1972    #[test]
1973    fn disco_advertisement_matches_priority_message_for_peer() {
1974        let peer = PeerId(3);
1975        let peer_v4 = std::net::IpAddr::from([100, 64, 0, 2]);
1976        let target = AdvertisementTarget {
1977            node_addr: peer_v4,
1978            wireguard_only: false,
1979        };
1980        let state = advertisement_state(peer, target);
1981
1982        // Happy path: a v4 peer gets a v4 advertisement sourced from our v4 address — the first
1983        // self address in the destination's family (Go `selfIPMatchingFamily`).
1984        let msg = state
1985            .advertisement_for(peer)
1986            .expect("a Tailscale peer with a matching-family address must be advertised to");
1987        let parsed = ts_packet::tsmp::DiscoKeyAdvertisement::parse(&msg)
1988            .expect("what we emit must parse as an advertisement");
1989        assert_eq!(parsed.key, SELF_DISCO_KEY, "we advertise OUR disco key");
1990        assert_eq!(parsed.src, std::net::IpAddr::from([100, 64, 0, 1]));
1991        assert_eq!(parsed.dst, peer_v4);
1992        assert_eq!(
1993            msg,
1994            ts_packet::tsmp::DiscoKeyAdvertisement {
1995                src: std::net::IpAddr::from([100, 64, 0, 1]),
1996                dst: peer_v4,
1997                key: SELF_DISCO_KEY,
1998            }
1999            .marshal()
2000            .unwrap(),
2001            "the emitted bytes are exactly what Marshal produces"
2002        );
2003
2004        // A v6 peer is sourced from our v6 address, not our v4 one.
2005        let peer_v6 = std::net::IpAddr::from([
2006            0xfd, 0x7a, 0x11, 0x5c, 0xa1, 0xe0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
2007        ]);
2008        let v6_state = advertisement_state(
2009            peer,
2010            AdvertisementTarget {
2011                node_addr: peer_v6,
2012                wireguard_only: false,
2013            },
2014        );
2015        let parsed = v6_state
2016            .advertisement_for(peer)
2017            .and_then(|m| ts_packet::tsmp::DiscoKeyAdvertisement::parse(&m))
2018            .expect("a v6 peer must be advertised to over v6");
2019        assert!(parsed.src.is_ipv6(), "source must match the peer's family");
2020        assert_eq!(parsed.dst, peer_v6);
2021
2022        // Refusal 1 (Go `disco.IsZero()`): no disco key of our own, nothing to advertise.
2023        let mut no_key = advertisement_state(peer, target);
2024        no_key.disco_key = [0u8; 32];
2025        assert!(
2026            no_key.advertisement_for(peer).is_none(),
2027            "the zero disco key must never be advertised"
2028        );
2029
2030        // Refusal 2 (Go `endpointForNodeKey` miss / `!self.Valid()`): a peer the netmap snapshot
2031        // does not cover, and a node with no addresses of its own.
2032        assert!(
2033            state.advertisement_for(PeerId(0xbad)).is_none(),
2034            "an unknown peer must not be advertised to"
2035        );
2036        let mut no_self = advertisement_state(peer, target);
2037        no_self.self_addrs.clear();
2038        assert!(
2039            no_self.advertisement_for(peer).is_none(),
2040            "a node with no tailnet address of its own has no source to advertise from"
2041        );
2042
2043        // Refusal 3 (Go `ep.isWireguardOnly`): "Do not send TSMP messages to peers that only speaks
2044        // wireguard" — such a peer would hand it to its host stack as an unknown protocol.
2045        let wg_only = advertisement_state(
2046            peer,
2047            AdvertisementTarget {
2048                node_addr: peer_v4,
2049                wireguard_only: true,
2050            },
2051        );
2052        assert!(
2053            wg_only.advertisement_for(peer).is_none(),
2054            "a WireGuard-only peer must never be sent TSMP"
2055        );
2056
2057        // Refusal 4 (Go `selfIPMatchingFamily` returning the zero Addr): an IPv4-only node has no
2058        // source address for a packet to a peer's IPv6 address.
2059        let mut v4_only = advertisement_state(
2060            peer,
2061            AdvertisementTarget {
2062                node_addr: peer_v6,
2063                wireguard_only: false,
2064            },
2065        );
2066        v4_only.self_addrs = vec![std::net::IpAddr::from([100, 64, 0, 1])];
2067        assert!(
2068            v4_only.advertisement_for(peer).is_none(),
2069            "no self address in the peer's family means no advertisement"
2070        );
2071    }
2072
2073    /// End to end, over a real WireGuard handshake: when a session with a peer comes up, this
2074    /// node's dataplane emits its own TSMP disco-key advertisement to that peer — and the peer's
2075    /// dataplane learns the key from it and drops the packet.
2076    ///
2077    /// This is the send side (Go capability version 144) meeting the receive side already in this
2078    /// tree, so the assertion is not "some bytes went out" but "the far side learned exactly the
2079    /// disco key we hold". B is deliberately left with no advertisement state, which also pins the
2080    /// unconfigured case: it establishes the same session and sends nothing back.
2081    #[test]
2082    fn session_establishment_advertises_our_disco_key_to_the_peer() {
2083        let underlay: UnderlayTransportId = 0.into();
2084        let wg_peer = ts_tunnel::PeerId(1);
2085        let peer = PeerId(1);
2086        let a_addr = std::net::IpAddr::from([100, 64, 0, 1]);
2087        let b_addr = std::net::IpAddr::from([100, 64, 0, 2]);
2088
2089        let (a_static, b_static) = (NodeKeyPair::new(), NodeKeyPair::new());
2090        let (mut a, mut b) = (
2091            DataPlane::new(a_static.clone()),
2092            DataPlane::new(b_static.clone()),
2093        );
2094
2095        for (dp, key) in [(&mut a, b_static.public), (&mut b, a_static.public)] {
2096            dp.wireguard.upsert_peer(
2097                wg_peer,
2098                ts_tunnel::PeerConfig {
2099                    key,
2100                    psk: [0u8; 32].into(),
2101                    persistent_keepalive_interval: None,
2102                },
2103            );
2104            dp.ur_out.table.insert(peer, underlay);
2105        }
2106
2107        // Only A knows how to advertise: its own disco key, its own address, and B's address.
2108        a.disco_advertisement = Some(Arc::new(advertisement_state(
2109            peer,
2110            AdvertisementTarget {
2111                node_addr: b_addr,
2112                wireguard_only: false,
2113            },
2114        )));
2115
2116        // B attributes A's tailnet address to the WireGuard peer that carries it, as the runtime's
2117        // source filter does — without that, B drops the advertisement before parsing it.
2118        let mut src_filter = ts_bart::Table::default();
2119        src_filter.insert(ipnet::IpNet::from(a_addr), peer);
2120        b.src_filter_in = Arc::new(src_filter);
2121
2122        // Drive the handshake. Only the initiation is kicked off directly (the dataplane starts one
2123        // from routed outbound traffic, which is not what this test is about); everything after it
2124        // goes through `process_inbound`, the path under test.
2125        let take = |out: HashMap<(UnderlayTransportId, PeerId), Vec<PacketMut>>| {
2126            out.into_values().flatten().collect::<Vec<_>>()
2127        };
2128        let init = a
2129            .wireguard
2130            .send([(wg_peer, vec![PacketMut::from(&b"hello"[..])])])
2131            .to_peers
2132            .remove(&wg_peer)
2133            .expect("handshake initiation");
2134
2135        let resp = take(b.process_inbound(init).to_peers);
2136        assert!(!resp.is_empty(), "B must answer the handshake initiation");
2137
2138        // A completes the handshake. Its session is now current, so alongside the queued data it
2139        // emits the advertisement.
2140        let from_a = take(a.process_inbound(resp).to_peers);
2141        assert_eq!(
2142            from_a.len(),
2143            2,
2144            "A must emit the queued data AND its disco-key advertisement"
2145        );
2146
2147        // B learns A's disco key from it, and the advertisement itself is consumed rather than
2148        // delivered to B's local stack.
2149        let inbound = b.process_inbound(from_a);
2150        assert_eq!(
2151            inbound
2152                .learned_disco_keys
2153                .iter()
2154                .map(|(peer, advert)| (*peer, advert.key))
2155                .collect::<Vec<_>>(),
2156            vec![(peer, SELF_DISCO_KEY)],
2157            "B must learn exactly the disco key A holds, attributed to A's wireguard peer"
2158        );
2159        assert!(
2160            inbound.to_peers.is_empty(),
2161            "B has no advertisement state, so it advertises nothing back"
2162        );
2163    }
2164
2165    /// Order regression: the advertisement must LEAD the traffic the same establishment released,
2166    /// not trail it.
2167    ///
2168    /// wireguard-go hands a priority message straight to the peer's *outbound* queue
2169    /// (`SendPriorityMessage` → `queueOutboundIfRunning`) and runs it before the flush that
2170    /// follows at both call sites — `peer.SendPriorityMessage()` ahead of `peer.SendKeepalive()`
2171    /// on the initiator and ahead of `peer.SendStagedPackets()` on the responder
2172    /// (`device/receive.go`) — so the advertisement is the first thing on the wire once a keypair
2173    /// becomes current. In this tree the flush has already happened inside `Endpoint::recv` by the
2174    /// time the advertisement exists, so `process_inbound` has to splice it in front; appending it
2175    /// would put it behind up to `MAX_QUEUED_PER_PEER` packets of queued traffic.
2176    ///
2177    /// The order is read off B's *decrypted* stream — its capture tee, which sees every inbound
2178    /// packet before any filtering — so what is pinned is the order the peer actually observes,
2179    /// not the order of a local vector.
2180    #[test]
2181    fn the_advertisement_leads_the_traffic_released_by_the_same_establishment() {
2182        let underlay: UnderlayTransportId = 0.into();
2183        let wg_peer = ts_tunnel::PeerId(1);
2184        let peer = PeerId(1);
2185        let a_addr = std::net::IpAddr::from([100, 64, 0, 1]);
2186        let b_addr = std::net::IpAddr::from([100, 64, 0, 2]);
2187
2188        let (a_static, b_static) = (NodeKeyPair::new(), NodeKeyPair::new());
2189        let (mut a, mut b) = (
2190            DataPlane::new(a_static.clone()),
2191            DataPlane::new(b_static.clone()),
2192        );
2193
2194        for (dp, key) in [(&mut a, b_static.public), (&mut b, a_static.public)] {
2195            dp.wireguard.upsert_peer(
2196                wg_peer,
2197                ts_tunnel::PeerConfig {
2198                    key,
2199                    psk: [0u8; 32].into(),
2200                    persistent_keepalive_interval: None,
2201                },
2202            );
2203            dp.ur_out.table.insert(peer, underlay);
2204        }
2205
2206        a.disco_advertisement = Some(Arc::new(advertisement_state(
2207            peer,
2208            AdvertisementTarget {
2209                node_addr: b_addr,
2210                wireguard_only: false,
2211            },
2212        )));
2213
2214        let mut src_filter = ts_bart::Table::default();
2215        src_filter.insert(ipnet::IpNet::from(a_addr), peer);
2216        b.src_filter_in = Arc::new(src_filter);
2217
2218        // Everything B decrypts, in arrival order, before any filtering runs.
2219        let recorded: CaptureLog = Arc::new(Mutex::new(Vec::new()));
2220        let sink = recorded.clone();
2221        b.capture = Some(Arc::new(move |path: CapturePath, bytes: &[u8]| {
2222            sink.lock().unwrap().push((path, bytes.to_vec()));
2223        }));
2224
2225        let take = |out: HashMap<(UnderlayTransportId, PeerId), Vec<PacketMut>>| {
2226            out.into_values().flatten().collect::<Vec<_>>()
2227        };
2228
2229        // Traffic for a peer with no session yet: it stages, and a handshake starts.
2230        const QUEUED: &[u8] = b"staged while the session was still coming up";
2231        let init = a
2232            .wireguard
2233            .send([(wg_peer, vec![PacketMut::from(QUEUED)])])
2234            .to_peers
2235            .remove(&wg_peer)
2236            .expect("handshake initiation");
2237        let resp = take(b.process_inbound(init).to_peers);
2238
2239        // A's keypair becomes current here, which both flushes the staged packet and produces the
2240        // advertisement — the batch whose order is under test.
2241        let from_a = take(a.process_inbound(resp).to_peers);
2242        assert_eq!(
2243            from_a.len(),
2244            2,
2245            "A must emit the queued data AND its disco-key advertisement"
2246        );
2247
2248        // Hand them to B in exactly the order A produced them.
2249        let learned = b.process_inbound(from_a).learned_disco_keys;
2250        assert_eq!(
2251            learned
2252                .iter()
2253                .map(|(peer, advert)| (*peer, advert.key))
2254                .collect::<Vec<_>>(),
2255            vec![(peer, SELF_DISCO_KEY)],
2256            "B must still learn A's disco key"
2257        );
2258
2259        let advertisement = ts_packet::tsmp::DiscoKeyAdvertisement {
2260            src: a_addr,
2261            dst: b_addr,
2262            key: SELF_DISCO_KEY,
2263        }
2264        .marshal()
2265        .expect("a v4 advertisement between two v4 addresses marshals");
2266
2267        let captured = recorded.lock().unwrap();
2268        let from_peer = captured
2269            .iter()
2270            .filter(|(path, _)| *path == CapturePath::FromPeer)
2271            .map(|(_, bytes)| bytes.as_slice())
2272            .collect::<Vec<_>>();
2273        assert_eq!(from_peer.len(), 2, "B must decrypt both of A's packets");
2274        // The send path zero-pads each payload up to a 16-byte boundary and the receiver delivers
2275        // it with that padding intact (see `session::PADDING_MULTIPLE`), so compare on the leading
2276        // bytes rather than for equality.
2277        assert!(
2278            from_peer[0].starts_with(&advertisement),
2279            "the advertisement must reach the peer FIRST, ahead of the traffic the same \
2280             establishment released"
2281        );
2282        assert!(
2283            from_peer[1].starts_with(QUEUED),
2284            "the queued traffic follows the advertisement"
2285        );
2286    }
2287
2288    /// Behavioral guard: an installed capture hook MUST be invoked with `CapturePath::FromLocal`
2289    /// and the exact packet bytes for every outbound packet. The tee sits at the top of
2290    /// `process_outbound`, before `or_out.route` consumes the packets, so it fires regardless of
2291    /// whether a wireguard peer exists (an empty router just drops the routed packets afterward).
2292    /// This is the only end-to-end guard that the dataplane capture tee actually fires; a refactor
2293    /// that drops the tee would leave every byte-layout test green.
2294    #[test]
2295    fn capture_hook_fires_on_outbound() {
2296        let mut dp = DataPlane::new(NodeKeyPair::new());
2297
2298        let recorded: CaptureLog = Arc::new(Mutex::new(Vec::new()));
2299        let sink = recorded.clone();
2300        dp.capture = Some(Arc::new(move |path: CapturePath, bytes: &[u8]| {
2301            sink.lock().unwrap().push((path, bytes.to_vec()));
2302        }));
2303
2304        // The outbound tee passes `p.as_ref()` as-given; the bytes need not be a valid IP packet.
2305        let payload: Vec<u8> = vec![0xde, 0xad, 0xbe, 0xef];
2306        let packet = PacketMut::from(payload.clone());
2307
2308        drop(dp.process_outbound(vec![packet]));
2309
2310        let captured = recorded.lock().unwrap();
2311        assert_eq!(captured.len(), 1, "hook must fire exactly once per packet");
2312        assert_eq!(captured[0].0, CapturePath::FromLocal);
2313        assert_eq!(captured[0].1, payload);
2314    }
2315
2316    /// A minimal IPv4/UDP datagram from `src` to `dst`. The control for the outbound TSMP refusal:
2317    /// same source, same destination, same batch as the forged advertisement — only the protocol
2318    /// byte differs.
2319    fn v4_udp_packet(src: std::net::IpAddr, dst: std::net::IpAddr, payload: &[u8]) -> Vec<u8> {
2320        let (std::net::IpAddr::V4(src), std::net::IpAddr::V4(dst)) = (src, dst) else {
2321            panic!("v4_udp_packet needs two IPv4 addresses");
2322        };
2323        let total_len = u16::try_from(IP4_HEADER_LEN + 8 + payload.len()).unwrap();
2324        let mut buf = vec![0u8; usize::from(total_len)];
2325        buf[0] = 0x45; // version 4, IHL 5 (no options)
2326        buf[2..4].copy_from_slice(&total_len.to_be_bytes());
2327        buf[8] = 64; // TTL
2328        buf[9] = 17; // UDP
2329        buf[12..16].copy_from_slice(&src.octets());
2330        buf[16..20].copy_from_slice(&dst.octets());
2331        buf[20..22].copy_from_slice(&4242u16.to_be_bytes()); // source port
2332        buf[22..24].copy_from_slice(&4343u16.to_be_bytes()); // destination port
2333        let udp_len = u16::try_from(8 + payload.len()).unwrap();
2334        buf[24..26].copy_from_slice(&udp_len.to_be_bytes());
2335        // UDP checksum left 0 ("not computed"), which is legal for IPv4.
2336        buf[IP4_HEADER_LEN + 8..].copy_from_slice(payload);
2337        buf
2338    }
2339
2340    /// What `process_outbound` refuses, mirroring the `p.IPProto == ipproto.TSMP` arm of Go
2341    /// `tstun.filterPacketOutboundToWireGuard` — plus the three shapes this tree drops that Go's
2342    /// TSMP arm alone does not, because there is no outbound ACL behind it here to refuse them as
2343    /// `ipproto.Unknown`. See [`outbound_packet_carries_tsmp`].
2344    #[test]
2345    fn outbound_tsmp_classification_matches_go_decode() {
2346        let v4_src = std::net::IpAddr::from([100, 64, 0, 1]);
2347        let v4_dst = std::net::IpAddr::from([100, 64, 0, 2]);
2348        let v4 = ts_packet::tsmp::DiscoKeyAdvertisement {
2349            src: v4_src,
2350            dst: v4_dst,
2351            key: SELF_DISCO_KEY,
2352        }
2353        .marshal()
2354        .expect("a v4 advertisement between two v4 addresses marshals");
2355        let v6 = ts_packet::tsmp::DiscoKeyAdvertisement {
2356            src: std::net::IpAddr::V6(IPV6_FIXTURE_SRC),
2357            dst: std::net::IpAddr::V6(IPV6_FIXTURE_DST),
2358            key: SELF_DISCO_KEY,
2359        }
2360        .marshal()
2361        .expect("a v6 advertisement between two v6 addresses marshals");
2362
2363        // The forgery this exists to stop, in both families: bytes byte-identical to what this node
2364        // would itself emit, handed to us by the host instead.
2365        assert!(
2366            outbound_packet_carries_tsmp(&v4),
2367            "an IPv4 TSMP packet from the host is refused"
2368        );
2369        assert!(
2370            outbound_packet_carries_tsmp(&v6),
2371            "an IPv6 TSMP packet from the host is refused"
2372        );
2373
2374        // Ordinary traffic is untouched — the refusal is protocol-specific, not a blanket drop.
2375        assert!(
2376            !outbound_packet_carries_tsmp(&v4_udp_packet(v4_src, v4_dst, b"hello")),
2377            "IPv4 UDP passes"
2378        );
2379        assert!(
2380            !outbound_packet_carries_tsmp(&ipv6_udp_packet(&udp_header(53))),
2381            "IPv6 UDP passes"
2382        );
2383
2384        // Go demotes a *fragmented* IPv4 TSMP packet to `ipproto.Unknown`, which its outbound ACL
2385        // then drops for "unknown proto". With no outbound ACL here the protocol byte is the whole
2386        // verdict, so the refusal happens one step earlier and the packet still never ships.
2387        let mut fragmented = v4.clone();
2388        fragmented[6] = 0x20; // More Fragments
2389        assert!(
2390            outbound_packet_carries_tsmp(&fragmented),
2391            "a fragmented IPv4 TSMP packet is refused too"
2392        );
2393
2394        // An IPv6 Fragment extension header naming TSMP: Go classifies the head fragment TSMP and
2395        // its followers `ipproto.Fragment`. Both are refused here — every fragment of one datagram
2396        // repeats the same Next Header, and with the head refused no peer could reassemble anyway.
2397        assert!(
2398            outbound_packet_carries_tsmp(&ipv6_fragment_packet(
2399                ts_packet::tsmp::IP_PROTO_TSMP,
2400                0,
2401                true,
2402                &[b'a'; 33],
2403            )),
2404            "the head fragment of an IPv6 TSMP datagram is refused"
2405        );
2406        assert!(
2407            outbound_packet_carries_tsmp(&ipv6_fragment_packet(
2408                ts_packet::tsmp::IP_PROTO_TSMP,
2409                MIN_FRAG_BLKS,
2410                false,
2411                &[0u8; 8],
2412            )),
2413            "so are its later fragments"
2414        );
2415        assert!(
2416            !outbound_packet_carries_tsmp(&ipv6_fragment_packet(17, 0, true, &udp_header(53))),
2417            "a fragmented IPv6 UDP datagram is not TSMP and still passes"
2418        );
2419
2420        // Nothing to classify: not IP at all, or truncated before the protocol byte can be trusted.
2421        assert!(
2422            !outbound_packet_carries_tsmp(&[]),
2423            "the empty buffer passes"
2424        );
2425        assert!(
2426            !outbound_packet_carries_tsmp(&[0xde, 0xad, 0xbe, 0xef]),
2427            "a non-IP buffer passes (the router drops it for want of a destination)"
2428        );
2429        assert!(
2430            !outbound_packet_carries_tsmp(&v4[..IP4_HEADER_LEN - 1]),
2431            "an IPv4 packet cut off inside its header passes"
2432        );
2433        assert!(
2434            !outbound_packet_carries_tsmp(&v6[..IP6_HEADER_LEN - 1]),
2435            "an IPv6 packet cut off inside its header passes"
2436        );
2437    }
2438
2439    /// The whole point of the outbound TSMP refusal, end to end, together with the negative case
2440    /// that keeps it from silently disabling capability version 144.
2441    ///
2442    /// A local process writes a well-formed disco-key advertisement — naming a disco key of its own
2443    /// choosing, addressed to a peer whose route really does resolve to a live WireGuard session —
2444    /// into the tun. The peer must never see it: it arrives inside this node's session from this
2445    /// node's tailnet address, so it is indistinguishable from one this node meant to send, and the
2446    /// peer would bind the forger's key for us. Ordinary traffic in the same batch to the same
2447    /// destination must be untouched.
2448    ///
2449    /// And the advertisement this node itself sends must still go out. It is built by
2450    /// `DiscoAdvertisementState::advertisement_for` and injected by `process_inbound` on session
2451    /// establishment, *below* the refusal — Go has the same relationship, where `injectedRead`
2452    /// bypasses the outbound filter. Without this half of the test a drop placed one layer too low
2453    /// would look green.
2454    #[test]
2455    fn host_written_tsmp_is_dropped_while_our_own_advertisement_still_goes_out() {
2456        let underlay: UnderlayTransportId = 0.into();
2457        let wg_peer = ts_tunnel::PeerId(1);
2458        let peer = PeerId(1);
2459        let a_addr = std::net::IpAddr::from([100, 64, 0, 1]);
2460        let b_addr = std::net::IpAddr::from([100, 64, 0, 2]);
2461
2462        let (a_static, b_static) = (NodeKeyPair::new(), NodeKeyPair::new());
2463        let (mut a, mut b) = (
2464            DataPlane::new(a_static.clone()),
2465            DataPlane::new(b_static.clone()),
2466        );
2467
2468        for (dp, key) in [(&mut a, b_static.public), (&mut b, a_static.public)] {
2469            dp.wireguard.upsert_peer(
2470                wg_peer,
2471                ts_tunnel::PeerConfig {
2472                    key,
2473                    psk: [0u8; 32].into(),
2474                    persistent_keepalive_interval: None,
2475                },
2476            );
2477            dp.ur_out.table.insert(peer, underlay);
2478        }
2479
2480        a.disco_advertisement = Some(Arc::new(advertisement_state(
2481            peer,
2482            AdvertisementTarget {
2483                node_addr: b_addr,
2484                wireguard_only: false,
2485            },
2486        )));
2487
2488        // A routes B's tailnet address to the wireguard peer, so a host-written packet addressed to
2489        // B really would be encrypted and shipped were it not refused. Without this the test would
2490        // pass on an empty routing table and prove nothing.
2491        let mut routes = ts_bart::Table::default();
2492        routes.insert(
2493            ipnet::IpNet::from(b_addr),
2494            or::outbound::RouteAction::Wireguard(peer),
2495        );
2496        a.or_out.swap(routes);
2497
2498        // B attributes A's tailnet address to the wireguard peer that carries it, as the runtime's
2499        // source filter does.
2500        let mut src_filter = ts_bart::Table::default();
2501        src_filter.insert(ipnet::IpNet::from(a_addr), peer);
2502        b.src_filter_in = Arc::new(src_filter);
2503
2504        // Everything B decrypts, in arrival order, before any filtering runs.
2505        let recorded: CaptureLog = Arc::new(Mutex::new(Vec::new()));
2506        let sink = recorded.clone();
2507        b.capture = Some(Arc::new(move |path: CapturePath, bytes: &[u8]| {
2508            sink.lock().unwrap().push((path, bytes.to_vec()));
2509        }));
2510
2511        let take = |out: HashMap<(UnderlayTransportId, PeerId), Vec<PacketMut>>| {
2512            out.into_values().flatten().collect::<Vec<_>>()
2513        };
2514
2515        // Establish the session. A's own advertisement rides the establishment.
2516        let init = a
2517            .wireguard
2518            .send([(wg_peer, vec![PacketMut::from(&b"hello"[..])])])
2519            .to_peers
2520            .remove(&wg_peer)
2521            .expect("handshake initiation");
2522        let resp = take(b.process_inbound(init).to_peers);
2523        let from_a = take(a.process_inbound(resp).to_peers);
2524        let learned = b.process_inbound(from_a).learned_disco_keys;
2525        assert_eq!(
2526            learned
2527                .iter()
2528                .map(|(peer, advert)| (*peer, advert.key))
2529                .collect::<Vec<_>>(),
2530            vec![(peer, SELF_DISCO_KEY)],
2531            "our own advertisement must still reach the peer: it is injected below process_outbound"
2532        );
2533
2534        // Now the forgery, alongside ordinary traffic to the same destination in the same batch.
2535        const FORGED_KEY: [u8; 32] = [0xff; 32];
2536        let forged = ts_packet::tsmp::DiscoKeyAdvertisement {
2537            src: a_addr,
2538            dst: b_addr,
2539            key: FORGED_KEY,
2540        }
2541        .marshal()
2542        .expect("a v4 advertisement between two v4 addresses marshals");
2543        const CARRIED: &[u8] = b"ordinary traffic in the same batch";
2544        let control = v4_udp_packet(a_addr, b_addr, CARRIED);
2545
2546        // This is the only test that increments this counter, so the delta is exact.
2547        let counted_before = metric_out_to_wg_drop_tsmp().value();
2548        let out = a.process_outbound(vec![
2549            PacketMut::from(&forged[..]),
2550            PacketMut::from(&control[..]),
2551        ]);
2552
2553        let mark = recorded.lock().unwrap().len();
2554        let inbound = b.process_inbound(take(out.to_peers));
2555        assert!(
2556            inbound.learned_disco_keys.is_empty(),
2557            "the forged advertisement must never reach the peer, or it binds the forger's key for us"
2558        );
2559
2560        let captured = recorded.lock().unwrap();
2561        let delivered = captured[mark..]
2562            .iter()
2563            .filter(|(path, _)| *path == CapturePath::FromPeer)
2564            .map(|(_, bytes)| bytes.as_slice())
2565            .collect::<Vec<_>>();
2566        assert_eq!(
2567            delivered.len(),
2568            1,
2569            "exactly the one non-TSMP packet of the batch crosses the tunnel"
2570        );
2571        // The send path zero-pads each payload up to a 16-byte boundary and the receiver delivers it
2572        // with that padding intact (see `session::PADDING_MULTIPLE`), so compare on the leading bytes.
2573        assert!(
2574            delivered[0].starts_with(&control),
2575            "and it is the ordinary traffic, unaltered"
2576        );
2577
2578        assert_eq!(
2579            metric_out_to_wg_drop_tsmp().value(),
2580            counted_before + 1,
2581            "the drop is counted in tstun_out_to_wg_drop_tsmp (Go metricPacketOutDropTSMP)"
2582        );
2583    }
2584}