inside.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. package nebula
  2. import (
  3. "net/netip"
  4. "sync"
  5. "time"
  6. "github.com/sirupsen/logrus"
  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/routing"
  12. )
  13. // preEncryptionPacket holds packet data before batch encryption
  14. type preEncryptionPacket struct {
  15. hostinfo *HostInfo
  16. ci *ConnectionState
  17. packet []byte
  18. out []byte
  19. }
  20. // Pool for preEncryptionBatch slices to reduce allocations
  21. var preEncryptionBatchPool = sync.Pool{
  22. New: func() any {
  23. // Pre-allocate with reasonable capacity
  24. batch := make([]preEncryptionPacket, 0, 128)
  25. return &batch
  26. },
  27. }
  28. // consumeInsidePackets processes multiple packets in a batch for improved performance
  29. // packets: slice of packet buffers to process
  30. // sizes: slice of packet sizes
  31. // count: number of packets to process
  32. // outs: slice of output buffers (one per packet) with virtio headroom
  33. // q: queue index
  34. // localCache: firewall conntrack cache
  35. // batchPackets: pre-allocated slice for accumulating encrypted packets
  36. // batchAddrs: pre-allocated slice for accumulating destination addresses
  37. func (f *Interface) consumeInsidePackets(packets [][]byte, sizes []int, count int, outs [][]byte, nb []byte, q int, localCache firewall.ConntrackCache, batchPackets *[][]byte, batchAddrs *[]netip.AddrPort) {
  38. // Reusable per-packet state
  39. fwPacket := &firewall.Packet{}
  40. // Reset batch accumulation slices (reuse capacity)
  41. *batchPackets = (*batchPackets)[:0]
  42. *batchAddrs = (*batchAddrs)[:0]
  43. // Collect packets for batched encryption
  44. preEncryptionBatch := make([]preEncryptionPacket, 0, count)
  45. // Process each packet in the batch
  46. for i := 0; i < count; i++ {
  47. packet := packets[i][:sizes[i]]
  48. out := outs[i]
  49. // Inline the consumeInsidePacket logic for better performance
  50. err := newPacket(packet, false, fwPacket)
  51. if err != nil {
  52. if f.l.Level >= logrus.DebugLevel {
  53. f.l.WithField("packet", packet).Debugf("Error while validating outbound packet: %s", err)
  54. }
  55. continue
  56. }
  57. // Ignore local broadcast packets
  58. if f.dropLocalBroadcast {
  59. if f.myBroadcastAddrsTable.Contains(fwPacket.RemoteAddr) {
  60. continue
  61. }
  62. }
  63. if f.myVpnAddrsTable.Contains(fwPacket.RemoteAddr) {
  64. // Immediately forward packets from self to self.
  65. if immediatelyForwardToSelf {
  66. _, err := f.readers[q].Write(packet)
  67. if err != nil {
  68. f.l.WithError(err).Error("Failed to forward to tun")
  69. }
  70. }
  71. continue
  72. }
  73. // Ignore multicast packets
  74. if f.dropMulticast && fwPacket.RemoteAddr.IsMulticast() {
  75. continue
  76. }
  77. hostinfo, ready := f.getOrHandshakeConsiderRouting(fwPacket, func(hh *HandshakeHostInfo) {
  78. hh.cachePacket(f.l, header.Message, 0, packet, f.sendMessageNow, f.cachedPacketMetrics)
  79. })
  80. if hostinfo == nil {
  81. f.rejectInside(packet, out, q)
  82. if f.l.Level >= logrus.DebugLevel {
  83. f.l.WithField("vpnAddr", fwPacket.RemoteAddr).
  84. WithField("fwPacket", fwPacket).
  85. Debugln("dropping outbound packet, vpnAddr not in our vpn networks or in unsafe networks")
  86. }
  87. continue
  88. }
  89. if !ready {
  90. continue
  91. }
  92. dropReason := f.firewall.Drop(*fwPacket, false, hostinfo, f.pki.GetCAPool(), localCache)
  93. if dropReason != nil {
  94. f.rejectInside(packet, out, q)
  95. if f.l.Level >= logrus.DebugLevel {
  96. hostinfo.logger(f.l).
  97. WithField("fwPacket", fwPacket).
  98. WithField("reason", dropReason).
  99. Debugln("dropping outbound packet")
  100. }
  101. continue
  102. }
  103. // Prepare packet for batch encryption
  104. ci := hostinfo.ConnectionState
  105. if ci.eKey == nil {
  106. continue
  107. }
  108. // Check if this needs relay - if so, send immediately and skip batching
  109. useRelay := !hostinfo.remote.IsValid()
  110. if useRelay {
  111. // Handle relay sends individually (less common path)
  112. f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, packet, nb, out, q)
  113. continue
  114. }
  115. // Collect for batched encryption
  116. preEncryptionBatch = append(preEncryptionBatch, preEncryptionPacket{
  117. hostinfo: hostinfo,
  118. ci: ci,
  119. packet: packet,
  120. out: out,
  121. })
  122. }
  123. // BATCH ENCRYPTION: Process all collected packets
  124. if len(preEncryptionBatch) > 0 {
  125. f.encryptBatch(preEncryptionBatch, nb, batchPackets, batchAddrs)
  126. }
  127. // Send all accumulated packets in one batch
  128. if len(*batchPackets) > 0 {
  129. batchSize := len(*batchPackets)
  130. n, err := f.writers[q].WriteMulti(*batchPackets, *batchAddrs)
  131. if err != nil {
  132. f.l.WithError(err).WithField("sent", n).WithField("total", batchSize).Error("Failed to send batch")
  133. }
  134. }
  135. }
  136. // encryptBatch processes multiple packets, grouping by ConnectionState to reduce lock acquisitions
  137. func (f *Interface) encryptBatch(batch []preEncryptionPacket, nb []byte, batchPackets *[][]byte, batchAddrs *[]netip.AddrPort) {
  138. lockStart := time.Now()
  139. lockAcquisitions := int64(0)
  140. if noiseutil.EncryptLockNeeded {
  141. // Group packets by ConnectionState to minimize lock acquisitions
  142. // Process packets in order but batch lock acquisitions per CI
  143. var currentCI *ConnectionState
  144. var lockHeld bool
  145. for i := range batch {
  146. ci := batch[i].ci
  147. hostinfo := batch[i].hostinfo
  148. // Validate packet data to prevent nil pointer dereference
  149. if ci == nil || hostinfo == nil {
  150. continue
  151. }
  152. // Switch locks if we're moving to a different ConnectionState
  153. if ci != currentCI {
  154. if lockHeld {
  155. currentCI.writeLock.Unlock()
  156. }
  157. ci.writeLock.Lock()
  158. lockAcquisitions++
  159. currentCI = ci
  160. lockHeld = true
  161. }
  162. c := ci.messageCounter.Add(1)
  163. out := header.Encode(batch[i].out, header.Version, header.Message, 0, hostinfo.remoteIndexId, c)
  164. f.connectionManager.Out(hostinfo)
  165. // Query lighthouse if needed
  166. if hostinfo.lastRebindCount != f.rebindCount {
  167. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  168. hostinfo.lastRebindCount = f.rebindCount
  169. if f.l.Level >= logrus.DebugLevel {
  170. f.l.WithField("vpnAddrs", hostinfo.vpnAddrs).Debug("Lighthouse update triggered for punch due to rebind counter")
  171. }
  172. }
  173. var err error
  174. out, err = ci.eKey.EncryptDanger(out, out, batch[i].packet, c, nb)
  175. if err != nil {
  176. hostinfo.logger(f.l).WithError(err).
  177. WithField("counter", c).
  178. Error("Failed to encrypt outgoing packet")
  179. continue
  180. }
  181. // Add to output batches
  182. *batchPackets = append(*batchPackets, out)
  183. *batchAddrs = append(*batchAddrs, hostinfo.remote)
  184. }
  185. // Release final lock
  186. if lockHeld {
  187. currentCI.writeLock.Unlock()
  188. }
  189. } else {
  190. // No locks needed - process directly
  191. for i := range batch {
  192. ci := batch[i].ci
  193. hostinfo := batch[i].hostinfo
  194. // Validate packet data to prevent nil pointer dereference
  195. if ci == nil || hostinfo == nil {
  196. continue
  197. }
  198. c := ci.messageCounter.Add(1)
  199. out := header.Encode(batch[i].out, header.Version, header.Message, 0, hostinfo.remoteIndexId, c)
  200. f.connectionManager.Out(hostinfo)
  201. // Query lighthouse if needed
  202. if hostinfo.lastRebindCount != f.rebindCount {
  203. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  204. hostinfo.lastRebindCount = f.rebindCount
  205. if f.l.Level >= logrus.DebugLevel {
  206. f.l.WithField("vpnAddrs", hostinfo.vpnAddrs).Debug("Lighthouse update triggered for punch due to rebind counter")
  207. }
  208. }
  209. var err error
  210. out, err = ci.eKey.EncryptDanger(out, out, batch[i].packet, c, nb)
  211. if err != nil {
  212. hostinfo.logger(f.l).WithError(err).
  213. WithField("counter", c).
  214. Error("Failed to encrypt outgoing packet")
  215. continue
  216. }
  217. // Add to output batches
  218. *batchPackets = append(*batchPackets, out)
  219. *batchAddrs = append(*batchAddrs, hostinfo.remote)
  220. }
  221. }
  222. // Record metrics
  223. encryptionTime := time.Since(lockStart)
  224. if noiseutil.EncryptLockNeeded {
  225. f.batchMetrics.lockAcquisitions.Inc(lockAcquisitions)
  226. }
  227. f.batchMetrics.encryptionTime.Update(encryptionTime.Nanoseconds())
  228. f.batchMetrics.batchSize.Update(int64(len(batch)))
  229. }
  230. func (f *Interface) consumeInsidePacket(packet []byte, fwPacket *firewall.Packet, nb, out []byte, q int, localCache firewall.ConntrackCache) {
  231. err := newPacket(packet, false, fwPacket)
  232. if err != nil {
  233. if f.l.Level >= logrus.DebugLevel {
  234. f.l.WithField("packet", packet).Debugf("Error while validating outbound packet: %s", err)
  235. }
  236. return
  237. }
  238. // Ignore local broadcast packets
  239. if f.dropLocalBroadcast {
  240. if f.myBroadcastAddrsTable.Contains(fwPacket.RemoteAddr) {
  241. return
  242. }
  243. }
  244. if f.myVpnAddrsTable.Contains(fwPacket.RemoteAddr) {
  245. // Immediately forward packets from self to self.
  246. // This should only happen on Darwin-based and FreeBSD hosts, which
  247. // routes packets from the Nebula addr to the Nebula addr through the Nebula
  248. // TUN device.
  249. if immediatelyForwardToSelf {
  250. _, err := f.readers[q].Write(packet)
  251. if err != nil {
  252. f.l.WithError(err).Error("Failed to forward to tun")
  253. }
  254. }
  255. // Otherwise, drop. On linux, we should never see these packets - Linux
  256. // routes packets from the nebula addr to the nebula addr through the loopback device.
  257. return
  258. }
  259. // Ignore multicast packets
  260. if f.dropMulticast && fwPacket.RemoteAddr.IsMulticast() {
  261. return
  262. }
  263. hostinfo, ready := f.getOrHandshakeConsiderRouting(fwPacket, func(hh *HandshakeHostInfo) {
  264. hh.cachePacket(f.l, header.Message, 0, packet, f.sendMessageNow, f.cachedPacketMetrics)
  265. })
  266. if hostinfo == nil {
  267. f.rejectInside(packet, out, q)
  268. if f.l.Level >= logrus.DebugLevel {
  269. f.l.WithField("vpnAddr", fwPacket.RemoteAddr).
  270. WithField("fwPacket", fwPacket).
  271. Debugln("dropping outbound packet, vpnAddr not in our vpn networks or in unsafe networks")
  272. }
  273. return
  274. }
  275. if !ready {
  276. return
  277. }
  278. dropReason := f.firewall.Drop(*fwPacket, false, hostinfo, f.pki.GetCAPool(), localCache)
  279. if dropReason == nil {
  280. f.sendNoMetrics(header.Message, 0, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, packet, nb, out, q)
  281. } else {
  282. f.rejectInside(packet, out, q)
  283. if f.l.Level >= logrus.DebugLevel {
  284. hostinfo.logger(f.l).
  285. WithField("fwPacket", fwPacket).
  286. WithField("reason", dropReason).
  287. Debugln("dropping outbound packet")
  288. }
  289. }
  290. }
  291. func (f *Interface) rejectInside(packet []byte, out []byte, q int) {
  292. if !f.firewall.InSendReject {
  293. return
  294. }
  295. out = iputil.CreateRejectPacket(packet, out)
  296. if len(out) == 0 {
  297. return
  298. }
  299. _, err := f.readers[q].Write(out)
  300. if err != nil {
  301. f.l.WithError(err).Error("Failed to write to tun")
  302. }
  303. }
  304. func (f *Interface) rejectOutside(packet []byte, ci *ConnectionState, hostinfo *HostInfo, nb, out []byte, q int) {
  305. if !f.firewall.OutSendReject {
  306. return
  307. }
  308. out = iputil.CreateRejectPacket(packet, out)
  309. if len(out) == 0 {
  310. return
  311. }
  312. if len(out) > iputil.MaxRejectPacketSize {
  313. if f.l.GetLevel() >= logrus.InfoLevel {
  314. f.l.
  315. WithField("packet", packet).
  316. WithField("outPacket", out).
  317. Info("rejectOutside: packet too big, not sending")
  318. }
  319. return
  320. }
  321. f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, out, nb, packet, q)
  322. }
  323. // 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
  324. // it does not check if it is within our vpn networks!
  325. func (f *Interface) Handshake(vpnAddr netip.Addr) {
  326. f.handshakeManager.GetOrHandshake(vpnAddr, nil)
  327. }
  328. // getOrHandshakeNoRouting returns nil if the vpnAddr is not routable.
  329. // If the 2nd return var is false then the hostinfo is not ready to be used in a tunnel
  330. func (f *Interface) getOrHandshakeNoRouting(vpnAddr netip.Addr, cacheCallback func(*HandshakeHostInfo)) (*HostInfo, bool) {
  331. if f.myVpnNetworksTable.Contains(vpnAddr) {
  332. return f.handshakeManager.GetOrHandshake(vpnAddr, cacheCallback)
  333. }
  334. return nil, false
  335. }
  336. // getOrHandshakeConsiderRouting will try to find the HostInfo to handle this packet, starting a handshake if necessary.
  337. // If the 2nd return var is false then the hostinfo is not ready to be used in a tunnel.
  338. func (f *Interface) getOrHandshakeConsiderRouting(fwPacket *firewall.Packet, cacheCallback func(*HandshakeHostInfo)) (*HostInfo, bool) {
  339. destinationAddr := fwPacket.RemoteAddr
  340. hostinfo, ready := f.getOrHandshakeNoRouting(destinationAddr, cacheCallback)
  341. // Host is inside the mesh, no routing required
  342. if hostinfo != nil {
  343. return hostinfo, ready
  344. }
  345. gateways := f.inside.RoutesFor(destinationAddr)
  346. switch len(gateways) {
  347. case 0:
  348. return nil, false
  349. case 1:
  350. // Single gateway route
  351. return f.handshakeManager.GetOrHandshake(gateways[0].Addr(), cacheCallback)
  352. default:
  353. // Multi gateway route, perform ECMP categorization
  354. gatewayAddr, balancingOk := routing.BalancePacket(fwPacket, gateways)
  355. if !balancingOk {
  356. // This happens if the gateway buckets were not calculated, this _should_ never happen
  357. f.l.Error("Gateway buckets not calculated, fallback from ECMP to random routing. Please report this bug.")
  358. }
  359. var handshakeInfoForChosenGateway *HandshakeHostInfo
  360. var hhReceiver = func(hh *HandshakeHostInfo) {
  361. handshakeInfoForChosenGateway = hh
  362. }
  363. // Store the handshakeHostInfo for later.
  364. // If this node is not reachable we will attempt other nodes, if none are reachable we will
  365. // cache the packet for this gateway.
  366. if hostinfo, ready = f.handshakeManager.GetOrHandshake(gatewayAddr, hhReceiver); ready {
  367. return hostinfo, true
  368. }
  369. // It appears the selected gateway cannot be reached, find another gateway to fallback on.
  370. // The current implementation breaks ECMP but that seems better than no connectivity.
  371. // If ECMP is also required when a gateway is down then connectivity status
  372. // for each gateway needs to be kept and the weights recalculated when they go up or down.
  373. // This would also need to interact with unsafe_route updates through reloading the config or
  374. // use of the use_system_route_table option
  375. if f.l.Level >= logrus.DebugLevel {
  376. f.l.WithField("destination", destinationAddr).
  377. WithField("originalGateway", gatewayAddr).
  378. Debugln("Calculated gateway for ECMP not available, attempting other gateways")
  379. }
  380. for i := range gateways {
  381. // Skip the gateway that failed previously
  382. if gateways[i].Addr() == gatewayAddr {
  383. continue
  384. }
  385. // We do not need the HandshakeHostInfo since we cache the packet in the originally chosen gateway
  386. if hostinfo, ready = f.handshakeManager.GetOrHandshake(gateways[i].Addr(), nil); ready {
  387. return hostinfo, true
  388. }
  389. }
  390. // No gateways reachable, cache the packet in the originally chosen gateway
  391. cacheCallback(handshakeInfoForChosenGateway)
  392. return hostinfo, false
  393. }
  394. }
  395. func (f *Interface) sendMessageNow(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p, nb, out []byte) {
  396. fp := &firewall.Packet{}
  397. err := newPacket(p, false, fp)
  398. if err != nil {
  399. f.l.Warnf("error while parsing outgoing packet for firewall check; %v", err)
  400. return
  401. }
  402. // check if packet is in outbound fw rules
  403. dropReason := f.firewall.Drop(*fp, false, hostinfo, f.pki.GetCAPool(), nil)
  404. if dropReason != nil {
  405. if f.l.Level >= logrus.DebugLevel {
  406. f.l.WithField("fwPacket", fp).
  407. WithField("reason", dropReason).
  408. Debugln("dropping cached packet")
  409. }
  410. return
  411. }
  412. f.sendNoMetrics(header.Message, st, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, p, nb, out, 0)
  413. }
  414. // SendMessageToVpnAddr handles real addr:port lookup and sends to the current best known address for vpnAddr.
  415. // This function ignores myVpnNetworksTable, and will always attempt to treat the address as a vpnAddr
  416. func (f *Interface) SendMessageToVpnAddr(t header.MessageType, st header.MessageSubType, vpnAddr netip.Addr, p, nb, out []byte) {
  417. hostInfo, ready := f.handshakeManager.GetOrHandshake(vpnAddr, func(hh *HandshakeHostInfo) {
  418. hh.cachePacket(f.l, t, st, p, f.SendMessageToHostInfo, f.cachedPacketMetrics)
  419. })
  420. if hostInfo == nil {
  421. if f.l.Level >= logrus.DebugLevel {
  422. f.l.WithField("vpnAddr", vpnAddr).
  423. Debugln("dropping SendMessageToVpnAddr, vpnAddr not in our vpn networks or in unsafe routes")
  424. }
  425. return
  426. }
  427. if !ready {
  428. return
  429. }
  430. f.SendMessageToHostInfo(t, st, hostInfo, p, nb, out)
  431. }
  432. func (f *Interface) SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hi *HostInfo, p, nb, out []byte) {
  433. f.send(t, st, hi.ConnectionState, hi, p, nb, out)
  434. }
  435. func (f *Interface) send(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, p, nb, out []byte) {
  436. f.messageMetrics.Tx(t, st, 1)
  437. f.sendNoMetrics(t, st, ci, hostinfo, netip.AddrPort{}, p, nb, out, 0)
  438. }
  439. func (f *Interface) sendTo(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte) {
  440. f.messageMetrics.Tx(t, st, 1)
  441. f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out, 0)
  442. }
  443. // SendVia sends a payload through a Relay tunnel. No authentication or encryption is done
  444. // to the payload for the ultimate target host, making this a useful method for sending
  445. // handshake messages to peers through relay tunnels.
  446. // via is the HostInfo through which the message is relayed.
  447. // ad is the plaintext data to authenticate, but not encrypt
  448. // nb is a buffer used to store the nonce value, re-used for performance reasons.
  449. // out is a buffer used to store the result of the Encrypt operation
  450. // q indicates which writer to use to send the packet.
  451. func (f *Interface) SendVia(via *HostInfo,
  452. relay *Relay,
  453. ad,
  454. nb,
  455. out []byte,
  456. nocopy bool,
  457. ) {
  458. if noiseutil.EncryptLockNeeded {
  459. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  460. via.ConnectionState.writeLock.Lock()
  461. }
  462. c := via.ConnectionState.messageCounter.Add(1)
  463. out = header.Encode(out, header.Version, header.Message, header.MessageRelay, relay.RemoteIndex, c)
  464. f.connectionManager.Out(via)
  465. // Authenticate the header and payload, but do not encrypt for this message type.
  466. // The payload consists of the inner, unencrypted Nebula header, as well as the end-to-end encrypted payload.
  467. if len(out)+len(ad)+via.ConnectionState.eKey.Overhead() > cap(out) {
  468. if noiseutil.EncryptLockNeeded {
  469. via.ConnectionState.writeLock.Unlock()
  470. }
  471. via.logger(f.l).
  472. WithField("outCap", cap(out)).
  473. WithField("payloadLen", len(ad)).
  474. WithField("headerLen", len(out)).
  475. WithField("cipherOverhead", via.ConnectionState.eKey.Overhead()).
  476. Error("SendVia out buffer not large enough for relay")
  477. return
  478. }
  479. // The header bytes are written to the 'out' slice; Grow the slice to hold the header and associated data payload.
  480. offset := len(out)
  481. out = out[:offset+len(ad)]
  482. // In one call path, the associated data _is_ already stored in out. In other call paths, the associated data must
  483. // be copied into 'out'.
  484. if !nocopy {
  485. copy(out[offset:], ad)
  486. }
  487. var err error
  488. out, err = via.ConnectionState.eKey.EncryptDanger(out, out, nil, c, nb)
  489. if noiseutil.EncryptLockNeeded {
  490. via.ConnectionState.writeLock.Unlock()
  491. }
  492. if err != nil {
  493. via.logger(f.l).WithError(err).Info("Failed to EncryptDanger in sendVia")
  494. return
  495. }
  496. err = f.writers[0].WriteTo(out, via.remote)
  497. if err != nil {
  498. via.logger(f.l).WithError(err).Info("Failed to WriteTo in sendVia")
  499. }
  500. f.connectionManager.RelayUsed(relay.LocalIndex)
  501. }
  502. func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte, q int) {
  503. if ci.eKey == nil {
  504. return
  505. }
  506. useRelay := !remote.IsValid() && !hostinfo.remote.IsValid()
  507. fullOut := out
  508. if useRelay {
  509. if len(out) < header.Len {
  510. // out always has a capacity of mtu, but not always a length greater than the header.Len.
  511. // Grow it to make sure the next operation works.
  512. out = out[:header.Len]
  513. }
  514. // Save a header's worth of data at the front of the 'out' buffer.
  515. out = out[header.Len:]
  516. }
  517. if noiseutil.EncryptLockNeeded {
  518. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  519. ci.writeLock.Lock()
  520. }
  521. c := ci.messageCounter.Add(1)
  522. //l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
  523. out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
  524. f.connectionManager.Out(hostinfo)
  525. // Query our LH if we haven't since the last time we've been rebound, this will cause the remote to punch against
  526. // all our addrs and enable a faster roaming.
  527. if t != header.CloseTunnel && hostinfo.lastRebindCount != f.rebindCount {
  528. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  529. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  530. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  531. hostinfo.lastRebindCount = f.rebindCount
  532. if f.l.Level >= logrus.DebugLevel {
  533. f.l.WithField("vpnAddrs", hostinfo.vpnAddrs).Debug("Lighthouse update triggered for punch due to rebind counter")
  534. }
  535. }
  536. var err error
  537. out, err = ci.eKey.EncryptDanger(out, out, p, c, nb)
  538. if noiseutil.EncryptLockNeeded {
  539. ci.writeLock.Unlock()
  540. }
  541. if err != nil {
  542. hostinfo.logger(f.l).WithError(err).
  543. WithField("udpAddr", remote).WithField("counter", c).
  544. WithField("attemptedCounter", c).
  545. Error("Failed to encrypt outgoing packet")
  546. return
  547. }
  548. if remote.IsValid() {
  549. err = f.writers[q].WriteTo(out, remote)
  550. if err != nil {
  551. hostinfo.logger(f.l).WithError(err).
  552. WithField("udpAddr", remote).Error("Failed to write outgoing packet")
  553. }
  554. } else if hostinfo.remote.IsValid() {
  555. err = f.writers[q].WriteTo(out, hostinfo.remote)
  556. if err != nil {
  557. hostinfo.logger(f.l).WithError(err).
  558. WithField("udpAddr", remote).Error("Failed to write outgoing packet")
  559. }
  560. } else {
  561. // Try to send via a relay
  562. for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
  563. relayHostInfo, relay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relayIP)
  564. if err != nil {
  565. hostinfo.relayState.DeleteRelay(relayIP)
  566. hostinfo.logger(f.l).WithField("relay", relayIP).WithError(err).Info("sendNoMetrics failed to find HostInfo")
  567. continue
  568. }
  569. f.SendVia(relayHostInfo, relay, out, nb, fullOut[:header.Len+len(out)], true)
  570. break
  571. }
  572. }
  573. }