outside.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. package nebula
  2. import (
  3. "context"
  4. "encoding/binary"
  5. "errors"
  6. "log/slog"
  7. "net/netip"
  8. "time"
  9. "github.com/google/gopacket/layers"
  10. "golang.org/x/net/ipv6"
  11. "github.com/slackhq/nebula/firewall"
  12. "github.com/slackhq/nebula/header"
  13. "golang.org/x/net/ipv4"
  14. )
  15. const (
  16. minFwPacketLen = 4
  17. )
  18. func (f *Interface) readOutsidePackets(via ViaSender, buf *WireBuffer, packet []byte, lhf *LightHouseHandler, q int, localCache firewall.ConntrackCache) {
  19. h := buf.H
  20. err := h.Parse(packet)
  21. if err != nil {
  22. // Hole punch packets are 0 or 1 byte big, so lets ignore printing those errors
  23. if len(packet) > 1 {
  24. f.l.Info("Error while parsing inbound packet",
  25. "from", via,
  26. "error", err,
  27. "packet", packet,
  28. )
  29. }
  30. return
  31. }
  32. //l.Error("in packet ", header, packet[HeaderLen:])
  33. if !via.IsRelayed {
  34. if f.myVpnNetworksTable.Contains(via.UdpAddr.Addr()) {
  35. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  36. f.l.Debug("Refusing to process double encrypted packet", "from", via)
  37. }
  38. return
  39. }
  40. }
  41. var hostinfo *HostInfo
  42. // verify if we've seen this index before, otherwise respond to the handshake initiation
  43. if h.Type == header.Message && h.Subtype == header.MessageRelay {
  44. hostinfo = f.hostMap.QueryRelayIndex(h.RemoteIndex)
  45. } else {
  46. hostinfo = f.hostMap.QueryIndex(h.RemoteIndex)
  47. }
  48. var ci *ConnectionState
  49. if hostinfo != nil {
  50. ci = hostinfo.ConnectionState
  51. }
  52. switch h.Type {
  53. case header.Message:
  54. if !f.handleEncrypted(ci, via, h) {
  55. return
  56. }
  57. switch h.Subtype {
  58. case header.MessageNone:
  59. if !f.decryptToTun(hostinfo, h.MessageCounter, buf, packet, q, localCache) {
  60. return
  61. }
  62. case header.MessageRelay:
  63. // The entire body is sent as AD, not encrypted.
  64. // The packet consists of a 16-byte parsed Nebula header, Associated Data-protected payload, and a trailing 16-byte AEAD signature value.
  65. // The packet is guaranteed to be at least 16 bytes at this point, b/c it got past the h.Parse() call above. If it's
  66. // otherwise malformed (meaning, there is no trailing 16 byte AEAD value), then this will result in at worst a 0-length slice
  67. // which will gracefully fail in the DecryptDanger call.
  68. signedPayload := packet[:len(packet)-hostinfo.ConnectionState.dKey.Overhead()]
  69. signatureValue := packet[len(packet)-hostinfo.ConnectionState.dKey.Overhead():]
  70. // AAD-only validation: passing dst=nil since there's no plaintext
  71. // to recover (ciphertext is just the trailing AEAD tag).
  72. if _, err = hostinfo.ConnectionState.dKey.DecryptDanger(nil, signedPayload, signatureValue, h.MessageCounter, buf.NB); err != nil {
  73. return
  74. }
  75. // Successfully validated the thing. Get rid of the Relay header.
  76. signedPayload = signedPayload[header.Len:]
  77. // Pull the Roaming parts up here, and return in all call paths.
  78. f.handleHostRoaming(hostinfo, via)
  79. // Track usage of both the HostInfo and the Relay for the received & authenticated packet
  80. f.connectionManager.In(hostinfo)
  81. f.connectionManager.RelayUsed(h.RemoteIndex)
  82. relay, ok := hostinfo.relayState.QueryRelayForByIdx(h.RemoteIndex)
  83. if !ok {
  84. // The only way this happens is if hostmap has an index to the correct HostInfo, but the HostInfo is missing
  85. // its internal mapping. This should never happen.
  86. hostinfo.logger(f.l).Error("HostInfo missing remote relay index",
  87. "vpnAddrs", hostinfo.vpnAddrs,
  88. "remoteIndex", h.RemoteIndex,
  89. )
  90. return
  91. }
  92. switch relay.Type {
  93. case TerminalType:
  94. // If I am the target of this relay, process the unwrapped packet
  95. // From this recursive point, all these variables are 'burned'. We shouldn't rely on them again.
  96. via = ViaSender{
  97. UdpAddr: via.UdpAddr,
  98. relayHI: hostinfo,
  99. remoteIdx: relay.RemoteIndex,
  100. relay: relay,
  101. IsRelayed: true,
  102. }
  103. buf.Reset()
  104. f.readOutsidePackets(via, buf, signedPayload, lhf, q, localCache)
  105. return
  106. case ForwardingType:
  107. // Find the target HostInfo relay object
  108. targetHI, targetRelay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relay.PeerAddr)
  109. if err != nil {
  110. hostinfo.logger(f.l).Info("Failed to find target host info by ip",
  111. "relayTo", relay.PeerAddr,
  112. "error", err,
  113. "hostinfo.vpnAddrs", hostinfo.vpnAddrs,
  114. )
  115. return
  116. }
  117. // If that relay is Established, forward the payload through it
  118. if targetRelay.State == Established {
  119. switch targetRelay.Type {
  120. case ForwardingType:
  121. // Forward this packet through the relay tunnel
  122. // Find the target HostInfo
  123. f.SendVia(targetHI, targetRelay, signedPayload, buf)
  124. return
  125. case TerminalType:
  126. hostinfo.logger(f.l).Error("Unexpected Relay Type of Terminal")
  127. }
  128. } else {
  129. hostinfo.logger(f.l).Info("Unexpected target relay state",
  130. "relayTo", relay.PeerAddr,
  131. "relayFrom", hostinfo.vpnAddrs[0],
  132. "targetRelayState", targetRelay.State,
  133. )
  134. return
  135. }
  136. }
  137. }
  138. case header.LightHouse:
  139. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  140. if !f.handleEncrypted(ci, via, h) {
  141. return
  142. }
  143. d, err := f.decrypt(hostinfo, h.MessageCounter, buf, packet, h)
  144. if err != nil {
  145. hostinfo.logger(f.l).Error("Failed to decrypt lighthouse packet",
  146. "error", err,
  147. "from", via,
  148. "packet", packet,
  149. )
  150. return
  151. }
  152. //TODO: assert via is not relayed
  153. lhf.HandleRequest(via.UdpAddr, hostinfo.vpnAddrs, d, f)
  154. // Fallthrough to the bottom to record incoming traffic
  155. case header.Test:
  156. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  157. if !f.handleEncrypted(ci, via, h) {
  158. return
  159. }
  160. d, err := f.decrypt(hostinfo, h.MessageCounter, buf, packet, h)
  161. if err != nil {
  162. hostinfo.logger(f.l).Error("Failed to decrypt test packet",
  163. "error", err,
  164. "from", via,
  165. "packet", packet,
  166. )
  167. return
  168. }
  169. if h.Subtype == header.TestRequest {
  170. // This testRequest might be from TryPromoteBest, so we should roam
  171. // to the new IP address before responding.
  172. f.handleHostRoaming(hostinfo, via)
  173. f.send(header.Test, header.TestReply, ci, hostinfo, d, buf)
  174. }
  175. // Fallthrough to the bottom to record incoming traffic
  176. // Non encrypted messages below here, they should not fall through to avoid tracking incoming traffic since they
  177. // are unauthenticated
  178. case header.Handshake:
  179. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  180. f.handshakeManager.HandleIncoming(via, packet, h)
  181. return
  182. case header.RecvError:
  183. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  184. f.handleRecvError(via.UdpAddr, h)
  185. return
  186. case header.CloseTunnel:
  187. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  188. if !f.handleEncrypted(ci, via, h) {
  189. return
  190. }
  191. _, err = f.decrypt(hostinfo, h.MessageCounter, buf, packet, h)
  192. if err != nil {
  193. hostinfo.logger(f.l).Error("Failed to decrypt CloseTunnel packet",
  194. "error", err,
  195. "from", via,
  196. "packet", packet,
  197. )
  198. return
  199. }
  200. hostinfo.logger(f.l).Info("Close tunnel received, tearing down.", "from", via)
  201. f.closeTunnel(hostinfo)
  202. return
  203. case header.Control:
  204. if !f.handleEncrypted(ci, via, h) {
  205. return
  206. }
  207. d, err := f.decrypt(hostinfo, h.MessageCounter, buf, packet, h)
  208. if err != nil {
  209. hostinfo.logger(f.l).Error("Failed to decrypt Control packet",
  210. "error", err,
  211. "from", via,
  212. "packet", packet,
  213. )
  214. return
  215. }
  216. f.relayManager.HandleControlMsg(hostinfo, d, f)
  217. default:
  218. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  219. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  220. hostinfo.logger(f.l).Debug("Unexpected packet received", "from", via)
  221. }
  222. return
  223. }
  224. f.handleHostRoaming(hostinfo, via)
  225. f.connectionManager.In(hostinfo)
  226. }
  227. // closeTunnel closes a tunnel locally, it does not send a closeTunnel packet to the remote
  228. func (f *Interface) closeTunnel(hostInfo *HostInfo) {
  229. final := f.hostMap.DeleteHostInfo(hostInfo)
  230. if final {
  231. // We no longer have any tunnels with this vpn addr, clear learned lighthouse state to lower memory usage
  232. f.lightHouse.DeleteVpnAddrs(hostInfo.vpnAddrs)
  233. }
  234. }
  235. // sendCloseTunnel is a helper function to send a proper close tunnel packet to a remote
  236. func (f *Interface) sendCloseTunnel(h *HostInfo) {
  237. buf := f.bufAlloc.Acquire()
  238. defer f.bufAlloc.Release(buf)
  239. f.send(header.CloseTunnel, 0, h.ConnectionState, h, []byte{}, buf)
  240. }
  241. func (f *Interface) handleHostRoaming(hostinfo *HostInfo, via ViaSender) {
  242. if !via.IsRelayed && hostinfo.remote != via.UdpAddr {
  243. if !f.lightHouse.GetRemoteAllowList().AllowAll(hostinfo.vpnAddrs, via.UdpAddr.Addr()) {
  244. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  245. hostinfo.logger(f.l).Debug("lighthouse.remote_allow_list denied roaming", "newAddr", via.UdpAddr)
  246. }
  247. return
  248. }
  249. if !hostinfo.lastRoam.IsZero() && via.UdpAddr == hostinfo.lastRoamRemote && time.Since(hostinfo.lastRoam) < RoamingSuppressSeconds*time.Second {
  250. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  251. hostinfo.logger(f.l).Debug("Suppressing roam back to previous remote",
  252. "suppressSeconds", RoamingSuppressSeconds,
  253. "udpAddr", hostinfo.remote,
  254. "newAddr", via.UdpAddr,
  255. )
  256. }
  257. return
  258. }
  259. hostinfo.logger(f.l).Info("Host roamed to new udp ip/port.",
  260. "udpAddr", hostinfo.remote,
  261. "newAddr", via.UdpAddr,
  262. )
  263. hostinfo.lastRoam = time.Now()
  264. hostinfo.lastRoamRemote = hostinfo.remote
  265. hostinfo.SetRemote(via.UdpAddr)
  266. }
  267. }
  268. // handleEncrypted returns true if a packet should be processed, false otherwise
  269. func (f *Interface) handleEncrypted(ci *ConnectionState, via ViaSender, h *header.H) bool {
  270. // If connectionstate does not exist, send a recv error, if possible, to encourage a fast reconnect
  271. if ci == nil {
  272. if !via.IsRelayed {
  273. f.maybeSendRecvError(via.UdpAddr, h.RemoteIndex)
  274. }
  275. return false
  276. }
  277. // If the window check fails, refuse to process the packet, but don't send a recv error
  278. if !ci.window.Check(f.l, h.MessageCounter) {
  279. return false
  280. }
  281. return true
  282. }
  283. var (
  284. ErrPacketTooShort = errors.New("packet is too short")
  285. ErrUnknownIPVersion = errors.New("packet is an unknown ip version")
  286. ErrIPv4InvalidHeaderLength = errors.New("invalid ipv4 header length")
  287. ErrIPv4PacketTooShort = errors.New("ipv4 packet is too short")
  288. ErrIPv6PacketTooShort = errors.New("ipv6 packet is too short")
  289. ErrIPv6CouldNotFindPayload = errors.New("could not find payload in ipv6 packet")
  290. )
  291. // newPacket validates and parses the interesting bits for the firewall out of the ip and sub protocol headers
  292. func newPacket(data []byte, incoming bool, fp *firewall.Packet) error {
  293. if len(data) < 1 {
  294. return ErrPacketTooShort
  295. }
  296. version := int((data[0] >> 4) & 0x0f)
  297. switch version {
  298. case ipv4.Version:
  299. return parseV4(data, incoming, fp)
  300. case ipv6.Version:
  301. return parseV6(data, incoming, fp)
  302. }
  303. return ErrUnknownIPVersion
  304. }
  305. func parseV6(data []byte, incoming bool, fp *firewall.Packet) error {
  306. dataLen := len(data)
  307. if dataLen < ipv6.HeaderLen {
  308. return ErrIPv6PacketTooShort
  309. }
  310. if incoming {
  311. fp.RemoteAddr, _ = netip.AddrFromSlice(data[8:24])
  312. fp.LocalAddr, _ = netip.AddrFromSlice(data[24:40])
  313. } else {
  314. fp.LocalAddr, _ = netip.AddrFromSlice(data[8:24])
  315. fp.RemoteAddr, _ = netip.AddrFromSlice(data[24:40])
  316. }
  317. protoAt := 6 // NextHeader is at 6 bytes into the ipv6 header
  318. offset := ipv6.HeaderLen // Start at the end of the ipv6 header
  319. next := 0
  320. for {
  321. if protoAt >= dataLen {
  322. break
  323. }
  324. proto := layers.IPProtocol(data[protoAt])
  325. switch proto {
  326. case layers.IPProtocolESP, layers.IPProtocolNoNextHeader:
  327. fp.Protocol = uint8(proto)
  328. fp.RemotePort = 0
  329. fp.LocalPort = 0
  330. fp.Fragment = false
  331. return nil
  332. case layers.IPProtocolICMPv6:
  333. if dataLen < offset+6 {
  334. return ErrIPv6PacketTooShort
  335. }
  336. fp.Protocol = uint8(proto)
  337. fp.LocalPort = 0 //incoming vs outgoing doesn't matter for icmpv6
  338. icmptype := data[offset+1]
  339. switch icmptype {
  340. case layers.ICMPv6TypeEchoRequest, layers.ICMPv6TypeEchoReply:
  341. fp.RemotePort = binary.BigEndian.Uint16(data[offset+4 : offset+6]) //identifier
  342. default:
  343. fp.RemotePort = 0
  344. }
  345. fp.Fragment = false
  346. return nil
  347. case layers.IPProtocolTCP, layers.IPProtocolUDP:
  348. if dataLen < offset+4 {
  349. return ErrIPv6PacketTooShort
  350. }
  351. fp.Protocol = uint8(proto)
  352. if incoming {
  353. fp.RemotePort = binary.BigEndian.Uint16(data[offset : offset+2])
  354. fp.LocalPort = binary.BigEndian.Uint16(data[offset+2 : offset+4])
  355. } else {
  356. fp.LocalPort = binary.BigEndian.Uint16(data[offset : offset+2])
  357. fp.RemotePort = binary.BigEndian.Uint16(data[offset+2 : offset+4])
  358. }
  359. fp.Fragment = false
  360. return nil
  361. case layers.IPProtocolIPv6Fragment:
  362. // Fragment header is 8 bytes, need at least offset+4 to read the offset field
  363. if dataLen < offset+8 {
  364. return ErrIPv6PacketTooShort
  365. }
  366. // Check if this is the first fragment
  367. fragmentOffset := binary.BigEndian.Uint16(data[offset+2:offset+4]) &^ uint16(0x7) // Remove the reserved and M flag bits
  368. if fragmentOffset != 0 {
  369. // Non-first fragment, use what we have now and stop processing
  370. fp.Protocol = data[offset]
  371. fp.Fragment = true
  372. fp.RemotePort = 0
  373. fp.LocalPort = 0
  374. return nil
  375. }
  376. // The next loop should be the transport layer since we are the first fragment
  377. next = 8 // Fragment headers are always 8 bytes
  378. case layers.IPProtocolAH:
  379. // Auth headers, used by IPSec, have a different meaning for header length
  380. if dataLen <= offset+1 {
  381. break
  382. }
  383. next = int(data[offset+1]+2) << 2
  384. default:
  385. // Normal ipv6 header length processing
  386. if dataLen <= offset+1 {
  387. break
  388. }
  389. next = int(data[offset+1]+1) << 3
  390. }
  391. if next <= 0 {
  392. // Safety check, each ipv6 header has to be at least 8 bytes
  393. next = 8
  394. }
  395. protoAt = offset
  396. offset = offset + next
  397. }
  398. return ErrIPv6CouldNotFindPayload
  399. }
  400. func parseV4(data []byte, incoming bool, fp *firewall.Packet) error {
  401. // Do we at least have an ipv4 header worth of data?
  402. if len(data) < ipv4.HeaderLen {
  403. return ErrIPv4PacketTooShort
  404. }
  405. // Adjust our start position based on the advertised ip header length
  406. ihl := int(data[0]&0x0f) << 2
  407. // Well-formed ip header length?
  408. if ihl < ipv4.HeaderLen {
  409. return ErrIPv4InvalidHeaderLength
  410. }
  411. // Check if this is the second or further fragment of a fragmented packet.
  412. flagsfrags := binary.BigEndian.Uint16(data[6:8])
  413. fp.Fragment = (flagsfrags & 0x1FFF) != 0
  414. // Firewall handles protocol checks
  415. fp.Protocol = data[9]
  416. // Accounting for a variable header length, do we have enough data for our src/dst tuples?
  417. minLen := ihl
  418. if !fp.Fragment {
  419. if fp.Protocol == firewall.ProtoICMP {
  420. minLen += minFwPacketLen + 2
  421. } else {
  422. minLen += minFwPacketLen
  423. }
  424. }
  425. if len(data) < minLen {
  426. return ErrIPv4InvalidHeaderLength
  427. }
  428. if incoming { // Firewall packets are locally oriented
  429. fp.RemoteAddr, _ = netip.AddrFromSlice(data[12:16])
  430. fp.LocalAddr, _ = netip.AddrFromSlice(data[16:20])
  431. } else {
  432. fp.LocalAddr, _ = netip.AddrFromSlice(data[12:16])
  433. fp.RemoteAddr, _ = netip.AddrFromSlice(data[16:20])
  434. }
  435. if fp.Fragment {
  436. fp.RemotePort = 0
  437. fp.LocalPort = 0
  438. } else if fp.Protocol == firewall.ProtoICMP { //note that orientation doesn't matter on ICMP
  439. fp.RemotePort = binary.BigEndian.Uint16(data[ihl+4 : ihl+6]) //identifier
  440. fp.LocalPort = 0 //code would be uint16(data[ihl+1])
  441. } else if incoming {
  442. fp.RemotePort = binary.BigEndian.Uint16(data[ihl : ihl+2]) //src port
  443. fp.LocalPort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4]) //dst port
  444. } else {
  445. fp.LocalPort = binary.BigEndian.Uint16(data[ihl : ihl+2]) //src port
  446. fp.RemotePort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4]) //dst port
  447. }
  448. return nil
  449. }
  450. func (f *Interface) decrypt(hostinfo *HostInfo, mc uint64, buf *WireBuffer, packet []byte, h *header.H) ([]byte, error) {
  451. plaintext, err := buf.DecryptForHandler(hostinfo.ConnectionState, packet, mc)
  452. if err != nil {
  453. return nil, err
  454. }
  455. if !hostinfo.ConnectionState.window.Update(f.l, mc) {
  456. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  457. hostinfo.logger(f.l).Debug("dropping out of window packet", "header", h)
  458. }
  459. return nil, errors.New("out of window packet")
  460. }
  461. return plaintext, nil
  462. }
  463. func (f *Interface) decryptToTun(hostinfo *HostInfo, messageCounter uint64, buf *WireBuffer, packet []byte, q int, localCache firewall.ConntrackCache) bool {
  464. if err := buf.DecryptDatagram(hostinfo.ConnectionState, packet, messageCounter); err != nil {
  465. hostinfo.logger(f.l).Error("Failed to decrypt packet", "error", err)
  466. return false
  467. }
  468. ipPacket := buf.IPPacket()
  469. if err := newPacket(ipPacket, true, buf.FwPacket); err != nil {
  470. hostinfo.logger(f.l).Warn("Error while validating inbound packet",
  471. "error", err,
  472. "packet", ipPacket,
  473. )
  474. return false
  475. }
  476. if !hostinfo.ConnectionState.window.Update(f.l, messageCounter) {
  477. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  478. hostinfo.logger(f.l).Debug("dropping out of window packet", "fwPacket", buf.FwPacket)
  479. }
  480. return false
  481. }
  482. dropReason := f.firewall.Drop(*buf.FwPacket, true, hostinfo, f.pki.GetCAPool(), localCache)
  483. if dropReason != nil {
  484. // NOTE: We hand `packet` (the original UDP ciphertext we already
  485. // decrypted from) as the reject-IP scratch since we no longer
  486. // need its ciphertext, and it's disjoint from buf.Out where
  487. // sendNoMetrics will encrypt the wire packet.
  488. f.rejectOutside(ipPacket, hostinfo.ConnectionState, hostinfo, packet, buf, q)
  489. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  490. hostinfo.logger(f.l).Debug("dropping inbound packet",
  491. "fwPacket", buf.FwPacket,
  492. "reason", dropReason,
  493. )
  494. }
  495. return false
  496. }
  497. f.connectionManager.In(hostinfo)
  498. if _, err := buf.WriteIPToTUN(f.readers[q]); err != nil {
  499. f.l.Error("Failed to write to tun", "error", err)
  500. }
  501. return true
  502. }
  503. func (f *Interface) maybeSendRecvError(endpoint netip.AddrPort, index uint32) {
  504. if f.sendRecvErrorConfig.ShouldRecvError(endpoint) {
  505. f.sendRecvError(endpoint, index)
  506. }
  507. }
  508. func (f *Interface) sendRecvError(endpoint netip.AddrPort, index uint32) {
  509. f.messageMetrics.Tx(header.RecvError, 0, 1)
  510. b := header.Encode(make([]byte, header.Len), header.Version, header.RecvError, 0, index, 0)
  511. _ = f.outside.WriteTo(b, endpoint)
  512. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  513. f.l.Debug("Recv error sent",
  514. "index", index,
  515. "udpAddr", endpoint,
  516. )
  517. }
  518. }
  519. func (f *Interface) handleRecvError(addr netip.AddrPort, h *header.H) {
  520. if !f.acceptRecvErrorConfig.ShouldRecvError(addr) {
  521. f.l.Debug("Recv error received, ignoring",
  522. "index", h.RemoteIndex,
  523. "udpAddr", addr,
  524. )
  525. return
  526. }
  527. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  528. f.l.Debug("Recv error received",
  529. "index", h.RemoteIndex,
  530. "udpAddr", addr,
  531. )
  532. }
  533. hostinfo := f.hostMap.QueryReverseIndex(h.RemoteIndex)
  534. if hostinfo == nil {
  535. f.l.Debug("Did not find remote index in main hostmap", "remoteIndex", h.RemoteIndex)
  536. return
  537. }
  538. if hostinfo.remote.IsValid() && hostinfo.remote != addr {
  539. f.l.Info("Someone spoofing recv_errors?",
  540. "addr", addr,
  541. "hostinfoRemote", hostinfo.remote,
  542. )
  543. return
  544. }
  545. f.closeTunnel(hostinfo)
  546. // We also delete it from pending hostmap to allow for fast reconnect.
  547. f.handshakeManager.DeleteHostInfo(hostinfo)
  548. }