outside.go 19 KB

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