inside.go 20 KB

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