lanes.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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/slackhq/nebula/handshake"
  11. "github.com/slackhq/nebula/header"
  12. "github.com/slackhq/nebula/noiseutil"
  13. )
  14. // Multiport lanes give each data-plane routine its own underlay 5-tuple, so one
  15. // tunnel's traffic spreads over ECMP paths, NIC receive queues and per-flow
  16. // policers instead of funnelling through a single flow.
  17. //
  18. // A lane is not a second tunnel: it is an extra session on the same HostInfo.
  19. // Noise leaves us with A.eKey == B.dKey, so both sides expand the same two keys
  20. // with the same per-lane label and land on a matched pair without exchanging
  21. // anything. A lane therefore costs no handshake, has no half-established state,
  22. // and dies exactly when its base tunnel does. Which lane a packet belongs to
  23. // travels in the nebula header, inside the AEAD's associated data.
  24. //
  25. // Lane 0 is the base tunnel itself: HostInfo.ConnectionState, socket 0, and the
  26. // peer's real remote address. Lane s > 0 egresses writers[s] (bound to
  27. // listen.port+s) toward the peer's advertised port range. Receiving on a lane
  28. // needs no permission — the session exists as soon as the base handshake
  29. // completes — but sending on one needs proof the new 5-tuple actually works,
  30. // since nothing else would notice a middlebox quietly dropping it. So a lane
  31. // stays down until a probe on it is acked, and falls back to the base tunnel the
  32. // moment it stops being acked.
  33. const (
  34. // laneKeyInfo is the HKDF label prefix for lane key expansion. Changing it
  35. // means older builds derive different keys and drop our lane traffic; the
  36. // base tunnel would keep working, so the failure would be a silent loss of
  37. // lanes rather than of connectivity.
  38. laneKeyInfo = "nebula multiport lane v1"
  39. // laneRetryBase and laneRetryMax bound the backoff between probes of a lane
  40. // that will not come up, so a peer whose lane ports are firewalled costs one
  41. // packet a minute rather than one per traffic tick.
  42. laneRetryBase = 5 * time.Second
  43. laneRetryMax = 60 * time.Second
  44. // laneMaxFails caps the failure counter; the backoff saturates well before.
  45. laneMaxFails = 8
  46. // laneProbeTimeout is how long a probe may go unacked before it counts as a
  47. // failure. It is shorter than the connection manager's check interval on
  48. // purpose: an outstanding probe is judged on the next tick either way, and a
  49. // longer timeout would only delay that by a whole tick.
  50. laneProbeTimeout = 2 * time.Second
  51. // laneKeepalive is how often a lane that is up re-proves its path. Traffic
  52. // on a lane is not evidence the lane works — that is the whole reason lanes
  53. // need probing — so a lane that silently breaks is only caught here.
  54. laneKeepalive = 30 * time.Second
  55. )
  56. // laneSet holds a peer's lane sessions and the state deciding which lanes may
  57. // carry traffic. It is built when the base handshake completes and never
  58. // resized, so the slices and their lengths are immutable; mu guards the fields
  59. // under it, and txAddr/demand are atomics read by the data plane without it.
  60. type laneSet struct {
  61. // sessions[s] is lane s's session. sessions[0] is nil: lane 0 is the base
  62. // tunnel's own ConnectionState. Immutable, so the RX path reads it with no
  63. // synchronization at all.
  64. sessions []*ConnectionState
  65. // txAddr[s] holds lane s's remote address while the lane is proven usable
  66. // and nil otherwise. This single atomic is both the TX gate and the
  67. // destination, so a routine that loads non-nil has everything it needs.
  68. txAddr []atomic.Pointer[netip.AddrPort]
  69. // demand[s] is raised by the TX path when a routine riding lane s has
  70. // traffic for this peer and the lane is down. Probing is demand-driven: a
  71. // peer we exchange a trickle with never costs more than its base tunnel, no
  72. // matter how many lanes are configured.
  73. demand []atomic.Bool
  74. // txLanes is how many lanes we may send on — our lane count clamped to the
  75. // ports the peer bound. Lanes from txLanes up exist only to receive, which
  76. // is how a peer with more routines than us still spreads its own traffic.
  77. // Immutable.
  78. txLanes int
  79. mu sync.Mutex
  80. // peerPortCount and peerBasePort are the peer's advertised port range and
  81. // portOffset is this pair's rotation within it: lane s targets
  82. // peerBasePort + ((s + portOffset) % peerPortCount).
  83. peerPortCount uint16
  84. peerBasePort uint16
  85. portOffset uint16
  86. // peerAddr is the address the current lane targets were built from. The
  87. // peer's lane ports have no derivable relationship to a new NAT mapping, so
  88. // a roam invalidates every lane rather than moving it.
  89. peerAddr netip.Addr
  90. // probe[s] is lane s's probe and backoff state.
  91. probe []laneProbeState
  92. }
  93. type laneProbeState struct {
  94. // gen is the generation of the last probe sent, echoed in the ack so a late
  95. // ack cannot promote a lane on the strength of a superseded probe.
  96. gen uint8
  97. // fails is the consecutive failure count driving retryAt.
  98. fails uint8
  99. // sentAt is when the outstanding probe went out, zero when none is pending.
  100. sentAt time.Time
  101. // target is where the outstanding probe went, promoted to txAddr on ack.
  102. target netip.AddrPort
  103. // lastAck is when the lane was last confirmed usable, driving the keepalive.
  104. lastAck time.Time
  105. // retryAt is the earliest we may probe this lane again.
  106. retryAt time.Time
  107. }
  108. // newLaneSet derives the lane sessions for a freshly completed base handshake.
  109. // It returns nil when the pair has no lane beyond the base tunnel, which is the
  110. // normal answer for a peer running without multiport.
  111. func newLaneSet(r *handshake.Result, myLanes int, myAddr, peerAddr netip.Addr) (*laneSet, error) {
  112. // PeerPortCount and PeerBasePort are already bounded to uint16 by the
  113. // handshake payload parser. A zero port count is a peer that did not
  114. // advertise multiport at all, so there is no lane to be had in either
  115. // direction.
  116. peerPorts := uint16(r.PeerPortCount)
  117. if peerPorts == 0 {
  118. return nil, nil
  119. }
  120. // Sessions have to cover both directions: we send on our lanes and receive
  121. // on the peer's, and one derived session serves both ends of a lane index.
  122. n := min(max(myLanes, int(r.PeerTxLanes)), header.MaxLane+1)
  123. if n < 2 {
  124. return nil, nil
  125. }
  126. ls := &laneSet{
  127. sessions: make([]*ConnectionState, n),
  128. txAddr: make([]atomic.Pointer[netip.AddrPort], n),
  129. demand: make([]atomic.Bool, n),
  130. probe: make([]laneProbeState, n),
  131. txLanes: min(myLanes, int(peerPorts), n),
  132. peerPortCount: peerPorts,
  133. peerBasePort: uint16(r.PeerBasePort),
  134. portOffset: lanePortOffset(myAddr, peerAddr, peerPorts),
  135. }
  136. for s := 1; s < n; s++ {
  137. cs, err := newLaneConnectionState(r, uint8(s))
  138. if err != nil {
  139. return nil, err
  140. }
  141. ls.sessions[s] = cs
  142. }
  143. return ls, nil
  144. }
  145. // lanePortOffset returns the rotation applied to this pair's lane target ports,
  146. // in [0, peerPortCount). Without it every low-routine peer would aim its few
  147. // lanes at a big peer's first few ports, concentrating the big peer's receive
  148. // work on a couple of sockets; the hash spreads pairs across the whole range.
  149. //
  150. // Both sides hash the same sorted vpn-address pair and the higher address
  151. // negates the result, so when port counts match the two sides' rotations
  152. // cancel: our lane s's 4-tuple stays the reverse of the peer's lane s, and each
  153. // side's probe opens the conntrack entry the other's arrives through. (The one
  154. // lane a nonzero rotation lands on the peer's base port has no partner lane;
  155. // behind a port-restricted NAT it may never come up, and its routine rides the
  156. // base tunnel — the standard lane fallback.)
  157. func lanePortOffset(myAddr, peerAddr netip.Addr, peerPortCount uint16) uint16 {
  158. if peerPortCount == 0 {
  159. return 0
  160. }
  161. lo, hi := myAddr, peerAddr
  162. if hi.Less(lo) {
  163. lo, hi = hi, lo
  164. }
  165. h := fnv.New32a()
  166. b := lo.As16()
  167. h.Write(b[:])
  168. b = hi.As16()
  169. h.Write(b[:])
  170. o := uint16(h.Sum32() % uint32(peerPortCount))
  171. if myAddr == hi {
  172. o = (peerPortCount - o) % peerPortCount
  173. }
  174. return o
  175. }
  176. // laneSession returns lane s's session, or nil if this peer has no lane s.
  177. func (i *HostInfo) laneSession(s uint8) *ConnectionState {
  178. ls := i.lanes
  179. if ls == nil || int(s) >= len(ls.sessions) {
  180. return nil
  181. }
  182. return ls.sessions[s]
  183. }
  184. // maxMessageCounter returns the highest counter across the base session and
  185. // every lane session. Data rides the lanes, so the base counter alone would
  186. // never reach the rehandshake or exhaustion thresholds and the lane keys would
  187. // be used past their data-volume margin. Rolling the base tunnel replaces the
  188. // lane keys with it, since lanes are derived from it.
  189. func (i *HostInfo) maxMessageCounter() uint64 {
  190. if i.ConnectionState == nil {
  191. return 0
  192. }
  193. c := i.ConnectionState.messageCounter.Load()
  194. if ls := i.lanes; ls != nil {
  195. for _, cs := range ls.sessions {
  196. if cs == nil {
  197. continue
  198. }
  199. if lc := cs.messageCounter.Load(); lc > c {
  200. c = lc
  201. }
  202. }
  203. }
  204. return c
  205. }
  206. // txLane returns the session and destination for lane s, or a nil session when
  207. // the lane is down and the caller must use the base tunnel. A miss raises
  208. // demand, which is the only thing that gets a lane probed, so we pay for a lane
  209. // exactly where real traffic wanted one.
  210. func (ls *laneSet) txLane(s int) (*ConnectionState, netip.AddrPort) {
  211. if ls == nil || s <= 0 || s >= ls.txLanes {
  212. return nil, netip.AddrPort{}
  213. }
  214. if addr := ls.txAddr[s].Load(); addr != nil {
  215. return ls.sessions[s], *addr
  216. }
  217. // Load-guarded so the common case of a lane that will not come up is a
  218. // plain read and cannot ping-pong the cache line these flags share.
  219. if !ls.demand[s].Load() {
  220. ls.demand[s].Store(true)
  221. }
  222. return nil, netip.AddrPort{}
  223. }
  224. // laneTargetPortLocked returns the peer port lane s aims at. Only meaningful
  225. // when peerPortCount is nonzero, which txLanes > 0 guarantees.
  226. func (ls *laneSet) laneTargetPortLocked(s int) uint16 {
  227. return ls.peerBasePort + uint16((s+int(ls.portOffset))%int(ls.peerPortCount))
  228. }
  229. // laneRetryDelay is the backoff after fails consecutive probe failures.
  230. func laneRetryDelay(fails uint8) time.Duration {
  231. d := laneRetryBase << min(fails, 4)
  232. if d > laneRetryMax {
  233. d = laneRetryMax
  234. }
  235. return d
  236. }
  237. // noteAck records an acked probe for lane s, promoting the lane if it was down.
  238. // gen must match the outstanding probe. Reports whether the lane was promoted.
  239. func (ls *laneSet) noteAck(s int, gen uint8, now time.Time) bool {
  240. if s <= 0 || s >= len(ls.probe) {
  241. return false
  242. }
  243. ls.mu.Lock()
  244. defer ls.mu.Unlock()
  245. p := &ls.probe[s]
  246. if p.sentAt.IsZero() || p.gen != gen {
  247. // No probe outstanding, or an ack for a probe we have already given up
  248. // on. Either way it says nothing about the lane's current path.
  249. return false
  250. }
  251. p.sentAt = time.Time{}
  252. p.lastAck = now
  253. p.fails = 0
  254. p.retryAt = time.Time{}
  255. if ls.txAddr[s].Load() != nil {
  256. // Keepalive for a lane already up.
  257. return false
  258. }
  259. target := p.target
  260. ls.txAddr[s].Store(&target)
  261. return true
  262. }
  263. // probeLanes runs one lane maintenance pass for a peer: it demotes lanes whose
  264. // probe went unanswered, re-proves lanes that have been up a while without one,
  265. // and probes down lanes the data plane asked for. Driven by the connection
  266. // manager's per-tunnel traffic tick, which only fires for a live tunnel — the
  267. // same condition that produces lane demand in the first place.
  268. func (f *Interface) probeLanes(hostinfo *HostInfo, now time.Time, nb, out []byte) {
  269. ls := hostinfo.lanes
  270. if ls == nil || ls.txLanes < 2 {
  271. return
  272. }
  273. remote := hostinfo.GetRemote()
  274. ls.mu.Lock()
  275. defer ls.mu.Unlock()
  276. if !remote.IsValid() {
  277. // Relayed, or otherwise without a direct path. Lanes are direct-only,
  278. // so drop them all; a later tick rebuilds if a direct path returns.
  279. ls.resetLocked()
  280. return
  281. }
  282. if ls.peerAddr != remote.Addr() {
  283. if ls.peerAddr.IsValid() {
  284. // A roam is a new path, not a failure: forget the lanes built on
  285. // the old one and let demand re-probe from a clean backoff. On the
  286. // first pass there is nothing built yet, so just record the address.
  287. ls.resetLocked()
  288. }
  289. ls.peerAddr = remote.Addr()
  290. }
  291. for s := 1; s < ls.txLanes; s++ {
  292. p := &ls.probe[s]
  293. up := ls.txAddr[s].Load() != nil
  294. if !p.sentAt.IsZero() {
  295. if now.Sub(p.sentAt) < laneProbeTimeout {
  296. continue
  297. }
  298. // An aged-out probe is a failure whether it was bringing the lane
  299. // up or keeping it up.
  300. p.sentAt = time.Time{}
  301. p.fails = min(p.fails+1, laneMaxFails)
  302. p.retryAt = now.Add(laneRetryDelay(p.fails))
  303. if up {
  304. ls.txAddr[s].Store(nil)
  305. hostinfo.logger(f.l).Info("Multiport lane demoted, probe unanswered", "lane", s)
  306. }
  307. continue
  308. }
  309. if up {
  310. if now.Sub(p.lastAck) < laneKeepalive {
  311. continue
  312. }
  313. } else if now.Before(p.retryAt) || !ls.demand[s].Swap(false) {
  314. continue
  315. }
  316. p.gen++
  317. p.target = netip.AddrPortFrom(remote.Addr(), ls.laneTargetPortLocked(s))
  318. if f.sendLaneProbe(hostinfo, s, p.gen, p.target, nb, out) {
  319. p.sentAt = now
  320. } else {
  321. p.fails = min(p.fails+1, laneMaxFails)
  322. p.retryAt = now.Add(laneRetryDelay(p.fails))
  323. }
  324. }
  325. }
  326. // resetLocked takes every lane down and clears its probe state, without
  327. // counting it as a failure.
  328. //
  329. // Demand is deliberately left standing: it records that a routine has real
  330. // traffic for this peer, which a roam or a relay detour does not change. Keeping
  331. // it re-probes the lanes that were actually carrying data as soon as a path
  332. // exists again, while a lane whose routine has gone quiet stays down.
  333. func (ls *laneSet) resetLocked() {
  334. for s := 1; s < len(ls.probe); s++ {
  335. ls.txAddr[s].Store(nil)
  336. ls.probe[s] = laneProbeState{}
  337. }
  338. }
  339. // sendLaneProbe sends a probe on lane s to addr from writers[s]. The probe is an
  340. // ordinary Test packet encrypted with the lane's session, so an ack proves the
  341. // whole lane: our source port reached the peer, its reply reached us, and the
  342. // keys we derived for this lane match the ones it derived. Reports whether the
  343. // probe made it onto the wire.
  344. func (f *Interface) sendLaneProbe(hostinfo *HostInfo, s int, gen uint8, addr netip.AddrPort, nb, out []byte) bool {
  345. ci := hostinfo.lanes.sessions[s]
  346. if ci == nil || ci.eKey == nil {
  347. return false
  348. }
  349. if noiseutil.EncryptLockNeeded {
  350. ci.writeLock.Lock()
  351. }
  352. c, ok := ci.NextMessageCounter()
  353. if !ok {
  354. if noiseutil.EncryptLockNeeded {
  355. ci.writeLock.Unlock()
  356. }
  357. f.dropExhausted(hostinfo, c, "Dropping multiport lane probe, lane message counter is exhausted")
  358. return false
  359. }
  360. b := header.EncodeLane(out[:0], header.Version, header.Test, header.LaneProbe, hostinfo.remoteIndexId, c, uint8(s))
  361. b, err := ci.eKey.EncryptDanger(b, b, []byte{uint8(s), gen}, c, nb)
  362. if noiseutil.EncryptLockNeeded {
  363. ci.writeLock.Unlock()
  364. }
  365. if err != nil {
  366. hostinfo.logger(f.l).Error("Failed to encrypt multiport lane probe", "error", err, "lane", s)
  367. return false
  368. }
  369. f.messageMetrics.Tx(header.Test, header.LaneProbe, 1)
  370. if err := f.writers[s].WriteTo(b, addr); err != nil {
  371. hostinfo.logger(f.l).Error("Failed to send multiport lane probe", "error", err, "lane", s, "udpAddr", addr)
  372. return false
  373. }
  374. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  375. hostinfo.logger(f.l).Debug("Multiport lane probe sent", "lane", s, "gen", gen, "udpAddr", addr)
  376. }
  377. return true
  378. }
  379. // handleLaneProbe answers a peer's lane probe. The ack rides the base tunnel on
  380. // purpose: a probe proves the peer's lane s works in its send direction, and
  381. // answering on our own lane s would make the result depend on a second path
  382. // that may be broken independently.
  383. func (f *Interface) handleLaneProbe(hostinfo *HostInfo, lane uint8, payload []byte, rxc *rxContext) {
  384. if lane == 0 || len(payload) < 2 {
  385. return
  386. }
  387. // Echo the header's lane rather than the payload's, so a peer cannot get us
  388. // to vouch for a lane it did not actually probe.
  389. f.send(header.Test, header.LaneProbeAck, hostinfo.ConnectionState, hostinfo,
  390. []byte{lane, payload[1]}, rxc.nb, rxc.scratch[:0])
  391. }
  392. // handleLaneProbeAck promotes the lane a peer just acked.
  393. func (f *Interface) handleLaneProbeAck(hostinfo *HostInfo, payload []byte) {
  394. ls := hostinfo.lanes
  395. if ls == nil || len(payload) < 2 {
  396. return
  397. }
  398. if ls.noteAck(int(payload[0]), payload[1], time.Now()) {
  399. hostinfo.logger(f.l).Info("Multiport lane up", "lane", payload[0])
  400. }
  401. }