1
0

inside.go 20 KB

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