outside.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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. switch h.Subtype {
  167. case header.TestRequest:
  168. // This testRequest might be from TryPromoteBest, so we should roam
  169. // to the new IP address before responding
  170. f.handleHostRoaming(hostinfo, via)
  171. f.send(header.Test, header.TestReply, ci, hostinfo, d, nb, out)
  172. case header.MTUDProbeRequest:
  173. // Reply with just the 8-byte ack header so the reverse path doesn't have to
  174. // carry the full probe size; we only verify the forward direction.
  175. if len(d) >= 8 {
  176. f.send(header.Test, header.MTUDProbeReply, ci, hostinfo, d[:8], nb, out)
  177. }
  178. case header.MTUDProbeReply:
  179. f.pmtudManager.HandleReply(hostinfo.localIndexId, d)
  180. }
  181. // Fallthrough to the bottom to record incoming traffic
  182. // Non encrypted messages below here, they should not fall through to avoid tracking incoming traffic since they
  183. // are unauthenticated
  184. case header.Handshake:
  185. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  186. f.handshakeManager.HandleIncoming(via, packet, h)
  187. return
  188. case header.RecvError:
  189. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  190. f.handleRecvError(via.UdpAddr, h)
  191. return
  192. case header.CloseTunnel:
  193. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  194. if !f.handleEncrypted(ci, via, h) {
  195. return
  196. }
  197. _, err = f.decrypt(hostinfo, h.MessageCounter, out, packet, h, nb)
  198. if err != nil {
  199. hostinfo.logger(f.l).Error("Failed to decrypt CloseTunnel packet",
  200. "error", err,
  201. "from", via,
  202. "packet", packet,
  203. )
  204. return
  205. }
  206. hostinfo.logger(f.l).Info("Close tunnel received, tearing down.", "from", via)
  207. f.closeTunnel(hostinfo)
  208. return
  209. case header.Control:
  210. if !f.handleEncrypted(ci, via, h) {
  211. return
  212. }
  213. d, err := f.decrypt(hostinfo, h.MessageCounter, out, packet, h, nb)
  214. if err != nil {
  215. hostinfo.logger(f.l).Error("Failed to decrypt Control packet",
  216. "error", err,
  217. "from", via,
  218. "packet", packet,
  219. )
  220. return
  221. }
  222. f.relayManager.HandleControlMsg(hostinfo, d, f)
  223. default:
  224. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  225. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  226. hostinfo.logger(f.l).Debug("Unexpected packet received", "from", via)
  227. }
  228. return
  229. }
  230. f.handleHostRoaming(hostinfo, via)
  231. f.connectionManager.In(hostinfo)
  232. }
  233. // closeTunnel closes a tunnel locally, it does not send a closeTunnel packet to the remote
  234. func (f *Interface) closeTunnel(hostInfo *HostInfo) {
  235. f.pmtudManager.OnTunnelDown(hostInfo)
  236. final := f.hostMap.DeleteHostInfo(hostInfo)
  237. if final {
  238. // We no longer have any tunnels with this vpn addr, clear learned lighthouse state to lower memory usage
  239. f.lightHouse.DeleteVpnAddrs(hostInfo.vpnAddrs)
  240. }
  241. }
  242. // sendCloseTunnel is a helper function to send a proper close tunnel packet to a remote
  243. func (f *Interface) sendCloseTunnel(h *HostInfo) {
  244. f.send(header.CloseTunnel, 0, h.ConnectionState, h, []byte{}, make([]byte, 12, 12), make([]byte, mtu))
  245. }
  246. func (f *Interface) handleHostRoaming(hostinfo *HostInfo, via ViaSender) {
  247. if !via.IsRelayed && hostinfo.remote != via.UdpAddr {
  248. if !f.lightHouse.GetRemoteAllowList().AllowAll(hostinfo.vpnAddrs, via.UdpAddr.Addr()) {
  249. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  250. hostinfo.logger(f.l).Debug("lighthouse.remote_allow_list denied roaming", "newAddr", via.UdpAddr)
  251. }
  252. return
  253. }
  254. if !hostinfo.lastRoam.IsZero() && via.UdpAddr == hostinfo.lastRoamRemote && time.Since(hostinfo.lastRoam) < RoamingSuppressSeconds*time.Second {
  255. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  256. hostinfo.logger(f.l).Debug("Suppressing roam back to previous remote",
  257. "suppressSeconds", RoamingSuppressSeconds,
  258. "udpAddr", hostinfo.remote,
  259. "newAddr", via.UdpAddr,
  260. )
  261. }
  262. return
  263. }
  264. hostinfo.logger(f.l).Info("Host roamed to new udp ip/port.",
  265. "udpAddr", hostinfo.remote,
  266. "newAddr", via.UdpAddr,
  267. )
  268. hostinfo.lastRoam = time.Now()
  269. hostinfo.lastRoamRemote = hostinfo.remote
  270. hostinfo.SetRemote(via.UdpAddr)
  271. f.pmtudManager.OnRoam(hostinfo)
  272. }
  273. }
  274. // handleEncrypted returns true if a packet should be processed, false otherwise
  275. func (f *Interface) handleEncrypted(ci *ConnectionState, via ViaSender, h *header.H) bool {
  276. // If connectionstate does not exist, send a recv error, if possible, to encourage a fast reconnect
  277. if ci == nil {
  278. if !via.IsRelayed {
  279. f.maybeSendRecvError(via.UdpAddr, h.RemoteIndex)
  280. }
  281. return false
  282. }
  283. // If the window check fails, refuse to process the packet, but don't send a recv error
  284. if !ci.window.Check(f.l, h.MessageCounter) {
  285. return false
  286. }
  287. return true
  288. }
  289. var (
  290. ErrPacketTooShort = errors.New("packet is too short")
  291. ErrUnknownIPVersion = errors.New("packet is an unknown ip version")
  292. ErrIPv4InvalidHeaderLength = errors.New("invalid ipv4 header length")
  293. ErrIPv4PacketTooShort = errors.New("ipv4 packet is too short")
  294. ErrIPv6PacketTooShort = errors.New("ipv6 packet is too short")
  295. ErrIPv6CouldNotFindPayload = errors.New("could not find payload in ipv6 packet")
  296. )
  297. // newPacket validates and parses the interesting bits for the firewall out of the ip and sub protocol headers
  298. func newPacket(data []byte, incoming bool, fp *firewall.Packet) error {
  299. if len(data) < 1 {
  300. return ErrPacketTooShort
  301. }
  302. version := int((data[0] >> 4) & 0x0f)
  303. switch version {
  304. case ipv4.Version:
  305. return parseV4(data, incoming, fp)
  306. case ipv6.Version:
  307. return parseV6(data, incoming, fp)
  308. }
  309. return ErrUnknownIPVersion
  310. }
  311. func parseV6(data []byte, incoming bool, fp *firewall.Packet) error {
  312. dataLen := len(data)
  313. if dataLen < ipv6.HeaderLen {
  314. return ErrIPv6PacketTooShort
  315. }
  316. if incoming {
  317. fp.RemoteAddr, _ = netip.AddrFromSlice(data[8:24])
  318. fp.LocalAddr, _ = netip.AddrFromSlice(data[24:40])
  319. } else {
  320. fp.LocalAddr, _ = netip.AddrFromSlice(data[8:24])
  321. fp.RemoteAddr, _ = netip.AddrFromSlice(data[24:40])
  322. }
  323. protoAt := 6 // NextHeader is at 6 bytes into the ipv6 header
  324. offset := ipv6.HeaderLen // Start at the end of the ipv6 header
  325. next := 0
  326. for {
  327. if protoAt >= dataLen {
  328. break
  329. }
  330. proto := layers.IPProtocol(data[protoAt])
  331. switch proto {
  332. case layers.IPProtocolESP, layers.IPProtocolNoNextHeader:
  333. fp.Protocol = uint8(proto)
  334. fp.RemotePort = 0
  335. fp.LocalPort = 0
  336. fp.Fragment = false
  337. return nil
  338. case layers.IPProtocolICMPv6:
  339. if dataLen < offset+6 {
  340. return ErrIPv6PacketTooShort
  341. }
  342. fp.Protocol = uint8(proto)
  343. fp.LocalPort = 0 //incoming vs outgoing doesn't matter for icmpv6
  344. icmptype := data[offset+1]
  345. switch icmptype {
  346. case layers.ICMPv6TypeEchoRequest, layers.ICMPv6TypeEchoReply:
  347. fp.RemotePort = binary.BigEndian.Uint16(data[offset+4 : offset+6]) //identifier
  348. default:
  349. fp.RemotePort = 0
  350. }
  351. fp.Fragment = false
  352. return nil
  353. case layers.IPProtocolTCP, layers.IPProtocolUDP:
  354. if dataLen < offset+4 {
  355. return ErrIPv6PacketTooShort
  356. }
  357. fp.Protocol = uint8(proto)
  358. if incoming {
  359. fp.RemotePort = binary.BigEndian.Uint16(data[offset : offset+2])
  360. fp.LocalPort = binary.BigEndian.Uint16(data[offset+2 : offset+4])
  361. } else {
  362. fp.LocalPort = binary.BigEndian.Uint16(data[offset : offset+2])
  363. fp.RemotePort = binary.BigEndian.Uint16(data[offset+2 : offset+4])
  364. }
  365. fp.Fragment = false
  366. return nil
  367. case layers.IPProtocolIPv6Fragment:
  368. // Fragment header is 8 bytes, need at least offset+4 to read the offset field
  369. if dataLen < offset+8 {
  370. return ErrIPv6PacketTooShort
  371. }
  372. // Check if this is the first fragment
  373. fragmentOffset := binary.BigEndian.Uint16(data[offset+2:offset+4]) &^ uint16(0x7) // Remove the reserved and M flag bits
  374. if fragmentOffset != 0 {
  375. // Non-first fragment, use what we have now and stop processing
  376. fp.Protocol = data[offset]
  377. fp.Fragment = true
  378. fp.RemotePort = 0
  379. fp.LocalPort = 0
  380. return nil
  381. }
  382. // The next loop should be the transport layer since we are the first fragment
  383. next = 8 // Fragment headers are always 8 bytes
  384. case layers.IPProtocolAH:
  385. // Auth headers, used by IPSec, have a different meaning for header length
  386. if dataLen <= offset+1 {
  387. break
  388. }
  389. next = int(data[offset+1]+2) << 2
  390. default:
  391. // Normal ipv6 header length processing
  392. if dataLen <= offset+1 {
  393. break
  394. }
  395. next = int(data[offset+1]+1) << 3
  396. }
  397. if next <= 0 {
  398. // Safety check, each ipv6 header has to be at least 8 bytes
  399. next = 8
  400. }
  401. protoAt = offset
  402. offset = offset + next
  403. }
  404. return ErrIPv6CouldNotFindPayload
  405. }
  406. func parseV4(data []byte, incoming bool, fp *firewall.Packet) error {
  407. // Do we at least have an ipv4 header worth of data?
  408. if len(data) < ipv4.HeaderLen {
  409. return ErrIPv4PacketTooShort
  410. }
  411. // Adjust our start position based on the advertised ip header length
  412. ihl := int(data[0]&0x0f) << 2
  413. // Well-formed ip header length?
  414. if ihl < ipv4.HeaderLen {
  415. return ErrIPv4InvalidHeaderLength
  416. }
  417. // Check if this is the second or further fragment of a fragmented packet.
  418. flagsfrags := binary.BigEndian.Uint16(data[6:8])
  419. fp.Fragment = (flagsfrags & 0x1FFF) != 0
  420. // Firewall handles protocol checks
  421. fp.Protocol = data[9]
  422. // Accounting for a variable header length, do we have enough data for our src/dst tuples?
  423. minLen := ihl
  424. if !fp.Fragment {
  425. if fp.Protocol == firewall.ProtoICMP {
  426. minLen += minFwPacketLen + 2
  427. } else {
  428. minLen += minFwPacketLen
  429. }
  430. }
  431. if len(data) < minLen {
  432. return ErrIPv4InvalidHeaderLength
  433. }
  434. if incoming { // Firewall packets are locally oriented
  435. fp.RemoteAddr, _ = netip.AddrFromSlice(data[12:16])
  436. fp.LocalAddr, _ = netip.AddrFromSlice(data[16:20])
  437. } else {
  438. fp.LocalAddr, _ = netip.AddrFromSlice(data[12:16])
  439. fp.RemoteAddr, _ = netip.AddrFromSlice(data[16:20])
  440. }
  441. if fp.Fragment {
  442. fp.RemotePort = 0
  443. fp.LocalPort = 0
  444. } else if fp.Protocol == firewall.ProtoICMP { //note that orientation doesn't matter on ICMP
  445. fp.RemotePort = binary.BigEndian.Uint16(data[ihl+4 : ihl+6]) //identifier
  446. fp.LocalPort = 0 //code would be uint16(data[ihl+1])
  447. } else if incoming {
  448. fp.RemotePort = binary.BigEndian.Uint16(data[ihl : ihl+2]) //src port
  449. fp.LocalPort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4]) //dst port
  450. } else {
  451. fp.LocalPort = binary.BigEndian.Uint16(data[ihl : ihl+2]) //src port
  452. fp.RemotePort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4]) //dst port
  453. }
  454. return nil
  455. }
  456. func (f *Interface) decrypt(hostinfo *HostInfo, mc uint64, out []byte, packet []byte, h *header.H, nb []byte) ([]byte, error) {
  457. var err error
  458. out, err = hostinfo.ConnectionState.dKey.DecryptDanger(out, packet[:header.Len], packet[header.Len:], mc, nb)
  459. if err != nil {
  460. return nil, err
  461. }
  462. if !hostinfo.ConnectionState.window.Update(f.l, mc) {
  463. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  464. hostinfo.logger(f.l).Debug("dropping out of window packet", "header", h)
  465. }
  466. return nil, errors.New("out of window packet")
  467. }
  468. return out, nil
  469. }
  470. func (f *Interface) decryptToTun(hostinfo *HostInfo, messageCounter uint64, out []byte, packet []byte, fwPacket *firewall.Packet, nb []byte, q int, localCache firewall.ConntrackCache) bool {
  471. var err error
  472. out, err = hostinfo.ConnectionState.dKey.DecryptDanger(out, packet[:header.Len], packet[header.Len:], messageCounter, nb)
  473. if err != nil {
  474. hostinfo.logger(f.l).Error("Failed to decrypt packet", "error", err)
  475. return false
  476. }
  477. err = newPacket(out, true, fwPacket)
  478. if err != nil {
  479. hostinfo.logger(f.l).Warn("Error while validating inbound packet",
  480. "error", err,
  481. "packet", out,
  482. )
  483. return false
  484. }
  485. if !hostinfo.ConnectionState.window.Update(f.l, messageCounter) {
  486. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  487. hostinfo.logger(f.l).Debug("dropping out of window packet", "fwPacket", fwPacket)
  488. }
  489. return false
  490. }
  491. dropReason := f.firewall.Drop(*fwPacket, true, hostinfo, f.pki.GetCAPool(), localCache)
  492. if dropReason != nil {
  493. // NOTE: We give `packet` as the `out` here since we already decrypted from it and we don't need it anymore
  494. // This gives us a buffer to build the reject packet in
  495. f.rejectOutside(out, hostinfo.ConnectionState, hostinfo, nb, packet, q)
  496. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  497. hostinfo.logger(f.l).Debug("dropping inbound packet",
  498. "fwPacket", fwPacket,
  499. "reason", dropReason,
  500. )
  501. }
  502. return false
  503. }
  504. f.connectionManager.In(hostinfo)
  505. _, err = f.readers[q].Write(out)
  506. if err != nil {
  507. f.l.Error("Failed to write to tun", "error", err)
  508. }
  509. return true
  510. }
  511. func (f *Interface) maybeSendRecvError(endpoint netip.AddrPort, index uint32) {
  512. if f.sendRecvErrorConfig.ShouldRecvError(endpoint) {
  513. f.sendRecvError(endpoint, index)
  514. }
  515. }
  516. func (f *Interface) sendRecvError(endpoint netip.AddrPort, index uint32) {
  517. f.messageMetrics.Tx(header.RecvError, 0, 1)
  518. b := header.Encode(make([]byte, header.Len), header.Version, header.RecvError, 0, index, 0)
  519. _ = f.outside.WriteTo(b, endpoint)
  520. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  521. f.l.Debug("Recv error sent",
  522. "index", index,
  523. "udpAddr", endpoint,
  524. )
  525. }
  526. }
  527. func (f *Interface) handleRecvError(addr netip.AddrPort, h *header.H) {
  528. if !f.acceptRecvErrorConfig.ShouldRecvError(addr) {
  529. f.l.Debug("Recv error received, ignoring",
  530. "index", h.RemoteIndex,
  531. "udpAddr", addr,
  532. )
  533. return
  534. }
  535. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  536. f.l.Debug("Recv error received",
  537. "index", h.RemoteIndex,
  538. "udpAddr", addr,
  539. )
  540. }
  541. hostinfo := f.hostMap.QueryReverseIndex(h.RemoteIndex)
  542. if hostinfo == nil {
  543. f.l.Debug("Did not find remote index in main hostmap", "remoteIndex", h.RemoteIndex)
  544. return
  545. }
  546. if hostinfo.remote.IsValid() && hostinfo.remote != addr {
  547. f.l.Info("Someone spoofing recv_errors?",
  548. "addr", addr,
  549. "hostinfoRemote", hostinfo.remote,
  550. )
  551. return
  552. }
  553. f.closeTunnel(hostinfo)
  554. // We also delete it from pending hostmap to allow for fast reconnect.
  555. f.handshakeManager.DeleteHostInfo(hostinfo)
  556. }