1
0

inside.go 21 KB

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