lanes.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. package nebula
  2. import (
  3. "context"
  4. "hash/fnv"
  5. "log/slog"
  6. "net/netip"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  10. "github.com/flynn/noise"
  11. "github.com/rcrowley/go-metrics"
  12. "github.com/slackhq/nebula/cert"
  13. "github.com/slackhq/nebula/firewall"
  14. "github.com/slackhq/nebula/handshake"
  15. "github.com/slackhq/nebula/header"
  16. "github.com/slackhq/nebula/noiseutil"
  17. )
  18. // Multiport lanes give one tunnel several underlay 5-tuples, so its traffic
  19. // spreads over ECMP paths, NIC receive queues and per-flow policers instead of
  20. // funnelling through a single flow. Each inside flow picks a lane by hashing its
  21. // own 5-tuple, so the spread doesn't depend on how a kernel steers tun queues
  22. // (see txQueue).
  23. //
  24. // A lane is not a second tunnel: it is an extra session on the same HostInfo.
  25. // Noise leaves us with A.eKey == B.dKey, so both sides expand the same two keys
  26. // with the same per-lane label and land on a matched pair without exchanging
  27. // anything. A lane therefore costs no handshake, has no half-established state,
  28. // and dies exactly when its base tunnel does. Which lane a packet belongs to
  29. // travels in the nebula header, inside the AEAD's associated data.
  30. //
  31. // Lane 0 is the base tunnel itself: HostInfo.ConnectionState, the base port, and
  32. // the peer's real remote address, and it carries its share of flows like any
  33. // other. Lane s > 0 egresses a socket on listen.port+s (see laneSock) toward the
  34. // peer's advertised port range. Receiving on a lane
  35. // needs no permission — the keys are derivable the moment the base handshake
  36. // completes — but sending on one needs proof the new 5-tuple actually works,
  37. // since nothing else would notice a middlebox quietly dropping it. So a lane
  38. // stays down until a probe on it is acked, and falls back to the base tunnel the
  39. // moment it stops being acked.
  40. //
  41. // Receive is pay-per-use. A lane we only receive on gets its session on the
  42. // first packet that arrives on it, because how many lanes exist is partly the
  43. // peer's call: it advertises how many it sends on, and we have to be able to
  44. // receive all of them. Deriving them all up front would let a peer advertising
  45. // the maximum cost us a replay window and two cipher states per lane, per
  46. // tunnel, for lanes it may never send on. A lane we send on gets its session
  47. // from its first probe, and every such lane is probed on the tunnel's first
  48. // tick with traffic.
  49. const (
  50. // laneKeyInfo is the HKDF label prefix for lane key expansion. Changing it
  51. // means older builds derive different keys and drop our lane traffic; the
  52. // base tunnel would keep working, so the failure would be a silent loss of
  53. // lanes rather than of connectivity.
  54. laneKeyInfo = "nebula multiport lane v1"
  55. // laneRetryBase and laneRetryMax bound the backoff between probes of a lane
  56. // that will not come up, so a peer whose lane ports are firewalled costs one
  57. // packet a minute rather than one per traffic tick.
  58. laneRetryBase = 5 * time.Second
  59. laneRetryMax = 60 * time.Second
  60. // laneMaxFails caps the failure counter; the backoff saturates well before.
  61. laneMaxFails = 8
  62. // laneWarnFails is how many unanswered probes a lane that has never come up
  63. // takes before it is worth a warning. One or two can be loss; this many in a
  64. // row is usually a firewall that only opens the base port.
  65. laneWarnFails = 3
  66. // laneProbeTimeout is how long a probe may go unacked before it counts as a
  67. // failure. It is shorter than the connection manager's check interval on
  68. // purpose: an outstanding probe is judged on the next tick either way, and a
  69. // longer timeout would only delay that by a whole tick.
  70. laneProbeTimeout = 2 * time.Second
  71. // laneKeepalive is how often a lane that is up re-proves its path. Traffic
  72. // on a lane is not evidence the lane works — that is the whole reason lanes
  73. // need probing — so a lane that silently breaks is only caught here.
  74. laneKeepalive = 30 * time.Second
  75. )
  76. // laneSet holds a peer's lane sessions and the state deciding which lanes may
  77. // carry traffic. It is built when the base handshake completes and never
  78. // resized, so the slices and their lengths are immutable; mu guards the fields
  79. // under it, and sessions/txAddr/demand are atomics read by the data plane
  80. // without it.
  81. type laneSet struct {
  82. // sessions[s] holds lane s's session once something has needed it, and nil
  83. // until then. sessions[0] is never populated: lane 0 is the base tunnel's own
  84. // ConnectionState. The length is immutable, so the data plane bounds-checks
  85. // and loads with no locking.
  86. sessions []atomic.Pointer[ConnectionState]
  87. // material is what a lane session is derived from, kept because sessions are
  88. // derived lazily and the handshake result is long gone by then.
  89. material laneMaterial
  90. // txAddr[s] holds lane s's remote address while the lane is proven usable
  91. // and nil otherwise. This single atomic is both the TX gate and the
  92. // destination, so a routine that loads non-nil has everything it needs.
  93. // Sized txLanes: lanes above that never send.
  94. txAddr []atomic.Pointer[netip.AddrPort]
  95. // demand[s] is raised at creation, and again by the TX path whenever a flow
  96. // hashes onto lane s while it is down. Probing is demand-driven, so a peer we
  97. // never send to costs nothing beyond its base tunnel no matter how many lanes
  98. // are configured, and a lane that keeps failing is only retried while
  99. // something still wants it. Sized txLanes.
  100. demand []atomic.Bool
  101. // txLanes is how many lanes we may send on — our lane count clamped to the
  102. // ports the peer bound — and so the modulus a flow's hash is reduced by.
  103. // Lanes from txLanes up can only receive, which is how a peer with more
  104. // ports than us still spreads its own traffic.
  105. // Immutable, and the length of every TX-side slice here.
  106. txLanes int
  107. mu sync.Mutex
  108. // peerPortCount and peerBasePort are the peer's advertised port range and
  109. // portOffset is this pair's rotation within it: lane s targets
  110. // peerBasePort + ((s + portOffset) % peerPortCount).
  111. peerPortCount uint16
  112. peerBasePort uint16
  113. portOffset uint16
  114. // laneBias rotates the flow hash before it picks a lane, so the two sides of
  115. // a flow land on lanes that are each other's partner rather than at
  116. // independent points in the range. See newLaneSet.
  117. laneBias uint16
  118. // peerAddr is the address the current lane targets were built from. The
  119. // peer's lane ports have no derivable relationship to a new NAT mapping, so
  120. // a roam invalidates every lane rather than moving it.
  121. peerAddr netip.Addr
  122. // probe[s] is lane s's probe and backoff state. Sized txLanes.
  123. probe []laneProbeState
  124. }
  125. // laneMaterial is everything a lane session is derived from. The two base keys
  126. // are the same secret the base tunnel's own cipher states already hold — the
  127. // noiseutil.CipherState interface just doesn't hand them back, so a lane set
  128. // keeps its own copy rather than a reference to the session.
  129. type laneMaterial struct {
  130. eKey, dKey [32]byte
  131. cipher noise.CipherFunc
  132. myCert cert.Certificate
  133. peerCert *cert.CachedCertificate
  134. initiator bool
  135. }
  136. type laneProbeState struct {
  137. // gen is the generation of the last probe sent, echoed in the ack so a late
  138. // ack cannot promote a lane on the strength of a superseded probe.
  139. gen uint8
  140. // fails is the consecutive failure count driving retryAt.
  141. fails uint8
  142. // sentAt is when the outstanding probe went out, zero when none is pending.
  143. sentAt time.Time
  144. // target is where the outstanding probe went, promoted to txAddr on ack. It
  145. // outlives the probe, which is what lets a demotion log the address that
  146. // stopped answering.
  147. target netip.AddrPort
  148. // lastAck is when the lane was last confirmed usable, driving the keepalive.
  149. lastAck time.Time
  150. // retryAt is the earliest we may probe this lane again.
  151. retryAt time.Time
  152. }
  153. // validLaneAdvert reports whether a peer's advertised port range is one we can
  154. // aim lanes at: a real base port, and every port in the range a valid one.
  155. func validLaneAdvert(basePort, portCount uint32) bool {
  156. return basePort != 0 && portCount != 0 && basePort+portCount-1 <= 0xffff
  157. }
  158. // newLaneSet sets up the lanes for a freshly completed base handshake. It
  159. // returns nil when the pair has no lane beyond the base tunnel, which is the
  160. // normal answer for a peer running without multiport. No session is derived
  161. // here; each is derived on the first packet that needs it.
  162. func newLaneSet(r *handshake.Result, myLanes int, myAddr, peerAddr netip.Addr) *laneSet {
  163. // PeerPortCount and PeerBasePort are already bounded to uint16 by the
  164. // handshake payload parser. A zero port count is a peer that did not
  165. // advertise multiport at all, so there is no lane to be had in either
  166. // direction.
  167. peerPorts := uint16(r.PeerPortCount)
  168. if peerPorts == 0 {
  169. return nil
  170. }
  171. // Sessions have to cover both directions: we send on our lanes and receive
  172. // on the peer's, and one derived session serves both ends of a lane index.
  173. // Only the session table is sized by the peer's advertised count; the TX-side
  174. // state is sized by what we will actually send on.
  175. n := min(max(myLanes, int(r.PeerTxLanes)), header.MaxLane+1)
  176. if n < 2 {
  177. return nil
  178. }
  179. txLanes := min(myLanes, int(peerPorts), n)
  180. offset := lanePortOffset(myAddr, peerAddr, peerPorts)
  181. // A flow picks its lane from a hash both sides compute identically, so with
  182. // the ranges lined up the two directions of a flow would pick the same lane
  183. // index — and lane s targets the peer's lane (s + portOffset), not lane s. The
  184. // high-addressed side rotates its choice by the low side's offset, which is
  185. // its own negated, so the two directions land on partner lanes and their
  186. // 4-tuples are exact reverses: each side's traffic then arrives through the
  187. // conntrack entry the other's probe opened. With mismatched ranges there are
  188. // no partner lanes to find, so don't pretend: hash straight.
  189. bias := uint16(0)
  190. if txLanes == int(peerPorts) && peerAddr.Less(myAddr) {
  191. bias = (peerPorts - offset) % peerPorts
  192. }
  193. ls := &laneSet{
  194. sessions: make([]atomic.Pointer[ConnectionState], n),
  195. material: laneMaterial{
  196. eKey: r.EKey.UnsafeKey(),
  197. dKey: r.DKey.UnsafeKey(),
  198. cipher: r.Cipher,
  199. myCert: r.MyCert,
  200. peerCert: r.RemoteCert,
  201. initiator: r.Initiator,
  202. },
  203. txAddr: make([]atomic.Pointer[netip.AddrPort], txLanes),
  204. demand: make([]atomic.Bool, txLanes),
  205. probe: make([]laneProbeState, txLanes),
  206. txLanes: txLanes,
  207. peerPortCount: peerPorts,
  208. peerBasePort: uint16(r.PeerBasePort),
  209. portOffset: offset,
  210. laneBias: bias,
  211. }
  212. // Every lane starts out demanded, so the first traffic tick on this tunnel
  213. // probes all of them at once instead of waiting for a flow to hash onto each.
  214. // Lanes have to be up *before* the flows are, not after: the peer writes a
  215. // flow's inbound packets to the tun queue matching the socket they arrived on,
  216. // and the kernel remembers that for as long as the flow stays busy. A flow that
  217. // starts while the lanes are still down therefore gets pinned to queue 0 on
  218. // both hosts for its whole life. This costs one probe per lane on any tunnel
  219. // with traffic; an idle tunnel is never probed, so it still costs nothing.
  220. for s := 1; s < txLanes; s++ {
  221. ls.demand[s].Store(true)
  222. }
  223. return ls
  224. }
  225. // laneLogAttr summarizes what a tunnel negotiated, for the handshake log lines.
  226. // It is an empty attr, which slog drops, on a node not running multiport. A peer
  227. // that negotiated no lanes still logs, with zeros: "we offered and got nothing"
  228. // is exactly what you want to see when you expected lanes and have none.
  229. func laneLogAttr(myLanes int, ls *laneSet) slog.Attr {
  230. if myLanes == 0 {
  231. return slog.Attr{}
  232. }
  233. if ls == nil {
  234. return slog.Any("lanes", m{"tx": 0, "sessions": 0})
  235. }
  236. // Every field read here is immutable once the set is built.
  237. return slog.Any("lanes", m{
  238. "tx": ls.txLanes,
  239. "sessions": len(ls.sessions),
  240. "peerBasePort": ls.peerBasePort,
  241. "peerPorts": ls.peerPortCount,
  242. "portOffset": ls.portOffset,
  243. })
  244. }
  245. // emitLaneStats reports how many lanes are carrying traffic and how many tunnels
  246. // have any. Both are counted by walking the hostmap, because a counter kept at
  247. // promotion and demotion would drift upward forever: a tunnel torn down while its
  248. // lanes are up never demotes them. Only a node running multiport pays for the
  249. // walk.
  250. func (f *Interface) emitLaneStats(up, tunnels metrics.Gauge) {
  251. var nUp, nTunnels int64
  252. f.hostMap.ForEachIndex(func(hostinfo *HostInfo) {
  253. ls := hostinfo.lanes
  254. if ls == nil {
  255. return
  256. }
  257. nTunnels++
  258. for s := 1; s < ls.txLanes; s++ {
  259. if ls.txAddr[s].Load() != nil {
  260. nUp++
  261. }
  262. }
  263. })
  264. up.Update(nUp)
  265. tunnels.Update(nTunnels)
  266. }
  267. // lanePortOffset returns the rotation applied to this pair's lane target ports,
  268. // in [0, peerPortCount). Without it every peer with few ports would aim its few
  269. // lanes at a big peer's first few ports, concentrating the big peer's receive
  270. // work on a couple of sockets; the hash spreads pairs across the whole range.
  271. //
  272. // Both sides hash the same sorted vpn-address pair and the higher address
  273. // negates the result, so when port counts match the two sides' rotations
  274. // cancel on ports: our lane s's 4-tuple is the reverse of the peer's lane
  275. // s+offset, and each side's probe opens the conntrack entry the other's arrives
  276. // through. The lane indices still differ by offset; laneBias lines those up. (The one
  277. // lane a nonzero rotation lands on the peer's base port has no partner lane, so
  278. // behind a port-restricted NAT it is the one lane that may never come up.)
  279. func lanePortOffset(myAddr, peerAddr netip.Addr, peerPortCount uint16) uint16 {
  280. if peerPortCount == 0 {
  281. return 0
  282. }
  283. lo, hi := myAddr, peerAddr
  284. if hi.Less(lo) {
  285. lo, hi = hi, lo
  286. }
  287. h := fnv.New32a()
  288. b := lo.As16()
  289. h.Write(b[:])
  290. b = hi.As16()
  291. h.Write(b[:])
  292. o := uint16(h.Sum32() % uint32(peerPortCount))
  293. if myAddr == hi {
  294. o = (peerPortCount - o) % peerPortCount
  295. }
  296. return o
  297. }
  298. // laneSession returns the session to decrypt a lane s packet with, deriving one
  299. // if this is the first packet to claim that lane. A nil session with no error
  300. // means this tunnel has no lane s at all.
  301. //
  302. // cached reports whether the session was already in the table. A fresh one is
  303. // deliberately left out of it: anyone who can spoof this tunnel's local index
  304. // can name any lane, and installing on sight would let them make us hold a
  305. // replay window and two cipher states per lane without authenticating anything.
  306. // The caller must install with installSession once the packet decrypts, which is
  307. // the first moment the lane is known to be real.
  308. func (i *HostInfo) laneSession(s uint8) (ci *ConnectionState, cached bool, err error) {
  309. ls := i.lanes
  310. if ls == nil || s == 0 || int(s) >= len(ls.sessions) {
  311. return nil, false, nil
  312. }
  313. if cs := ls.sessions[s].Load(); cs != nil {
  314. return cs, true, nil
  315. }
  316. cs, err := newLaneConnectionState(&ls.material, s)
  317. if err != nil {
  318. return nil, false, err
  319. }
  320. return cs, false, nil
  321. }
  322. // installSession publishes a session derived by laneSession, so the next packet
  323. // on the lane doesn't have to derive it again. cs must have already decrypted the
  324. // packet at messageCounter.
  325. //
  326. // Two routines can race on a lane's first packet and derive a session each. The
  327. // loser's is dropped, and with it the replay-window entry for the packet it just
  328. // accepted, so hand that counter to the session that survives — the keys are
  329. // identical, so it is the same window in every respect that matters.
  330. func (ls *laneSet) installSession(l *slog.Logger, s uint8, cs *ConnectionState, messageCounter uint64) {
  331. if ls.sessions[s].CompareAndSwap(nil, cs) {
  332. return
  333. }
  334. ls.sessions[s].Load().noteSeen(l, messageCounter)
  335. }
  336. // session returns lane s's session for our own use, deriving and installing it
  337. // if it doesn't exist yet. Unlike the RX path this needs no proof the lane is
  338. // real: we only ask for lanes we chose to send on. s must be a lane this set
  339. // covers.
  340. func (ls *laneSet) session(s int) (*ConnectionState, error) {
  341. if cs := ls.sessions[s].Load(); cs != nil {
  342. return cs, nil
  343. }
  344. cs, err := newLaneConnectionState(&ls.material, uint8(s))
  345. if err != nil {
  346. return nil, err
  347. }
  348. if !ls.sessions[s].CompareAndSwap(nil, cs) {
  349. return ls.sessions[s].Load(), nil
  350. }
  351. return cs, nil
  352. }
  353. // maxMessageCounter returns the highest counter across the base session and
  354. // every lane session. Data rides the lanes, so the base counter alone would
  355. // never reach the rehandshake or exhaustion thresholds and the lane keys would
  356. // be used past their data-volume margin. Rolling the base tunnel replaces the
  357. // lane keys with it, since lanes are derived from it.
  358. func (i *HostInfo) maxMessageCounter() uint64 {
  359. if i.ConnectionState == nil {
  360. return 0
  361. }
  362. c := i.ConnectionState.messageCounter.Load()
  363. if ls := i.lanes; ls != nil {
  364. for s := range ls.sessions {
  365. cs := ls.sessions[s].Load()
  366. if cs == nil {
  367. // Never derived, so it has never sent anything either.
  368. continue
  369. }
  370. if lc := cs.messageCounter.Load(); lc > c {
  371. c = lc
  372. }
  373. }
  374. }
  375. return c
  376. }
  377. // txLane returns the session and destination for lane s, or a nil session when
  378. // the lane is down and the caller must use the base tunnel. A miss raises
  379. // demand, which is what gets a down lane probed again, so we pay for a lane
  380. // exactly where real traffic wanted one. Callers on the data plane come through
  381. // txLaneForFlow.
  382. func (ls *laneSet) txLane(s int) (*ConnectionState, netip.AddrPort) {
  383. if ls == nil || s <= 0 || s >= ls.txLanes {
  384. return nil, netip.AddrPort{}
  385. }
  386. if addr := ls.txAddr[s].Load(); addr != nil {
  387. // The lane is only up because a probe was acked on it, and that probe
  388. // derived the session, so this load cannot miss. Fall back rather than
  389. // derive here anyway: this is the hot path and a nil is not worth an HKDF.
  390. if cs := ls.sessions[s].Load(); cs != nil {
  391. return cs, *addr
  392. }
  393. return nil, netip.AddrPort{}
  394. }
  395. // Load-guarded so the common case of a lane that will not come up is a
  396. // plain read and cannot ping-pong the cache line these flags share.
  397. if !ls.demand[s].Load() {
  398. ls.demand[s].Store(true)
  399. }
  400. return nil, netip.AddrPort{}
  401. }
  402. // txLaneForFlow picks the lane a flow rides and returns it with its session and
  403. // destination, or lane 0 and a nil session when the flow belongs on the base
  404. // tunnel — either because the hash landed on lane 0 or because the lane it
  405. // landed on is down.
  406. //
  407. // The lane comes from the flow rather than from the sending routine so that lane
  408. // use doesn't depend on how the kernel steers tun queues; see txQueue. It is a
  409. // pure function of the 5-tuple, so a flow stays on one lane for its life: no
  410. // per-packet reordering, and one lane's replay window sees one set of flows.
  411. func (ls *laneSet) txLaneForFlow(p *firewall.Packet) (int, *ConnectionState, netip.AddrPort) {
  412. if ls == nil || ls.txLanes < 2 {
  413. return 0, nil, netip.AddrPort{}
  414. }
  415. s := int((laneFlowHash(p) + uint32(ls.laneBias)) % uint32(ls.txLanes))
  416. if s == 0 {
  417. // Lane 0 is the base tunnel, and a full share of flows belongs on it.
  418. return 0, nil, netip.AddrPort{}
  419. }
  420. cs, addr := ls.txLane(s)
  421. return s, cs, addr
  422. }
  423. // laneFlowHash hashes a 5-tuple to the same value from either end of the flow,
  424. // which is what lets both peers pick partner lanes for it (see laneBias). FNV-1a
  425. // by hand rather than through hash/fnv: this runs per packet, and the interface
  426. // there would escape the addresses to the heap.
  427. func laneFlowHash(p *firewall.Packet) uint32 {
  428. // Order the two endpoints so the direction of travel cannot change the hash.
  429. aAddr, aPort := p.LocalAddr, p.LocalPort
  430. bAddr, bPort := p.RemoteAddr, p.RemotePort
  431. if bAddr.Less(aAddr) || (aAddr == bAddr && bPort < aPort) {
  432. aAddr, aPort, bAddr, bPort = bAddr, bPort, aAddr, aPort
  433. }
  434. const prime = 16777619
  435. h := uint32(2166136261)
  436. x, y := aAddr.As16(), bAddr.As16()
  437. for i := range x {
  438. h = (h ^ uint32(x[i])) * prime
  439. h = (h ^ uint32(y[i])) * prime
  440. }
  441. for _, b := range [5]byte{byte(aPort >> 8), byte(aPort), byte(bPort >> 8), byte(bPort), p.Protocol} {
  442. h = (h ^ uint32(b)) * prime
  443. }
  444. return h
  445. }
  446. // laneTargetPortLocked returns the peer port lane s aims at. Only meaningful
  447. // when peerPortCount is nonzero, which txLanes > 0 guarantees.
  448. func (ls *laneSet) laneTargetPortLocked(s int) uint16 {
  449. return ls.peerBasePort + uint16((s+int(ls.portOffset))%int(ls.peerPortCount))
  450. }
  451. // laneTargetLocked returns where lane s's probes go: the peer port this lane is
  452. // paired with, on the peer's current direct address.
  453. //
  454. // A lane only ever aims at its own port. There is no fallback to the peer's base
  455. // port when the lane port doesn't answer — a lane sharing the base port's
  456. // destination gains only a source port of its own, while costing the peer the
  457. // receive spread that is the whole point, so a lane that can't reach its port
  458. // stays down and its traffic rides the base tunnel.
  459. func (ls *laneSet) laneTargetLocked(s int, addr netip.Addr) netip.AddrPort {
  460. return netip.AddrPortFrom(addr, ls.laneTargetPortLocked(s))
  461. }
  462. // laneRetryDelay is the backoff after fails consecutive probe failures.
  463. func laneRetryDelay(fails uint8) time.Duration {
  464. d := laneRetryBase << min(fails, 4)
  465. if d > laneRetryMax {
  466. d = laneRetryMax
  467. }
  468. return d
  469. }
  470. // noteAck records an acked probe for lane s, promoting the lane if it was down.
  471. // gen must match the outstanding probe. Reports the target the lane came up on,
  472. // and whether this ack is what promoted it.
  473. func (ls *laneSet) noteAck(s int, gen uint8, now time.Time) (netip.AddrPort, bool) {
  474. if s <= 0 || s >= len(ls.probe) {
  475. return netip.AddrPort{}, false
  476. }
  477. ls.mu.Lock()
  478. defer ls.mu.Unlock()
  479. p := &ls.probe[s]
  480. if p.sentAt.IsZero() || p.gen != gen {
  481. // No probe outstanding, or an ack for a probe we have already given up
  482. // on. Either way it says nothing about the lane's current path.
  483. return netip.AddrPort{}, false
  484. }
  485. p.sentAt = time.Time{}
  486. p.lastAck = now
  487. p.fails = 0
  488. p.retryAt = time.Time{}
  489. target := p.target
  490. if ls.txAddr[s].Load() != nil {
  491. // Keepalive for a lane already up.
  492. return target, false
  493. }
  494. ls.txAddr[s].Store(&target)
  495. return target, true
  496. }
  497. // probeLanes runs one lane maintenance pass for a peer: it demotes lanes whose
  498. // probe went unanswered, re-proves lanes that have been up a while without one,
  499. // and probes down lanes the data plane asked for. Driven by the connection
  500. // manager's per-tunnel traffic tick, which skips a tunnel that is idle in both
  501. // directions.
  502. func (f *Interface) probeLanes(hostinfo *HostInfo, now time.Time, nb, out []byte) {
  503. ls := hostinfo.lanes
  504. if ls == nil || ls.txLanes < 2 {
  505. return
  506. }
  507. remote := hostinfo.GetRemote()
  508. ls.mu.Lock()
  509. defer ls.mu.Unlock()
  510. if !remote.IsValid() {
  511. // Relayed, or otherwise without a direct path. Lanes are direct-only,
  512. // so drop them all; a later tick rebuilds if a direct path returns.
  513. ls.resetLocked()
  514. return
  515. }
  516. if ls.peerAddr != remote.Addr() {
  517. if ls.peerAddr.IsValid() {
  518. // A roam is a new path, not a failure: forget the lanes built on
  519. // the old one and let demand re-probe from a clean backoff. On the
  520. // first pass there is nothing built yet, so just record the address.
  521. ls.resetLocked()
  522. }
  523. ls.peerAddr = remote.Addr()
  524. }
  525. for s := 1; s < ls.txLanes; s++ {
  526. p := &ls.probe[s]
  527. up := ls.txAddr[s].Load() != nil
  528. if !p.sentAt.IsZero() {
  529. if now.Sub(p.sentAt) < laneProbeTimeout {
  530. continue
  531. }
  532. // An aged-out probe is a failure whether it was bringing the lane
  533. // up or keeping it up.
  534. p.sentAt = time.Time{}
  535. p.fails = min(p.fails+1, laneMaxFails)
  536. p.retryAt = now.Add(laneRetryDelay(p.fails))
  537. if up {
  538. ls.txAddr[s].Store(nil)
  539. hostinfo.logger(f.l).Info("Multiport lane demoted, probe unanswered", "lane", s, "udpAddr", p.target)
  540. } else if p.lastAck.IsZero() && p.fails == laneWarnFails {
  541. // Said once per lane: fails only passes through this value again
  542. // after an ack or a reset clears it.
  543. hostinfo.logger(f.l).Warn("Multiport lane not coming up, probes unanswered; check that the peer's lane ports are reachable",
  544. "lane", s, "udpAddr", p.target, "fails", p.fails)
  545. }
  546. continue
  547. }
  548. if up {
  549. if now.Sub(p.lastAck) < laneKeepalive {
  550. continue
  551. }
  552. } else if now.Before(p.retryAt) || !ls.demand[s].Swap(false) {
  553. continue
  554. }
  555. p.gen++
  556. p.target = ls.laneTargetLocked(s, remote.Addr())
  557. if f.sendLaneProbe(hostinfo, s, p.gen, p.target, nb, out) {
  558. p.sentAt = now
  559. } else {
  560. p.fails = min(p.fails+1, laneMaxFails)
  561. p.retryAt = now.Add(laneRetryDelay(p.fails))
  562. }
  563. }
  564. }
  565. // resetLocked takes every lane down and clears its probe state, without
  566. // counting it as a failure.
  567. //
  568. // The probe generation survives the reset. Starting it over would let a late ack
  569. // for a probe sent before the reset match the first probe sent after it, and
  570. // promote the lane to a target nothing has proven.
  571. //
  572. // Demand is deliberately left standing: a roam or a relay detour doesn't change
  573. // what the data plane wants. Lanes that were up had their demand spent when they
  574. // were probed, but the first packet of a flow that hashes onto one after the
  575. // reset raises it again, so lanes still carrying flows are re-probed on the next
  576. // tick, while a lane nothing hashes onto stays down.
  577. func (ls *laneSet) resetLocked() {
  578. for s := 1; s < len(ls.probe); s++ {
  579. ls.txAddr[s].Store(nil)
  580. ls.probe[s] = laneProbeState{gen: ls.probe[s].gen}
  581. }
  582. }
  583. // isLaneProbe reports whether t/st is a lane probe or its ack. Probing is upkeep
  584. // the lanes do for themselves, not traffic: counting it would let a lane's own
  585. // keepalive keep an idle tunnel from ever being dropped.
  586. func isLaneProbe(t header.MessageType, st header.MessageSubType) bool {
  587. return t == header.Test && (st == header.LaneProbe || st == header.LaneProbeAck)
  588. }
  589. // isLaneRemote reports whether addr is the target of one of our up lanes. The
  590. // peer answers a lane packet from the socket it arrived on, so a recv_error for
  591. // lane traffic comes from that lane's target rather than the base remote.
  592. func (ls *laneSet) isLaneRemote(addr netip.AddrPort) bool {
  593. if ls == nil {
  594. return false
  595. }
  596. for s := 1; s < ls.txLanes; s++ {
  597. if a := ls.txAddr[s].Load(); a != nil && *a == addr {
  598. return true
  599. }
  600. }
  601. return false
  602. }
  603. // sendLaneProbe sends a probe on lane s to addr from a socket on lane s's port.
  604. // The probe is an ordinary Test packet encrypted with the lane's session, so an
  605. // ack proves the whole lane: our source port reached the peer, its reply reached
  606. // us, and the keys we derived for this lane match the ones it derived. Reports
  607. // whether the probe made it onto the wire.
  608. //
  609. // It goes out the first socket on the port, since the connection manager runs
  610. // this and has no queue of its own; every socket on the port has the same address,
  611. // so the probe proves the path for whichever one the data plane picks.
  612. func (f *Interface) sendLaneProbe(hostinfo *HostInfo, s int, gen uint8, addr netip.AddrPort, nb, out []byte) bool {
  613. // The first probe on a lane is what derives its session.
  614. ci, err := hostinfo.lanes.session(s)
  615. if err != nil {
  616. hostinfo.logger(f.l).Error("Failed to derive multiport lane session", "error", err, "lane", s)
  617. return false
  618. }
  619. if ci == nil || ci.eKey == nil {
  620. return false
  621. }
  622. if noiseutil.EncryptLockNeeded {
  623. ci.writeLock.Lock()
  624. }
  625. c, ok := ci.NextMessageCounter()
  626. if !ok {
  627. if noiseutil.EncryptLockNeeded {
  628. ci.writeLock.Unlock()
  629. }
  630. f.dropExhausted(hostinfo, c, "Dropping multiport lane probe, lane message counter is exhausted")
  631. return false
  632. }
  633. b := header.EncodeLane(out[:0], header.Version, header.Test, header.LaneProbe, hostinfo.remoteIndexId, c, uint8(s))
  634. b, err = ci.eKey.EncryptDanger(b, b, []byte{uint8(s), gen}, c, nb)
  635. if noiseutil.EncryptLockNeeded {
  636. ci.writeLock.Unlock()
  637. }
  638. if err != nil {
  639. hostinfo.logger(f.l).Error("Failed to encrypt multiport lane probe", "error", err, "lane", s)
  640. return false
  641. }
  642. f.messageMetrics.Tx(header.Test, header.LaneProbe, 1)
  643. if err := f.writers[f.laneSock(0, s)].WriteTo(b, addr); err != nil {
  644. hostinfo.logger(f.l).Error("Failed to send multiport lane probe", "error", err, "lane", s, "udpAddr", addr)
  645. return false
  646. }
  647. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  648. hostinfo.logger(f.l).Debug("Multiport lane probe sent", "lane", s, "gen", gen, "udpAddr", addr)
  649. }
  650. return true
  651. }
  652. // handleLaneProbe answers a peer's lane probe. The ack rides the base tunnel on
  653. // purpose: a probe proves the peer's lane s works in its send direction, and
  654. // answering on our own lane s would make the result depend on a second path
  655. // that may be broken independently.
  656. func (f *Interface) handleLaneProbe(hostinfo *HostInfo, lane uint8, payload []byte, rxc *rxContext) {
  657. if lane == 0 || len(payload) < 2 {
  658. return
  659. }
  660. // Echo the header's lane rather than the payload's, so a peer cannot get us
  661. // to vouch for a lane it did not actually probe.
  662. f.send(header.Test, header.LaneProbeAck, hostinfo.ConnectionState, hostinfo,
  663. []byte{lane, payload[1]}, rxc.nb, rxc.scratch[:0])
  664. }
  665. // handleLaneProbeAck promotes the lane a peer just acked.
  666. func (f *Interface) handleLaneProbeAck(hostinfo *HostInfo, payload []byte) {
  667. ls := hostinfo.lanes
  668. if ls == nil || len(payload) < 2 {
  669. return
  670. }
  671. // The target is worth logging next to the demotion that names the same
  672. // address, so a flapping lane can be read off the logs.
  673. if target, promoted := ls.noteAck(int(payload[0]), payload[1], time.Now()); promoted {
  674. hostinfo.logger(f.l).Info("Multiport lane up", "lane", payload[0], "udpAddr", target)
  675. }
  676. }