inside.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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 parse +
  26. // firewall check covers the whole superpacket.
  27. packet := pkt.Bytes
  28. var parsed batch.RxParsed
  29. if err := batch.ParsePacket(packet, false, &parsed); 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. parsed.Key.Hydrate(fwPacket)
  39. // Ignore local broadcast packets
  40. if f.dropLocalBroadcast {
  41. if f.myBroadcastAddrsTable.Contains(fwPacket.RemoteAddr) {
  42. return
  43. }
  44. }
  45. if f.myVpnAddrsTable.Contains(fwPacket.RemoteAddr) {
  46. // Immediately forward packets from self to self.
  47. // This should only happen on Darwin-based and FreeBSD hosts, which
  48. // routes packets from the Nebula addr to the Nebula addr through the Nebula
  49. // TUN device.
  50. if immediatelyForwardToSelf {
  51. // Write copies into the kernel queue synchronously, so seg's lifetime ends at return.
  52. // A self-forwarded superpacket would be re-handed to the
  53. // kernel as one giant blob; segment first so the loopback
  54. // path sees one IP datagram per Write.
  55. err := tio.SegmentSuperpacket(pkt, func(seg []byte) error {
  56. _, werr := f.readers[q].Write(seg)
  57. return werr
  58. })
  59. if err != nil {
  60. f.l.Error("Failed to forward to tun", "error", err)
  61. }
  62. }
  63. // Otherwise, drop. On linux, we should never see these packets - Linux
  64. // routes packets from the nebula addr to the nebula addr through the loopback device.
  65. return
  66. }
  67. // Ignore multicast packets
  68. if f.dropMulticast && fwPacket.RemoteAddr.IsMulticast() {
  69. return
  70. }
  71. hostinfo, ready := f.getOrHandshakeConsiderRouting(fwPacket, func(hh *HandshakeHostInfo) {
  72. // borrowed: SegmentSuperpacket builds each segment in the kernel-supplied pkt
  73. // bytes underneath. cachePacket explicitly copies its argument (handshake_manager.go cachePacket),
  74. // so retaining segments past the loop is safe.
  75. err := tio.SegmentSuperpacket(pkt, func(seg []byte) error {
  76. hh.cachePacket(f.l, header.Message, 0, seg, f.sendMessageNow, f.cachedPacketMetrics)
  77. return nil
  78. })
  79. if err != nil && f.l.Enabled(context.Background(), slog.LevelDebug) {
  80. f.l.Debug("Failed to segment superpacket for handshake cache",
  81. "error", err,
  82. "vpnAddr", fwPacket.RemoteAddr,
  83. )
  84. }
  85. })
  86. if hostinfo == nil {
  87. f.rejectInside(packet, rejectBuf, q)
  88. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  89. f.l.Debug("dropping outbound packet, vpnAddr not in our vpn networks or in unsafe networks",
  90. "vpnAddr", fwPacket.RemoteAddr,
  91. "fwPacket", fwPacket,
  92. )
  93. }
  94. return
  95. }
  96. if !ready {
  97. return
  98. }
  99. dropReason := f.firewall.Drop(parsed.Key, fwPacket, false, hostinfo, f.pki.GetCAPool(), localCache)
  100. if dropReason == nil {
  101. f.sendInsideMessage(hostinfo, pkt, nb, sendBatch, rejectBuf, q)
  102. } else {
  103. f.rejectInside(packet, rejectBuf, q)
  104. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  105. hostinfo.logger(f.l).Debug("dropping outbound packet",
  106. "fwPacket", fwPacket,
  107. "reason", dropReason,
  108. )
  109. }
  110. }
  111. }
  112. func (f *Interface) sendInsideEncrypt(hostinfo *HostInfo, ci *ConnectionState, seg, scratch, nb []byte) []byte {
  113. if noiseutil.EncryptLockNeeded {
  114. ci.writeLock.Lock()
  115. }
  116. c := ci.messageCounter.Add(1)
  117. out := header.Encode(scratch, header.Version, header.Message, 0, hostinfo.remoteIndexId, c)
  118. f.connectionManager.Out(hostinfo)
  119. out, encErr := ci.eKey.EncryptDanger(out, out, seg, c, nb)
  120. if noiseutil.EncryptLockNeeded {
  121. ci.writeLock.Unlock()
  122. }
  123. if encErr != nil {
  124. hostinfo.logger(f.l).Error("Failed to encrypt outgoing packet",
  125. "error", encErr,
  126. "udpAddr", hostinfo.remote,
  127. "counter", c,
  128. )
  129. // Skip this segment; the rest of the superpacket can still
  130. // go out — TCP will retransmit anything we drop here.
  131. return nil
  132. }
  133. return out
  134. }
  135. // sendInsideMessage encrypts a firewall-approved inside packet (or every
  136. // segment of a TSO/USO superpacket) into the caller's batch slot for
  137. // later sendmmsg flush. Segmentation is fused with encryption here so the
  138. // kernel-supplied superpacket bytes never get written into a separate
  139. // scratch arena: SegmentSuperpacket builds each segment's plaintext in
  140. // segScratch[:segLen] in turn, and we encrypt directly into a fresh
  141. // SendBatch slot.
  142. func (f *Interface) sendInsideMessage(hostinfo *HostInfo, pkt tio.Packet, nb []byte, sendBatch batch.TxBatcher, rejectBuf []byte, q int) {
  143. ci := hostinfo.ConnectionState
  144. if ci.eKey == nil {
  145. return
  146. }
  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 !hostinfo.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.remote, 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, hostinfo.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.InSendReject {
  242. return
  243. }
  244. out = iputil.CreateRejectPacket(packet, out)
  245. if len(out) == 0 {
  246. return
  247. }
  248. _, err := f.readers[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.OutSendReject {
  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. var parsed batch.RxParsed
  347. if err := batch.ParsePacket(p, false, &parsed); err != nil {
  348. f.l.Warn("error while parsing outgoing packet for firewall check", "error", err)
  349. return
  350. }
  351. fp := &firewall.Packet{}
  352. parsed.Key.Hydrate(fp)
  353. // check if packet is in outbound fw rules
  354. dropReason := f.firewall.Drop(parsed.Key, fp, false, hostinfo, f.pki.GetCAPool(), nil)
  355. if dropReason != nil {
  356. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  357. f.l.Debug("dropping cached packet",
  358. "fwPacket", fp,
  359. "reason", dropReason,
  360. )
  361. }
  362. return
  363. }
  364. f.sendNoMetrics(header.Message, st, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, p, nb, out, 0)
  365. }
  366. // SendMessageToVpnAddr handles real addr:port lookup and sends to the current best known address for vpnAddr.
  367. // This function ignores myVpnNetworksTable, and will always attempt to treat the address as a vpnAddr
  368. func (f *Interface) SendMessageToVpnAddr(t header.MessageType, st header.MessageSubType, vpnAddr netip.Addr, p, nb, out []byte) {
  369. hostInfo, ready := f.handshakeManager.GetOrHandshake(vpnAddr, func(hh *HandshakeHostInfo) {
  370. hh.cachePacket(f.l, t, st, p, f.SendMessageToHostInfo, f.cachedPacketMetrics)
  371. })
  372. if hostInfo == nil {
  373. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  374. f.l.Debug("dropping SendMessageToVpnAddr, vpnAddr not in our vpn networks or in unsafe routes",
  375. "vpnAddr", vpnAddr,
  376. )
  377. }
  378. return
  379. }
  380. if !ready {
  381. return
  382. }
  383. f.SendMessageToHostInfo(t, st, hostInfo, p, nb, out)
  384. }
  385. func (f *Interface) SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hi *HostInfo, p, nb, out []byte) {
  386. f.send(t, st, hi.ConnectionState, hi, p, nb, out)
  387. }
  388. func (f *Interface) send(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, p, nb, out []byte) {
  389. f.messageMetrics.Tx(t, st, 1)
  390. f.sendNoMetrics(t, st, ci, hostinfo, netip.AddrPort{}, p, nb, out, 0)
  391. }
  392. func (f *Interface) sendTo(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte) {
  393. f.messageMetrics.Tx(t, st, 1)
  394. f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out, 0)
  395. }
  396. func (f *Interface) prepareSendVia(via *HostInfo,
  397. relay *Relay,
  398. ad,
  399. nb,
  400. out []byte,
  401. nocopy bool,
  402. ) ([]byte, error) {
  403. if noiseutil.EncryptLockNeeded {
  404. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  405. via.ConnectionState.writeLock.Lock()
  406. }
  407. c := via.ConnectionState.messageCounter.Add(1)
  408. out = header.Encode(out, header.Version, header.Message, header.MessageRelay, relay.RemoteIndex, c)
  409. f.connectionManager.Out(via)
  410. // Authenticate the header and payload, but do not encrypt for this message type.
  411. // The payload consists of the inner, unencrypted Nebula header, as well as the end-to-end encrypted payload.
  412. if len(out)+len(ad)+via.ConnectionState.eKey.Overhead() > cap(out) {
  413. if noiseutil.EncryptLockNeeded {
  414. via.ConnectionState.writeLock.Unlock()
  415. }
  416. via.logger(f.l).Error("SendVia out buffer not large enough for relay",
  417. "outCap", cap(out),
  418. "payloadLen", len(ad),
  419. "headerLen", len(out),
  420. "cipherOverhead", via.ConnectionState.eKey.Overhead(),
  421. )
  422. return nil, io.ErrShortBuffer
  423. }
  424. // The header bytes are written to the 'out' slice; Grow the slice to hold the header and associated data payload.
  425. offset := len(out)
  426. out = out[:offset+len(ad)]
  427. // In one call path, the associated data _is_ already stored in out. In other call paths, the associated data must
  428. // be copied into 'out'.
  429. if !nocopy {
  430. copy(out[offset:], ad)
  431. }
  432. var err error
  433. out, err = via.ConnectionState.eKey.EncryptDanger(out, out, nil, c, nb)
  434. if noiseutil.EncryptLockNeeded {
  435. via.ConnectionState.writeLock.Unlock()
  436. }
  437. if err != nil {
  438. via.logger(f.l).Info("Failed to EncryptDanger in sendVia", "error", err)
  439. return nil, err
  440. }
  441. f.connectionManager.RelayUsed(relay.LocalIndex)
  442. return out, nil
  443. }
  444. // SendVia sends a payload through a Relay tunnel. No authentication or encryption is done
  445. // to the payload for the ultimate target host, making this a useful method for sending
  446. // handshake messages to peers through relay tunnels.
  447. // via is the HostInfo through which the message is relayed.
  448. // ad is the plaintext data to authenticate, but not encrypt
  449. // nb is a buffer used to store the nonce value, re-used for performance reasons.
  450. // out is a buffer used to store the result of the Encrypt operation
  451. // q indicates which writer to use to send the packet.
  452. func (f *Interface) SendVia(via *HostInfo,
  453. relay *Relay,
  454. ad,
  455. nb,
  456. out []byte,
  457. nocopy bool,
  458. ) {
  459. toSend, err := f.prepareSendVia(via, relay, ad, nb, out, nocopy)
  460. err = f.writers[0].WriteTo(toSend, via.remote)
  461. if err != nil {
  462. via.logger(f.l).Info("Failed to WriteTo in sendVia", "error", err)
  463. }
  464. }
  465. func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte, q int) {
  466. if ci.eKey == nil {
  467. return
  468. }
  469. useRelay := !remote.IsValid() && !hostinfo.remote.IsValid()
  470. fullOut := out
  471. if useRelay {
  472. if len(out) < header.Len {
  473. // out always has a capacity of mtu, but not always a length greater than the header.Len.
  474. // Grow it to make sure the next operation works.
  475. out = out[:header.Len]
  476. }
  477. // Save a header's worth of data at the front of the 'out' buffer.
  478. out = out[header.Len:]
  479. }
  480. if noiseutil.EncryptLockNeeded {
  481. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  482. ci.writeLock.Lock()
  483. }
  484. c := ci.messageCounter.Add(1)
  485. //l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
  486. out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
  487. f.connectionManager.Out(hostinfo)
  488. // Query our LH if we haven't since the last time we've been rebound, this will cause the remote to punch against
  489. // all our addrs and enable a faster roaming.
  490. if t != header.CloseTunnel && hostinfo.lastRebindCount != f.rebindCount {
  491. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  492. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  493. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  494. hostinfo.lastRebindCount = f.rebindCount
  495. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  496. f.l.Debug("Lighthouse update triggered for punch due to rebind counter",
  497. "vpnAddrs", hostinfo.vpnAddrs,
  498. )
  499. }
  500. }
  501. var err error
  502. out, err = ci.eKey.EncryptDanger(out, out, p, c, nb)
  503. if noiseutil.EncryptLockNeeded {
  504. ci.writeLock.Unlock()
  505. }
  506. if err != nil {
  507. hostinfo.logger(f.l).Error("Failed to encrypt outgoing packet",
  508. "error", err,
  509. "udpAddr", remote,
  510. "counter", c,
  511. "attemptedCounter", c,
  512. )
  513. return
  514. }
  515. if remote.IsValid() {
  516. err = f.writers[q].WriteTo(out, remote)
  517. if err != nil {
  518. hostinfo.logger(f.l).Error("Failed to write outgoing packet",
  519. "error", err,
  520. "udpAddr", remote,
  521. )
  522. }
  523. } else if hostinfo.remote.IsValid() {
  524. err = f.writers[q].WriteTo(out, hostinfo.remote)
  525. if err != nil {
  526. hostinfo.logger(f.l).Error("Failed to write outgoing packet",
  527. "error", err,
  528. "udpAddr", remote,
  529. )
  530. }
  531. } else {
  532. // Try to send via a relay
  533. for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
  534. relayHostInfo, relay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relayIP)
  535. if err != nil {
  536. hostinfo.relayState.DeleteRelay(relayIP)
  537. hostinfo.logger(f.l).Info("sendNoMetrics failed to find HostInfo",
  538. "relay", relayIP,
  539. "error", err,
  540. )
  541. continue
  542. }
  543. f.SendVia(relayHostInfo, relay, out, nb, fullOut[:header.Len+len(out)], true)
  544. break
  545. }
  546. }
  547. }