inside.go 21 KB

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