inside.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. package nebula
  2. import (
  3. "context"
  4. "io"
  5. "log/slog"
  6. "net/netip"
  7. "github.com/slackhq/nebula/firewall"
  8. "github.com/slackhq/nebula/header"
  9. "github.com/slackhq/nebula/iputil"
  10. "github.com/slackhq/nebula/noiseutil"
  11. "github.com/slackhq/nebula/overlay/tio"
  12. "github.com/slackhq/nebula/routing"
  13. )
  14. func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.Packet, nb []byte, tx *txQueue, rejectBuf []byte, q int, localCache firewall.ConntrackCache) {
  15. // borrowed: pkt.Bytes is owned by the originating tio.Queue and is
  16. // only valid until the next Read on that queue. Every consumer below
  17. // (parse, self-forward, handshake cache, sendInsideMessage) reads it
  18. // synchronously; do not retain pkt outside this call. If a future
  19. // caller needs to keep the packet, use pkt.Clone() to detach it from
  20. // the borrow.
  21. //
  22. // pkt.Bytes is either one IP datagram (GSO zero) or a TSO/USO
  23. // superpacket. In both cases the L3+L4 headers at the start describe
  24. // the same 5-tuple every segment will share, so a single newPacket /
  25. // firewall check covers the whole superpacket.
  26. packet := pkt.Bytes
  27. err := newPacket(packet, false, fwPacket)
  28. if err != nil {
  29. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  30. f.l.Debug("Error while validating outbound packet",
  31. "packet", packet,
  32. "error", err,
  33. )
  34. }
  35. return
  36. }
  37. // Ignore local broadcast packets
  38. if f.dropLocalBroadcast {
  39. if f.myBroadcastAddrsTable.Contains(fwPacket.RemoteAddr) {
  40. return
  41. }
  42. }
  43. if f.myVpnAddrsTable.Contains(fwPacket.RemoteAddr) {
  44. // Immediately forward packets from self to self.
  45. // This should only happen on Darwin-based and FreeBSD hosts, which
  46. // routes packets from the Nebula addr to the Nebula addr through the Nebula
  47. // TUN device.
  48. if immediatelyForwardToSelf {
  49. // Write copies into the kernel queue synchronously, so seg's lifetime ends at return.
  50. // A self-forwarded superpacket would be re-handed to the
  51. // kernel as one giant blob; segment first so the loopback
  52. // path sees one IP datagram per Write.
  53. err := tio.SegmentSuperpacket(pkt, func(seg []byte) error {
  54. _, werr := f.queues[q].Write(seg)
  55. return werr
  56. })
  57. if err != nil {
  58. f.l.Error("Failed to forward to tun", "error", err)
  59. }
  60. }
  61. // Otherwise, drop. On linux, we should never see these packets - Linux
  62. // routes packets from the nebula addr to the nebula addr through the loopback device.
  63. return
  64. }
  65. // Ignore multicast packets
  66. if f.dropMulticast && fwPacket.RemoteAddr.IsMulticast() {
  67. return
  68. }
  69. hostinfo, ready := f.getOrHandshakeConsiderRouting(fwPacket, func(hh *HandshakeHostInfo) {
  70. // borrowed: SegmentSuperpacket builds each segment in the kernel-supplied pkt
  71. // bytes underneath. cachePacket explicitly copies its argument (handshake_manager.go cachePacket),
  72. // so retaining segments past the loop is safe.
  73. err := tio.SegmentSuperpacket(pkt, func(seg []byte) error {
  74. hh.cachePacket(f.l, header.Message, 0, seg, f.sendMessageNow, f.cachedPacketMetrics)
  75. return nil
  76. })
  77. if err != nil && f.l.Enabled(context.Background(), slog.LevelDebug) {
  78. f.l.Debug("Failed to segment superpacket for handshake cache",
  79. "error", err,
  80. "vpnAddr", fwPacket.RemoteAddr,
  81. )
  82. }
  83. })
  84. if hostinfo == nil {
  85. f.rejectInside(packet, rejectBuf, q)
  86. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  87. f.l.Debug("dropping outbound packet, vpnAddr not in our vpn networks or in unsafe networks",
  88. "vpnAddr", fwPacket.RemoteAddr,
  89. "fwPacket", fwPacket,
  90. )
  91. }
  92. return
  93. }
  94. if !ready {
  95. return
  96. }
  97. dropReason := f.firewall.Drop(*fwPacket, false, hostinfo, f.pki.GetCAPool(), localCache)
  98. if dropReason == nil {
  99. f.sendInsideMessage(hostinfo, pkt, nb, tx)
  100. } else {
  101. f.rejectInside(packet, rejectBuf, q)
  102. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  103. hostinfo.logger(f.l).Debug("dropping outbound packet",
  104. "fwPacket", fwPacket,
  105. "reason", dropReason,
  106. )
  107. }
  108. }
  109. }
  110. func (f *Interface) sendInsideEncrypt(hostinfo *HostInfo, ci *ConnectionState, seg, scratch, nb []byte) []byte {
  111. if noiseutil.EncryptLockNeeded {
  112. ci.writeLock.Lock()
  113. }
  114. c := ci.messageCounter.Add(1)
  115. out := header.Encode(scratch, header.Version, header.Message, 0, hostinfo.remoteIndexId, c)
  116. f.connectionManager.Out(hostinfo)
  117. out, encErr := ci.eKey.EncryptDanger(out, out, seg, c, nb)
  118. if noiseutil.EncryptLockNeeded {
  119. ci.writeLock.Unlock()
  120. }
  121. if encErr != nil {
  122. hostinfo.logger(f.l).Error("Failed to encrypt outgoing packet",
  123. "error", encErr,
  124. "udpAddr", hostinfo.GetRemote(),
  125. "counter", c,
  126. )
  127. // Skip this segment; the rest of the superpacket can still
  128. // go out — TCP will retransmit anything we drop here.
  129. return nil
  130. }
  131. return out
  132. }
  133. // sendInsideMessage encrypts a firewall-approved inside packet (or every
  134. // segment of a TSO/USO superpacket) into the caller's batch slot for
  135. // later sendmmsg flush. Segmentation is fused with encryption here so the
  136. // kernel-supplied superpacket bytes never get written into a separate
  137. // scratch arena: SegmentSuperpacket builds each segment's plaintext in
  138. // segScratch[:segLen] in turn, and we encrypt directly into a fresh
  139. // SendBatch slot.
  140. //
  141. // hostinfo is always the base tunnel (the hostmap resolves by vpn address);
  142. // when routine q has an established lane to this peer, the direct path swaps
  143. // to the lane's session and socket below. Relay and base traffic stays on
  144. // tx.base (socket 0).
  145. func (f *Interface) sendInsideMessage(hostinfo *HostInfo, pkt tio.Packet, nb []byte, tx *txQueue) {
  146. ci := hostinfo.ConnectionState
  147. if ci.eKey == nil {
  148. return
  149. }
  150. sendBatch := tx.base
  151. remote := hostinfo.GetRemote()
  152. ecnEnabled := f.ecnEnabled.Load()
  153. if hostinfo.lastRebindCount != f.rebindCount {
  154. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  155. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  156. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  157. hostinfo.lastRebindCount = f.rebindCount
  158. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  159. hostinfo.logger(f.l).Debug("Lighthouse update triggered for punch due to rebind counter",
  160. "vpnAddrs", hostinfo.vpnAddrs,
  161. )
  162. }
  163. }
  164. if !remote.IsValid() { //the relay path
  165. //first, find our relay hostinfo:
  166. var relayHostInfo *HostInfo
  167. var relay *Relay
  168. var err error
  169. for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
  170. relayHostInfo, relay, err = f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relayIP)
  171. if err != nil {
  172. hostinfo.relayState.DeleteRelay(relayIP)
  173. hostinfo.logger(f.l).Info("sendNoMetrics failed to find HostInfo",
  174. "relay", relayIP,
  175. "error", err,
  176. )
  177. continue
  178. }
  179. break
  180. }
  181. if relayHostInfo == nil || relay == nil {
  182. //failure already logged
  183. return
  184. }
  185. err = tio.SegmentSuperpacket(pkt, func(seg []byte) error {
  186. //relay header + header + plaintext + AEAD tag (16 bytes for both AES-GCM and ChaCha20-Poly1305) + relay tag
  187. scratch := sendBatch.Reserve(header.Len + header.Len + len(seg) + 16 + 16)
  188. innerPacket := f.sendInsideEncrypt(hostinfo, ci, seg, scratch[header.Len:], nb)
  189. if innerPacket == nil {
  190. return nil
  191. }
  192. //now we need to do a relay-encrypt:
  193. toSend, err := f.prepareSendVia(relayHostInfo, relay, innerPacket, nb, scratch, true)
  194. if err != nil {
  195. //already logged
  196. return nil
  197. }
  198. var ecn byte
  199. if ecnEnabled {
  200. ecn = innerECN(seg)
  201. }
  202. sendBatch.Commit(toSend, relayHostInfo.GetRemote(), ecn)
  203. return nil
  204. })
  205. if err != nil {
  206. hostinfo.logger(f.l).Error("Failed to segment superpacket for relay send", "error", err)
  207. }
  208. return
  209. }
  210. // Direct path: prefer this routine's lane tunnel when it is established.
  211. // The pointer is only published once the lane's ConnectionState is fully
  212. // populated, so a non-nil Load is always usable. On lane death the slot
  213. // CAS-clears and traffic falls back to the base tunnel instantly.
  214. if ls := hostinfo.lanes; ls != nil && tx.laneSlot < len(ls.txLanes) {
  215. if lane := ls.txLanes[tx.laneSlot].Load(); lane != nil {
  216. if lci := lane.ConnectionState; lci != nil && lci.eKey != nil {
  217. hostinfo = lane
  218. ci = lci
  219. remote = lane.GetRemote()
  220. sendBatch = tx.lane
  221. }
  222. }
  223. }
  224. err := tio.SegmentSuperpacket(pkt, func(seg []byte) error {
  225. // header + plaintext + AEAD tag (16 bytes for both AES-GCM and ChaCha20-Poly1305)
  226. scratch := sendBatch.Reserve(header.Len + len(seg) + 16)
  227. out := f.sendInsideEncrypt(hostinfo, ci, seg, scratch, nb)
  228. if out == nil {
  229. return nil
  230. }
  231. var ecn byte
  232. if ecnEnabled {
  233. ecn = innerECN(seg)
  234. }
  235. sendBatch.Commit(out, remote, ecn)
  236. return nil
  237. })
  238. if err != nil {
  239. hostinfo.logger(f.l).Error("Failed to segment superpacket for send",
  240. "error", err,
  241. )
  242. }
  243. }
  244. // innerECN returns the 2-bit IP-level ECN codepoint of an inner IPv4 or IPv6
  245. // packet, or 0 if pkt is too short or its IP version is unrecognized. Used at
  246. // encap to copy the inner codepoint onto the outer carrier per RFC 6040.
  247. func innerECN(pkt []byte) byte {
  248. if len(pkt) < 2 {
  249. return 0
  250. }
  251. switch pkt[0] >> 4 {
  252. case 4:
  253. return pkt[1] & 0x03
  254. case 6:
  255. return (pkt[1] >> 4) & 0x03
  256. }
  257. return 0
  258. }
  259. func (f *Interface) rejectInside(packet []byte, out []byte, q int) {
  260. if !f.firewall.OutboundSendReject {
  261. return
  262. }
  263. out = iputil.CreateRejectPacket(packet, out)
  264. if len(out) == 0 {
  265. return
  266. }
  267. _, err := f.queues[q].Write(out)
  268. if err != nil {
  269. f.l.Error("Failed to write to tun", "error", err)
  270. }
  271. }
  272. func (f *Interface) rejectOutside(packet []byte, ci *ConnectionState, hostinfo *HostInfo, nb, rejectBuf []byte) {
  273. if !f.firewall.InboundSendReject {
  274. return
  275. }
  276. // split rejectBuf to make sure we have room to write the plaintext rejection, then encrypt it, without trampling anything
  277. // we can't re-use packet, if we need to send an icmp reject, it won't be long enough.
  278. half := len(rejectBuf) / 2
  279. encryptBuf := rejectBuf[0:0:half] //the first half of rejectBuf's capacity, len set to 0
  280. buildBuf := rejectBuf[half:]
  281. out := iputil.CreateRejectPacket(packet, buildBuf)
  282. if len(out) == 0 {
  283. return
  284. }
  285. if len(out) > iputil.MaxRejectPacketSize {
  286. if f.l.Enabled(context.Background(), slog.LevelInfo) {
  287. f.l.Info("rejectOutside: packet too big, not sending", "packet", packet, "outPacket", out)
  288. }
  289. return
  290. }
  291. f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, out, nb, encryptBuf)
  292. }
  293. // Handshake will attempt to initiate a tunnel with the provided vpn address. This is a no-op if the tunnel is already established or being established
  294. // it does not check if it is within our vpn networks!
  295. func (f *Interface) Handshake(vpnAddr netip.Addr) {
  296. f.handshakeManager.GetOrHandshake(vpnAddr, nil)
  297. }
  298. // getOrHandshakeNoRouting returns nil if the vpnAddr is not routable.
  299. // If the 2nd return var is false then the hostinfo is not ready to be used in a tunnel
  300. func (f *Interface) getOrHandshakeNoRouting(vpnAddr netip.Addr, cacheCallback func(*HandshakeHostInfo)) (*HostInfo, bool) {
  301. if f.myVpnNetworksTable.Contains(vpnAddr) {
  302. return f.handshakeManager.GetOrHandshake(vpnAddr, cacheCallback)
  303. }
  304. return nil, false
  305. }
  306. // getOrHandshakeConsiderRouting will try to find the HostInfo to handle this packet, starting a handshake if necessary.
  307. // If the 2nd return var is false then the hostinfo is not ready to be used in a tunnel.
  308. func (f *Interface) getOrHandshakeConsiderRouting(fwPacket *firewall.Packet, cacheCallback func(*HandshakeHostInfo)) (*HostInfo, bool) {
  309. destinationAddr := fwPacket.RemoteAddr
  310. hostinfo, ready := f.getOrHandshakeNoRouting(destinationAddr, cacheCallback)
  311. // Host is inside the mesh, no routing required
  312. if hostinfo != nil {
  313. return hostinfo, ready
  314. }
  315. gateways := f.inside.RoutesFor(destinationAddr)
  316. switch len(gateways) {
  317. case 0:
  318. return nil, false
  319. case 1:
  320. // Single gateway route
  321. return f.handshakeManager.GetOrHandshake(gateways[0].Addr(), cacheCallback)
  322. default:
  323. // Multi gateway route, perform ECMP categorization
  324. gatewayAddr, balancingOk := routing.BalancePacket(fwPacket, gateways)
  325. if !balancingOk {
  326. // This happens if the gateway buckets were not calculated, this _should_ never happen
  327. f.l.Error("Gateway buckets not calculated, fallback from ECMP to random routing. Please report this bug.")
  328. }
  329. var handshakeInfoForChosenGateway *HandshakeHostInfo
  330. var hhReceiver = func(hh *HandshakeHostInfo) {
  331. handshakeInfoForChosenGateway = hh
  332. }
  333. // Store the handshakeHostInfo for later.
  334. // If this node is not reachable we will attempt other nodes, if none are reachable we will
  335. // cache the packet for this gateway.
  336. if hostinfo, ready = f.handshakeManager.GetOrHandshake(gatewayAddr, hhReceiver); ready {
  337. return hostinfo, true
  338. }
  339. // It appears the selected gateway cannot be reached, find another gateway to fallback on.
  340. // The current implementation breaks ECMP but that seems better than no connectivity.
  341. // If ECMP is also required when a gateway is down then connectivity status
  342. // for each gateway needs to be kept and the weights recalculated when they go up or down.
  343. // This would also need to interact with unsafe_route updates through reloading the config or
  344. // use of the use_system_route_table option
  345. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  346. f.l.Debug("Calculated gateway for ECMP not available, attempting other gateways",
  347. "destination", destinationAddr,
  348. "originalGateway", gatewayAddr,
  349. )
  350. }
  351. for i := range gateways {
  352. // Skip the gateway that failed previously
  353. if gateways[i].Addr() == gatewayAddr {
  354. continue
  355. }
  356. // We do not need the HandshakeHostInfo since we cache the packet in the originally chosen gateway
  357. if hostinfo, ready = f.handshakeManager.GetOrHandshake(gateways[i].Addr(), nil); ready {
  358. return hostinfo, true
  359. }
  360. }
  361. // No gateways reachable, cache the packet in the originally chosen gateway
  362. cacheCallback(handshakeInfoForChosenGateway)
  363. return hostinfo, false
  364. }
  365. }
  366. func (f *Interface) sendMessageNow(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p, nb, out []byte) {
  367. fp := &firewall.Packet{}
  368. err := newPacket(p, false, fp)
  369. if err != nil {
  370. f.l.Warn("error while parsing outgoing packet for firewall check", "error", err)
  371. return
  372. }
  373. // check if packet is in outbound fw rules
  374. dropReason := f.firewall.Drop(*fp, false, hostinfo, f.pki.GetCAPool(), nil)
  375. if dropReason != nil {
  376. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  377. f.l.Debug("dropping cached packet",
  378. "fwPacket", fp,
  379. "reason", dropReason,
  380. )
  381. }
  382. return
  383. }
  384. f.sendNoMetrics(header.Message, st, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, p, nb, out)
  385. }
  386. // SendMessageToVpnAddr handles real addr:port lookup and sends to the current best known address for vpnAddr.
  387. // This function ignores myVpnNetworksTable, and will always attempt to treat the address as a vpnAddr
  388. func (f *Interface) SendMessageToVpnAddr(t header.MessageType, st header.MessageSubType, vpnAddr netip.Addr, p, nb, out []byte) {
  389. hostInfo, ready := f.handshakeManager.GetOrHandshake(vpnAddr, func(hh *HandshakeHostInfo) {
  390. hh.cachePacket(f.l, t, st, p, f.SendMessageToHostInfo, f.cachedPacketMetrics)
  391. })
  392. if hostInfo == nil {
  393. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  394. f.l.Debug("dropping SendMessageToVpnAddr, vpnAddr not in our vpn networks or in unsafe routes",
  395. "vpnAddr", vpnAddr,
  396. )
  397. }
  398. return
  399. }
  400. if !ready {
  401. return
  402. }
  403. f.SendMessageToHostInfo(t, st, hostInfo, p, nb, out)
  404. }
  405. func (f *Interface) SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hi *HostInfo, p, nb, out []byte) {
  406. f.send(t, st, hi.ConnectionState, hi, p, nb, out)
  407. }
  408. func (f *Interface) send(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, p, nb, out []byte) {
  409. f.messageMetrics.Tx(t, st, 1)
  410. f.sendNoMetrics(t, st, ci, hostinfo, netip.AddrPort{}, p, nb, out)
  411. }
  412. func (f *Interface) sendTo(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte) {
  413. f.messageMetrics.Tx(t, st, 1)
  414. f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out)
  415. }
  416. func (f *Interface) prepareSendVia(via *HostInfo,
  417. relay *Relay,
  418. ad,
  419. nb,
  420. out []byte,
  421. nocopy bool,
  422. ) ([]byte, error) {
  423. if noiseutil.EncryptLockNeeded {
  424. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  425. via.ConnectionState.writeLock.Lock()
  426. }
  427. c := via.ConnectionState.messageCounter.Add(1)
  428. out = header.Encode(out, header.Version, header.Message, header.MessageRelay, relay.RemoteIndex, c)
  429. f.connectionManager.Out(via)
  430. // Authenticate the header and payload, but do not encrypt for this message type.
  431. // The payload consists of the inner, unencrypted Nebula header, as well as the end-to-end encrypted payload.
  432. if len(out)+len(ad)+via.ConnectionState.eKey.Overhead() > cap(out) {
  433. if noiseutil.EncryptLockNeeded {
  434. via.ConnectionState.writeLock.Unlock()
  435. }
  436. via.logger(f.l).Error("SendVia out buffer not large enough for relay",
  437. "outCap", cap(out),
  438. "payloadLen", len(ad),
  439. "headerLen", len(out),
  440. "cipherOverhead", via.ConnectionState.eKey.Overhead(),
  441. )
  442. return nil, io.ErrShortBuffer
  443. }
  444. // The header bytes are written to the 'out' slice; Grow the slice to hold the header and associated data payload.
  445. offset := len(out)
  446. out = out[:offset+len(ad)]
  447. // In one call path, the associated data _is_ already stored in out. In other call paths, the associated data must
  448. // be copied into 'out'.
  449. if !nocopy {
  450. copy(out[offset:], ad)
  451. }
  452. var err error
  453. out, err = via.ConnectionState.eKey.EncryptDanger(out, out, nil, c, nb)
  454. if noiseutil.EncryptLockNeeded {
  455. via.ConnectionState.writeLock.Unlock()
  456. }
  457. if err != nil {
  458. via.logger(f.l).Info("Failed to EncryptDanger in sendVia", "error", err)
  459. return nil, err
  460. }
  461. f.connectionManager.RelayUsed(relay.LocalIndex)
  462. return out, nil
  463. }
  464. // SendVia sends a payload through a Relay tunnel. No authentication or encryption is done
  465. // to the payload for the ultimate target host, making this a useful method for sending
  466. // handshake messages to peers through relay tunnels.
  467. // via is the HostInfo through which the message is relayed.
  468. // ad is the plaintext data to authenticate, but not encrypt
  469. // nb is a buffer used to store the nonce value, re-used for performance reasons.
  470. // out is a buffer used to store the result of the Encrypt operation
  471. // q indicates which writer to use to send the packet.
  472. func (f *Interface) SendVia(via *HostInfo,
  473. relay *Relay,
  474. ad,
  475. nb,
  476. out []byte,
  477. nocopy bool,
  478. ) {
  479. toSend, err := f.prepareSendVia(via, relay, ad, nb, out, nocopy)
  480. if err != nil {
  481. // already logged by prepareSendVia
  482. return
  483. }
  484. // Relay carriers are base tunnels (sockIdx 0); indexing through the
  485. // carrier keeps the invariant explicit.
  486. err = f.writers[via.sockIdx].WriteTo(toSend, via.GetRemote())
  487. if err != nil {
  488. via.logger(f.l).Info("Failed to WriteTo in sendVia", "error", err)
  489. }
  490. }
  491. func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte) {
  492. if ci.eKey == nil {
  493. return
  494. }
  495. // Every packet on a tunnel egresses the tunnel's own socket. For base and
  496. // vanilla tunnels sockIdx is 0 (stock behavior); for lanes it keeps
  497. // keepalives, close packets and rejects on the lane's 4-tuple so the
  498. // peer's spoof/roam checks accept them and the NAT entry stays warm.
  499. q := hostinfo.sockIdx
  500. useRelay := !remote.IsValid() && !hostinfo.GetRemote().IsValid()
  501. fullOut := out
  502. if useRelay {
  503. if len(out) < header.Len {
  504. // out always has a capacity of mtu, but not always a length greater than the header.Len.
  505. // Grow it to make sure the next operation works.
  506. out = out[:header.Len]
  507. }
  508. // Save a header's worth of data at the front of the 'out' buffer.
  509. out = out[header.Len:]
  510. }
  511. if noiseutil.EncryptLockNeeded {
  512. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  513. ci.writeLock.Lock()
  514. }
  515. c := ci.messageCounter.Add(1)
  516. //l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
  517. out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
  518. f.connectionManager.Out(hostinfo)
  519. // Query our LH if we haven't since the last time we've been rebound, this will cause the remote to punch against
  520. // all our addrs and enable a faster roaming.
  521. // Lanes skip this: the base tunnel issues the one query for the peer.
  522. if t != header.CloseTunnel && !hostinfo.isLane() && hostinfo.lastRebindCount != f.rebindCount {
  523. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  524. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  525. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  526. hostinfo.lastRebindCount = f.rebindCount
  527. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  528. f.l.Debug("Lighthouse update triggered for punch due to rebind counter",
  529. "vpnAddrs", hostinfo.vpnAddrs,
  530. )
  531. }
  532. }
  533. var err error
  534. out, err = ci.eKey.EncryptDanger(out, out, p, c, nb)
  535. if noiseutil.EncryptLockNeeded {
  536. ci.writeLock.Unlock()
  537. }
  538. if err != nil {
  539. hostinfo.logger(f.l).Error("Failed to encrypt outgoing packet",
  540. "error", err,
  541. "udpAddr", remote,
  542. "counter", c,
  543. )
  544. return
  545. }
  546. if remote.IsValid() {
  547. err = f.writers[q].WriteTo(out, remote)
  548. if err != nil {
  549. hostinfo.logger(f.l).Error("Failed to write outgoing packet",
  550. "error", err,
  551. "udpAddr", remote,
  552. )
  553. }
  554. } else if hr := hostinfo.GetRemote(); hr.IsValid() {
  555. err = f.writers[q].WriteTo(out, hr)
  556. if err != nil {
  557. hostinfo.logger(f.l).Error("Failed to write outgoing packet",
  558. "error", err,
  559. "udpAddr", remote,
  560. )
  561. }
  562. } else {
  563. if hostinfo.isLane() {
  564. // A lane always has a valid remote (set from its own handshake);
  565. // reaching here means the lane is broken, and lane ciphertext must
  566. // never ride a relay (relays are base-tunnel-only).
  567. hostinfo.logger(f.l).Error("Dropping lane packet with no valid remote")
  568. return
  569. }
  570. // Try to send via a relay
  571. for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
  572. relayHostInfo, relay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relayIP)
  573. if err != nil {
  574. hostinfo.relayState.DeleteRelay(relayIP)
  575. hostinfo.logger(f.l).Info("sendNoMetrics failed to find HostInfo",
  576. "relay", relayIP,
  577. "error", err,
  578. )
  579. continue
  580. }
  581. f.SendVia(relayHostInfo, relay, out, nb, fullOut[:header.Len+len(out)], true)
  582. break
  583. }
  584. }
  585. }