1
0

inside.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. package nebula
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "log/slog"
  7. "net/netip"
  8. "github.com/slackhq/nebula/firewall"
  9. "github.com/slackhq/nebula/header"
  10. "github.com/slackhq/nebula/iputil"
  11. "github.com/slackhq/nebula/noiseutil"
  12. "github.com/slackhq/nebula/overlay/batch"
  13. "github.com/slackhq/nebula/overlay/tio"
  14. "github.com/slackhq/nebula/routing"
  15. )
  16. func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.ParsedPacket, nb []byte, sendBatch *batch.SendBatch, rejectBuf []byte, q int, localCache firewall.ConntrackCache) {
  17. // borrowed: pkt.Bytes is owned by the originating tio.Queue and is
  18. // only valid until the next Read on that queue. Every consumer below
  19. // (parse, self-forward, handshake cache, sendInsideMessage) reads it
  20. // synchronously; do not retain pkt outside this call. If a future
  21. // caller needs to keep the packet, use pkt.Clone() to detach it from
  22. // the borrow.
  23. //
  24. // pkt.Bytes is either one IP datagram (GSO zero) or a TSO/USO
  25. // superpacket. In both cases the L3+L4 headers at the start describe
  26. // the same 5-tuple every segment will share, so a single newPacket /
  27. // firewall check covers the whole superpacket.
  28. packet := pkt.Bytes
  29. err := newPacket(packet, false, fwPacket)
  30. if err != nil {
  31. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  32. f.l.Debug("Error while validating outbound packet",
  33. "packet", packet,
  34. "error", err,
  35. )
  36. }
  37. return
  38. }
  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.queues[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.Packet, 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(fwPacket.Packet, false, hostinfo, f.pki.GetCAPool(), localCache)
  100. if dropReason == nil {
  101. f.sendInsideMessage(hostinfo, pkt, nb, sendBatch)
  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. 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 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 SendBatch slot.
  139. func (f *Interface) sendInsideMessage(hostinfo *HostInfo, pkt tio.Packet, nb []byte, sendBatch *batch.SendBatch) {
  140. ci := hostinfo.ConnectionState
  141. if ci.eKey == nil {
  142. return
  143. }
  144. // One traffic-out mark covers every segment of the superpacket; doing it
  145. // per segment in sendInsideEncrypt paid an atomic store up to ~45 extra
  146. // times per TSO packet, inside writeLock under boring crypto.
  147. f.connectionManager.Out(hostinfo)
  148. remote := hostinfo.GetRemote()
  149. if hostinfo.lastRebindCount != f.rebindCount {
  150. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  151. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  152. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  153. hostinfo.lastRebindCount = f.rebindCount
  154. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  155. hostinfo.logger(f.l).Debug("Lighthouse update triggered for punch due to rebind counter",
  156. "vpnAddrs", hostinfo.vpnAddrs,
  157. )
  158. }
  159. }
  160. if !remote.IsValid() { //the relay path
  161. //first, find our relay hostinfo:
  162. var relayHostInfo *HostInfo
  163. var relay *Relay
  164. var err error
  165. for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
  166. relayHostInfo, relay, err = f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relayIP)
  167. if err != nil {
  168. hostinfo.relayState.DeleteRelay(relayIP)
  169. hostinfo.logger(f.l).Info("sendNoMetrics failed to find HostInfo",
  170. "relay", relayIP,
  171. "error", err,
  172. )
  173. continue
  174. }
  175. break
  176. }
  177. if relayHostInfo == nil || relay == nil {
  178. //failure already logged
  179. return
  180. }
  181. err = tio.SegmentSuperpacket(pkt, func(seg []byte) error {
  182. //relay header + header + plaintext + AEAD tag (16 bytes for both AES-GCM and ChaCha20-Poly1305) + relay tag
  183. scratch := sendBatch.Reserve(header.Len + header.Len + len(seg) + 16 + 16)
  184. innerPacket := f.sendInsideEncrypt(hostinfo, ci, seg, scratch[header.Len:], nb)
  185. if innerPacket == nil {
  186. return nil
  187. }
  188. //now we need to do a relay-encrypt:
  189. toSend, err := f.prepareSendVia(relayHostInfo, relay, innerPacket, nb, scratch, true)
  190. if err != nil {
  191. //already logged
  192. return nil
  193. }
  194. sendBatch.Commit(toSend, relayHostInfo.GetRemote())
  195. return nil
  196. })
  197. if err != nil {
  198. hostinfo.logger(f.l).Error("Failed to segment superpacket for relay send", "error", err)
  199. }
  200. return
  201. }
  202. err := tio.SegmentSuperpacket(pkt, func(seg []byte) error {
  203. // header + plaintext + AEAD tag (16 bytes for both AES-GCM and ChaCha20-Poly1305)
  204. scratch := sendBatch.Reserve(header.Len + len(seg) + 16)
  205. out := f.sendInsideEncrypt(hostinfo, ci, seg, scratch, nb)
  206. if out == nil {
  207. return nil
  208. }
  209. sendBatch.Commit(out, remote)
  210. return nil
  211. })
  212. if err != nil {
  213. hostinfo.logger(f.l).Error("Failed to segment superpacket for send", "error", err)
  214. }
  215. }
  216. func (f *Interface) rejectInside(packet []byte, out []byte, q int) {
  217. if !f.firewall.OutboundSendReject {
  218. return
  219. }
  220. out = iputil.CreateRejectPacket(packet, out)
  221. if len(out) == 0 {
  222. return
  223. }
  224. _, err := f.queues[q].Write(out)
  225. if err != nil {
  226. f.l.Error("Failed to write to tun", "error", err)
  227. }
  228. }
  229. func (f *Interface) rejectOutside(packet []byte, ci *ConnectionState, hostinfo *HostInfo, nb, rejectBuf []byte, q int) {
  230. if !f.firewall.InboundSendReject {
  231. return
  232. }
  233. // split rejectBuf to make sure we have room to write the plaintext rejection, then encrypt it, without trampling anything
  234. // we can't re-use packet, if we need to send an icmp reject, it won't be long enough.
  235. half := len(rejectBuf) / 2
  236. encryptBuf := rejectBuf[0:0:half] //the first half of rejectBuf's capacity, len set to 0
  237. buildBuf := rejectBuf[half:]
  238. out := iputil.CreateRejectPacket(packet, buildBuf)
  239. if len(out) == 0 {
  240. return
  241. }
  242. if len(out) > iputil.MaxRejectPacketSize {
  243. if f.l.Enabled(context.Background(), slog.LevelInfo) {
  244. f.l.Info("rejectOutside: packet too big, not sending", "packet", packet, "outPacket", out)
  245. }
  246. return
  247. }
  248. f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, out, nb, encryptBuf, q)
  249. }
  250. // 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
  251. // it does not check if it is within our vpn networks!
  252. func (f *Interface) Handshake(vpnAddr netip.Addr) {
  253. f.handshakeManager.GetOrHandshake(vpnAddr, nil)
  254. }
  255. // getOrHandshakeNoRouting returns nil if the vpnAddr is not routable.
  256. // If the 2nd return var is false then the hostinfo is not ready to be used in a tunnel
  257. func (f *Interface) getOrHandshakeNoRouting(vpnAddr netip.Addr, cacheCallback func(*HandshakeHostInfo)) (*HostInfo, bool) {
  258. if f.myVpnNetworksTable.Contains(vpnAddr) {
  259. return f.handshakeManager.GetOrHandshake(vpnAddr, cacheCallback)
  260. }
  261. return nil, false
  262. }
  263. // getOrHandshakeConsiderRouting will try to find the HostInfo to handle this packet, starting a handshake if necessary.
  264. // If the 2nd return var is false then the hostinfo is not ready to be used in a tunnel.
  265. func (f *Interface) getOrHandshakeConsiderRouting(fwPacket *firewall.Packet, cacheCallback func(*HandshakeHostInfo)) (*HostInfo, bool) {
  266. destinationAddr := fwPacket.RemoteAddr
  267. hostinfo, ready := f.getOrHandshakeNoRouting(destinationAddr, cacheCallback)
  268. // Host is inside the mesh, no routing required
  269. if hostinfo != nil {
  270. return hostinfo, ready
  271. }
  272. gateways := f.inside.RoutesFor(destinationAddr)
  273. switch len(gateways) {
  274. case 0:
  275. return nil, false
  276. case 1:
  277. // Single gateway route
  278. return f.handshakeManager.GetOrHandshake(gateways[0].Addr(), cacheCallback)
  279. default:
  280. // Multi gateway route, perform ECMP categorization
  281. gatewayAddr, balancingOk := routing.BalancePacket(fwPacket, gateways)
  282. if !balancingOk {
  283. // This happens if the gateway buckets were not calculated, this _should_ never happen
  284. f.l.Error("Gateway buckets not calculated, fallback from ECMP to random routing. Please report this bug.")
  285. }
  286. var handshakeInfoForChosenGateway *HandshakeHostInfo
  287. var hhReceiver = func(hh *HandshakeHostInfo) {
  288. handshakeInfoForChosenGateway = hh
  289. }
  290. // Store the handshakeHostInfo for later.
  291. // If this node is not reachable we will attempt other nodes, if none are reachable we will
  292. // cache the packet for this gateway.
  293. if hostinfo, ready = f.handshakeManager.GetOrHandshake(gatewayAddr, hhReceiver); ready {
  294. return hostinfo, true
  295. }
  296. // It appears the selected gateway cannot be reached, find another gateway to fallback on.
  297. // The current implementation breaks ECMP but that seems better than no connectivity.
  298. // If ECMP is also required when a gateway is down then connectivity status
  299. // for each gateway needs to be kept and the weights recalculated when they go up or down.
  300. // This would also need to interact with unsafe_route updates through reloading the config or
  301. // use of the use_system_route_table option
  302. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  303. f.l.Debug("Calculated gateway for ECMP not available, attempting other gateways",
  304. "destination", destinationAddr,
  305. "originalGateway", gatewayAddr,
  306. )
  307. }
  308. for i := range gateways {
  309. // Skip the gateway that failed previously
  310. if gateways[i].Addr() == gatewayAddr {
  311. continue
  312. }
  313. // We do not need the HandshakeHostInfo since we cache the packet in the originally chosen gateway
  314. if hostinfo, ready = f.handshakeManager.GetOrHandshake(gateways[i].Addr(), nil); ready {
  315. return hostinfo, true
  316. }
  317. }
  318. // No gateways reachable, cache the packet in the originally chosen gateway
  319. cacheCallback(handshakeInfoForChosenGateway)
  320. return hostinfo, false
  321. }
  322. }
  323. func (f *Interface) sendMessageNow(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p, nb, out []byte) {
  324. fp := &firewall.ParsedPacket{}
  325. err := newPacket(p, false, fp)
  326. if err != nil {
  327. f.l.Warn("error while parsing outgoing packet for firewall check", "error", err)
  328. return
  329. }
  330. // check if packet is in outbound fw rules
  331. dropReason := f.firewall.Drop(fp.Packet, false, hostinfo, f.pki.GetCAPool(), nil)
  332. if dropReason != nil {
  333. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  334. f.l.Debug("dropping cached packet",
  335. "fwPacket", fp,
  336. "reason", dropReason,
  337. )
  338. }
  339. return
  340. }
  341. f.sendNoMetrics(header.Message, st, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, p, nb, out, 0)
  342. }
  343. // SendMessageToVpnAddr handles real addr:port lookup and sends to the current best known address for vpnAddr.
  344. // This function ignores myVpnNetworksTable, and will always attempt to treat the address as a vpnAddr
  345. func (f *Interface) SendMessageToVpnAddr(t header.MessageType, st header.MessageSubType, vpnAddr netip.Addr, p, nb, out []byte) {
  346. hostInfo, ready := f.handshakeManager.GetOrHandshake(vpnAddr, func(hh *HandshakeHostInfo) {
  347. hh.cachePacket(f.l, t, st, p, f.SendMessageToHostInfo, f.cachedPacketMetrics)
  348. })
  349. if hostInfo == nil {
  350. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  351. f.l.Debug("dropping SendMessageToVpnAddr, vpnAddr not in our vpn networks or in unsafe routes",
  352. "vpnAddr", vpnAddr,
  353. )
  354. }
  355. return
  356. }
  357. if !ready {
  358. return
  359. }
  360. f.SendMessageToHostInfo(t, st, hostInfo, p, nb, out)
  361. }
  362. func (f *Interface) SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hi *HostInfo, p, nb, out []byte) {
  363. f.send(t, st, hi.ConnectionState, hi, p, nb, out)
  364. }
  365. func (f *Interface) send(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, p, nb, out []byte) {
  366. f.messageMetrics.Tx(t, st, 1)
  367. f.sendNoMetrics(t, st, ci, hostinfo, netip.AddrPort{}, p, nb, out, 0)
  368. }
  369. func (f *Interface) sendTo(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte) {
  370. f.messageMetrics.Tx(t, st, 1)
  371. f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out, 0)
  372. }
  373. // dropExhausted records an exhaustion drop and logs once, on the crossing send, for a spent tunnel.
  374. func (f *Interface) dropExhausted(hostinfo *HostInfo, c uint64, msg string) {
  375. f.messageMetrics.TxExhausted(1)
  376. if c == RejectAfterMessages {
  377. hostinfo.logger(f.l).Error(msg)
  378. }
  379. }
  380. func (f *Interface) prepareSendVia(via *HostInfo,
  381. relay *Relay,
  382. ad,
  383. nb,
  384. out []byte,
  385. nocopy bool,
  386. ) ([]byte, error) {
  387. if noiseutil.EncryptLockNeeded {
  388. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  389. via.ConnectionState.writeLock.Lock()
  390. }
  391. c, ok := via.ConnectionState.NextMessageCounter()
  392. if !ok {
  393. if noiseutil.EncryptLockNeeded {
  394. via.ConnectionState.writeLock.Unlock()
  395. }
  396. f.dropExhausted(via, c, "Dropping outbound relay packets, tunnel message counter is exhausted")
  397. return nil, fmt.Errorf("tunnel message counter is exhausted")
  398. }
  399. out = header.Encode(out, header.Version, header.Message, header.MessageRelay, relay.RemoteIndex, c)
  400. f.connectionManager.Out(via)
  401. // Authenticate the header and payload, but do not encrypt for this message type.
  402. // The payload consists of the inner, unencrypted Nebula header, as well as the end-to-end encrypted payload.
  403. if len(out)+len(ad)+via.ConnectionState.eKey.Overhead() > cap(out) {
  404. if noiseutil.EncryptLockNeeded {
  405. via.ConnectionState.writeLock.Unlock()
  406. }
  407. via.logger(f.l).Error("SendVia out buffer not large enough for relay",
  408. "outCap", cap(out),
  409. "payloadLen", len(ad),
  410. "headerLen", len(out),
  411. "cipherOverhead", via.ConnectionState.eKey.Overhead(),
  412. )
  413. return nil, io.ErrShortBuffer
  414. }
  415. // The header bytes are written to the 'out' slice; Grow the slice to hold the header and associated data payload.
  416. offset := len(out)
  417. out = out[:offset+len(ad)]
  418. // In one call path, the associated data _is_ already stored in out. In other call paths, the associated data must
  419. // be copied into 'out'.
  420. if !nocopy {
  421. copy(out[offset:], ad)
  422. }
  423. var err error
  424. out, err = via.ConnectionState.eKey.EncryptDanger(out, out, nil, c, nb)
  425. if noiseutil.EncryptLockNeeded {
  426. via.ConnectionState.writeLock.Unlock()
  427. }
  428. if err != nil {
  429. via.logger(f.l).Info("Failed to EncryptDanger in sendVia", "error", err)
  430. return nil, err
  431. }
  432. f.connectionManager.RelayUsed(relay.LocalIndex)
  433. return out, nil
  434. }
  435. // SendVia sends a payload through a Relay tunnel. No authentication or encryption is done
  436. // to the payload for the ultimate target host, making this a useful method for sending
  437. // handshake messages to peers through relay tunnels.
  438. // via is the HostInfo through which the message is relayed.
  439. // ad is the plaintext data to authenticate, but not encrypt
  440. // nb is a buffer used to store the nonce value, re-used for performance reasons.
  441. // out is a buffer used to store the result of the Encrypt operation
  442. // q indicates which writer to use to send the packet.
  443. func (f *Interface) SendVia(via *HostInfo, relay *Relay, ad, nb, out []byte, nocopy bool, q int) {
  444. toSend, err := f.prepareSendVia(via, relay, ad, nb, out, nocopy)
  445. if err != nil {
  446. // already logged by prepareSendVia
  447. return
  448. }
  449. err = f.writers[q].WriteTo(toSend, via.GetRemote())
  450. if err != nil {
  451. via.logger(f.l).Info("Failed to WriteTo in sendVia", "error", err)
  452. }
  453. }
  454. func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte, q int) {
  455. if ci.eKey == nil {
  456. return
  457. }
  458. useRelay := !remote.IsValid() && !hostinfo.GetRemote().IsValid()
  459. fullOut := out
  460. if useRelay {
  461. if len(out) < header.Len {
  462. // out always has a capacity of mtu, but not always a length greater than the header.Len.
  463. // Grow it to make sure the next operation works.
  464. out = out[:header.Len]
  465. }
  466. // Save a header's worth of data at the front of the 'out' buffer.
  467. out = out[header.Len:]
  468. }
  469. if noiseutil.EncryptLockNeeded {
  470. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  471. ci.writeLock.Lock()
  472. }
  473. c, ok := ci.NextMessageCounter()
  474. if !ok {
  475. if noiseutil.EncryptLockNeeded {
  476. ci.writeLock.Unlock()
  477. }
  478. f.dropExhausted(hostinfo, c, "Dropping outbound packets, tunnel message counter is exhausted")
  479. return
  480. }
  481. //l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
  482. out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
  483. f.connectionManager.Out(hostinfo)
  484. // Query our LH if we haven't since the last time we've been rebound, this will cause the remote to punch against
  485. // all our addrs and enable a faster roaming.
  486. if t != header.CloseTunnel && hostinfo.lastRebindCount != f.rebindCount {
  487. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  488. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  489. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  490. hostinfo.lastRebindCount = f.rebindCount
  491. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  492. f.l.Debug("Lighthouse update triggered for punch due to rebind counter",
  493. "vpnAddrs", hostinfo.vpnAddrs,
  494. )
  495. }
  496. }
  497. var err error
  498. out, err = ci.eKey.EncryptDanger(out, out, p, c, nb)
  499. if noiseutil.EncryptLockNeeded {
  500. ci.writeLock.Unlock()
  501. }
  502. if err != nil {
  503. hostinfo.logger(f.l).Error("Failed to encrypt outgoing packet",
  504. "error", err,
  505. "udpAddr", remote,
  506. "counter", c,
  507. )
  508. return
  509. }
  510. if remote.IsValid() {
  511. err = f.writers[q].WriteTo(out, remote)
  512. if err != nil {
  513. hostinfo.logger(f.l).Error("Failed to write outgoing packet",
  514. "error", err,
  515. "udpAddr", remote,
  516. )
  517. }
  518. } else if hr := hostinfo.GetRemote(); hr.IsValid() {
  519. err = f.writers[q].WriteTo(out, hr)
  520. if err != nil {
  521. hostinfo.logger(f.l).Error("Failed to write outgoing packet",
  522. "error", err,
  523. "udpAddr", hr,
  524. )
  525. }
  526. } else {
  527. // Try to send via a relay
  528. for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
  529. relayHostInfo, relay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relayIP)
  530. if err != nil {
  531. hostinfo.relayState.DeleteRelay(relayIP)
  532. hostinfo.logger(f.l).Info("sendNoMetrics failed to find HostInfo",
  533. "relay", relayIP,
  534. "error", err,
  535. )
  536. continue
  537. }
  538. f.SendVia(relayHostInfo, relay, out, nb, fullOut[:header.Len+len(out)], true, q)
  539. break
  540. }
  541. }
  542. }