outside.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. package nebula
  2. import (
  3. "context"
  4. "encoding/binary"
  5. "errors"
  6. "log/slog"
  7. "net/netip"
  8. "time"
  9. "golang.org/x/net/ipv6"
  10. "github.com/slackhq/nebula/firewall"
  11. "github.com/slackhq/nebula/header"
  12. "github.com/slackhq/nebula/iputil"
  13. "github.com/slackhq/nebula/overlay/batch"
  14. "golang.org/x/net/ipv4"
  15. )
  16. const (
  17. minFwPacketLen = 4
  18. )
  19. var ErrOutOfWindow = errors.New("out of window packet")
  20. // readOutsidePackets processes one received underlay packet.
  21. // Message payloads are decrypted IN PLACE, so packet must stay untouched
  22. // by the caller until the batcher for queue q has been flushed
  23. func (f *Interface) readOutsidePackets(via ViaSender, packet []byte, rxc *rxContext) {
  24. h := rxc.h
  25. err := h.Parse(packet)
  26. if err != nil {
  27. // Hole punch packets are 0 or 1 byte big, so lets ignore printing those errors
  28. // TODO: record metrics for rx holepunch/punchy packets?
  29. if len(packet) > 1 {
  30. f.messageMetrics.RxInvalid(1)
  31. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  32. f.l.Debug("Error while parsing inbound packet",
  33. "from", via,
  34. "error", err,
  35. "packet", packet,
  36. )
  37. }
  38. }
  39. return
  40. }
  41. if h.Version != header.Version {
  42. f.messageMetrics.RxInvalid(1)
  43. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  44. f.l.Debug("Unexpected header version received", "from", via)
  45. }
  46. return
  47. }
  48. // Check before processing to see if this is a expected type/subtype
  49. if !h.IsValidSubType() {
  50. f.messageMetrics.RxInvalid(1)
  51. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  52. f.l.Debug("Unexpected packet received", "from", via)
  53. }
  54. return
  55. }
  56. if !via.IsRelayed {
  57. if f.myVpnNetworksTable.Contains(via.UdpAddr.Addr()) {
  58. f.messageMetrics.RxInvalid(1)
  59. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  60. f.l.Debug("Refusing to process double encrypted packet", "from", via)
  61. }
  62. return
  63. }
  64. }
  65. // don't keep Rx metrics for message type, since you can see those in the tun metrics
  66. if h.Type != header.Message {
  67. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  68. }
  69. // Unencrypted packets
  70. switch h.Type {
  71. case header.Handshake:
  72. f.handshakeManager.HandleIncoming(via, packet, h)
  73. return
  74. case header.RecvError:
  75. f.handleRecvError(via.UdpAddr, h)
  76. return
  77. }
  78. // Relay packets are special
  79. isMessageRelay := (h.Type == header.Message && h.Subtype == header.MessageRelay)
  80. var hostinfo *HostInfo
  81. if isMessageRelay {
  82. hostinfo = f.hostMap.QueryRelayIndex(h.RemoteIndex)
  83. } else {
  84. hostinfo = f.hostMap.QueryIndexCached(h.RemoteIndex, rxc.hostmapCache)
  85. }
  86. // At this point we should have a valid existing tunnel, verify and send
  87. // recvError if necessary
  88. if hostinfo == nil || hostinfo.ConnectionState == nil {
  89. if !via.IsRelayed {
  90. f.maybeSendRecvError(via.UdpAddr, h.RemoteIndex, via.SockIdx)
  91. }
  92. return
  93. }
  94. // Which session decrypts this packet is the lane index in the header. Lane 0
  95. // is the base tunnel; a higher lane is one of the sessions derived from it.
  96. ci := hostinfo.ConnectionState
  97. lane := h.Lane()
  98. laneCached := true
  99. if lane != 0 {
  100. if isMessageRelay {
  101. // A relay carrier is always the base tunnel, so lane ciphertext can
  102. // never legitimately arrive wrapped in one. Checked before the lookup
  103. // below so a junk relay packet can't make us derive a session.
  104. f.messageMetrics.RxInvalid(1)
  105. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  106. hostinfo.logger(f.l).Debug("Refusing relayed multiport lane packet", "from", via, "header", h)
  107. }
  108. return
  109. }
  110. var err error
  111. ci, laneCached, err = hostinfo.laneSession(lane)
  112. if err != nil {
  113. f.messageMetrics.RxInvalid(1)
  114. hostinfo.logger(f.l).Error("Failed to derive multiport lane session", "error", err, "lane", lane)
  115. return
  116. }
  117. if ci == nil {
  118. // A lane this tunnel doesn't have: a stale lane from a tunnel that has
  119. // since rolled, or a peer sending above what it advertised. Dropping
  120. // silently is right for both — a recv_error would tear down a
  121. // perfectly good base tunnel on the strength of one odd packet.
  122. f.messageMetrics.RxInvalid(1)
  123. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  124. hostinfo.logger(f.l).Debug("Unknown multiport lane", "from", via, "header", h)
  125. }
  126. return
  127. }
  128. }
  129. if len(packet) < header.Len+ci.dKey.Overhead() {
  130. f.messageMetrics.RxInvalid(1)
  131. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  132. f.l.Debug("packet too small", "from", via, "length", len(packet))
  133. }
  134. return
  135. }
  136. // All remaining packets are encrypted
  137. if isMessageRelay {
  138. // Relay packets are special, this branch should always early-return
  139. err = ci.VerifyRelay(f.l, h.MessageCounter, packet, rxc.nb)
  140. if err != nil {
  141. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  142. hostinfo.logger(f.l).Debug("Failed to verify relay packet", "error", err, "from", via, "header", h)
  143. }
  144. return
  145. }
  146. f.handleOutsideRelayPacket(hostinfo, via, packet, rxc)
  147. return
  148. }
  149. out, err := ci.Decrypt(f.l, h.MessageCounter, packet, rxc.nb)
  150. if err != nil {
  151. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  152. hostinfo.logger(f.l).Debug("Failed to decrypt packet", "error", err, "from", via, "header", h)
  153. }
  154. return
  155. }
  156. if !laneCached {
  157. // The packet decrypted, so the peer really is using this lane and the
  158. // session we derived for it is worth keeping.
  159. hostinfo.lanes.installSession(f.l, lane, ci, h.MessageCounter)
  160. }
  161. // Roam before we respond, but only on the base tunnel: a lane's source
  162. // address is a per-lane 4-tuple, not the tunnel's remote, and letting it
  163. // roam the hostinfo would point every non-lane packet at a lane port.
  164. if lane == 0 {
  165. f.handleHostRoaming(hostinfo, via)
  166. }
  167. if !isLaneProbe(h.Type, h.Subtype) {
  168. f.connectionManager.In(hostinfo)
  169. }
  170. switch h.Type {
  171. case header.Message:
  172. switch h.Subtype {
  173. case header.MessageNone:
  174. f.handleOutsideMessagePacket(hostinfo, ci, h.MessageCounter, out, rxc)
  175. default:
  176. hostinfo.logger(f.l).Error("IsValidSubType was true, but unexpected message subtype seen", "from", via, "header", h)
  177. return
  178. }
  179. case header.LightHouse:
  180. //TODO: assert via is not relayed
  181. rxc.lhh.HandleRequest(via.UdpAddr, hostinfo.vpnAddrs, out, f)
  182. case header.Test:
  183. switch h.Subtype {
  184. case header.TestReply:
  185. // No-op, useful for the Roaming and connectionManager side-effects above
  186. case header.TestRequest:
  187. const maxCipherOverhead = 16 //todo we use this too often, needs a real importable const
  188. const maxOverhead = header.Len + header.Len + maxCipherOverhead + maxCipherOverhead
  189. if maxOverhead+len(out) > len(rxc.scratch) {
  190. // A reply that cannot fit in scratch is dropped no matter the log level.
  191. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  192. hostinfo.logger(f.l).Debug("dropping oversized test request", "payloadLen", len(out), "from", via)
  193. }
  194. return
  195. }
  196. f.send(header.Test, header.TestReply, hostinfo.ConnectionState, hostinfo, out, rxc.nb, rxc.scratch[:0])
  197. case header.LaneProbe:
  198. f.handleLaneProbe(hostinfo, lane, out, rxc)
  199. case header.LaneProbeAck:
  200. f.handleLaneProbeAck(hostinfo, out)
  201. default:
  202. hostinfo.logger(f.l).Error("IsValidSubType was true, but unexpected test subtype seen", "from", via, "header", h)
  203. return
  204. }
  205. case header.CloseTunnel:
  206. hostinfo.logger(f.l).Info("Close tunnel received, tearing down.", "from", via)
  207. f.closeTunnel(hostinfo)
  208. case header.Control:
  209. f.relayManager.HandleControlMsg(hostinfo, out, f)
  210. default:
  211. hostinfo.logger(f.l).Error("IsValidSubType was true, but unexpected message type seen", "from", via, "header", h)
  212. }
  213. }
  214. func (f *Interface) handleOutsideRelayPacket(hostinfo *HostInfo, via ViaSender, packet []byte, rxc *rxContext) {
  215. h := rxc.h
  216. // Successfully validated the thing. Get rid of the Relay header and the AEAD tag
  217. signedPayload := packet[header.Len : len(packet)-hostinfo.ConnectionState.dKey.Overhead()]
  218. // Pull the Roaming parts up here, and return in all call paths.
  219. f.handleHostRoaming(hostinfo, via)
  220. // Track usage of both the HostInfo and the Relay for the received & authenticated packet
  221. f.connectionManager.In(hostinfo)
  222. f.connectionManager.RelayUsed(h.RemoteIndex)
  223. relay, ok := hostinfo.relayState.QueryRelayForByIdx(h.RemoteIndex)
  224. if !ok {
  225. // The only way this happens is if hostmap has an index to the correct HostInfo, but the HostInfo is missing
  226. // its internal mapping. This should never happen.
  227. hostinfo.logger(f.l).Error("HostInfo missing remote relay index", "relayRemoteIndex", h.RemoteIndex)
  228. return
  229. }
  230. switch relay.Type {
  231. case TerminalType:
  232. // If I am the target of this relay, process the unwrapped packet
  233. // From this recursive point, all these variables are 'burned'. We shouldn't rely on them again.
  234. via = ViaSender{
  235. UdpAddr: via.UdpAddr,
  236. relayHI: hostinfo,
  237. relay: relay,
  238. IsRelayed: true,
  239. SockIdx: via.SockIdx,
  240. }
  241. f.readOutsidePackets(via, signedPayload, rxc)
  242. case ForwardingType:
  243. // Find the target HostInfo relay object
  244. targetHI, targetRelay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relay.PeerAddr)
  245. if err != nil {
  246. hostinfo.logger(f.l).Info("Failed to find target host info by ip",
  247. "relayTo", relay.PeerAddr,
  248. "relayFrom", hostinfo.vpnAddrs[0],
  249. "error", err,
  250. )
  251. return
  252. }
  253. // If that relay is Established, forward the payload through it
  254. if targetRelay.State == Established {
  255. switch targetRelay.Type {
  256. case ForwardingType:
  257. // Forward this packet through the relay tunnel, rebuilding it in place.
  258. // Encode overwrites the old outer header, and the new AEAD tag lands where the old one was
  259. fwdBuf := packet[:0]
  260. //todo it would potentially be nice to batch these
  261. f.SendVia(targetHI, targetRelay, signedPayload, rxc.nb, fwdBuf, true, rxc.q)
  262. case TerminalType:
  263. hostinfo.logger(f.l).Error("Unexpected Relay Type of Terminal")
  264. return
  265. default:
  266. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  267. hostinfo.logger(f.l).Debug("Unexpected targetRelay Type", "from", via, "relayType", targetRelay.Type)
  268. }
  269. return
  270. }
  271. } else {
  272. hostinfo.logger(f.l).Info("Unexpected target relay state",
  273. "relayTo", relay.PeerAddr,
  274. "relayFrom", hostinfo.vpnAddrs[0],
  275. "targetRelayState", targetRelay.State,
  276. )
  277. return
  278. }
  279. default:
  280. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  281. hostinfo.logger(f.l).Debug("Unexpected relay type", "from", via, "relayType", relay.Type)
  282. }
  283. }
  284. }
  285. // closeTunnel closes a tunnel locally, it does not send a closeTunnel packet to the remote
  286. func (f *Interface) closeTunnel(hostInfo *HostInfo) {
  287. final := f.hostMap.DeleteHostInfo(hostInfo)
  288. if final {
  289. // We no longer have any tunnels with this vpn addr, clear learned lighthouse state to lower memory usage
  290. f.lightHouse.DeleteVpnAddrs(hostInfo.vpnAddrs)
  291. }
  292. }
  293. // sendCloseTunnel is a helper function to send a proper close tunnel packet to a remote
  294. func (f *Interface) sendCloseTunnel(h *HostInfo) {
  295. f.send(header.CloseTunnel, 0, h.ConnectionState, h, []byte{}, make([]byte, 12, 12), make([]byte, mtu))
  296. }
  297. func (f *Interface) handleHostRoaming(hostinfo *HostInfo, via ViaSender) {
  298. curRemote := hostinfo.GetRemote()
  299. if !via.IsRelayed && curRemote != via.UdpAddr {
  300. if !f.lightHouse.GetRemoteAllowList().AllowAll(hostinfo.vpnAddrs, via.UdpAddr.Addr()) {
  301. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  302. hostinfo.logger(f.l).Debug("lighthouse.remote_allow_list denied roaming", "newAddr", via.UdpAddr)
  303. }
  304. return
  305. }
  306. if !hostinfo.lastRoam.IsZero() && via.UdpAddr == hostinfo.lastRoamRemote && time.Since(hostinfo.lastRoam) < RoamingSuppressSeconds*time.Second {
  307. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  308. hostinfo.logger(f.l).Debug("Suppressing roam back to previous remote",
  309. "suppressSeconds", RoamingSuppressSeconds,
  310. "udpAddr", curRemote,
  311. "newAddr", via.UdpAddr,
  312. )
  313. }
  314. return
  315. }
  316. hostinfo.logger(f.l).Info("Host roamed to new udp ip/port.",
  317. "udpAddr", curRemote,
  318. "newAddr", via.UdpAddr,
  319. )
  320. hostinfo.lastRoam = time.Now()
  321. hostinfo.lastRoamRemote = curRemote
  322. hostinfo.SetRemote(via.UdpAddr)
  323. }
  324. }
  325. var (
  326. ErrPacketTooShort = errors.New("packet is too short")
  327. ErrUnknownIPVersion = errors.New("packet is an unknown ip version")
  328. ErrIPv4InvalidHeaderLength = errors.New("invalid ipv4 header length")
  329. ErrIPv4PacketTooShort = errors.New("ipv4 packet is too short")
  330. ErrIPv6PacketTooShort = errors.New("ipv6 packet is too short")
  331. )
  332. // newPacket validates and parses the interesting bits for the firewall out of the ip and sub protocol headers
  333. func newPacket(data []byte, incoming bool, fp *firewall.ParsedPacket) error {
  334. // fp is reused across packets; reset the parse byproducts so an early-error return cannot
  335. // leak the previous packet's offsets.
  336. fp.IPHdrLen = 0
  337. fp.FragAny = false
  338. if len(data) < 1 {
  339. return ErrPacketTooShort
  340. }
  341. version := int((data[0] >> 4) & 0x0f)
  342. switch version {
  343. case ipv4.Version:
  344. return parseV4(data, incoming, fp)
  345. case ipv6.Version:
  346. return parseV6(data, incoming, fp)
  347. }
  348. return ErrUnknownIPVersion
  349. }
  350. func parseV6(data []byte, incoming bool, fp *firewall.ParsedPacket) error {
  351. dataLen := len(data)
  352. if dataLen < ipv6.HeaderLen {
  353. return ErrIPv6PacketTooShort
  354. }
  355. if incoming {
  356. fp.RemoteAddr, _ = netip.AddrFromSlice(data[8:24])
  357. fp.LocalAddr, _ = netip.AddrFromSlice(data[24:40])
  358. } else {
  359. fp.LocalAddr, _ = netip.AddrFromSlice(data[8:24])
  360. fp.RemoteAddr, _ = netip.AddrFromSlice(data[24:40])
  361. }
  362. // Walk the extension header chain to the upper layer protocol. iputil.IPv6FindUpperProtocol is the single
  363. // source of truth for which headers are extension headers, so this stays in lockstep with the reject path
  364. // and cannot drift into misreading an unknown protocol (SCTP, GRE, etc.) as a forged transport.
  365. proto, offset, isFragment, anyFragment, err := iputil.IPv6FindUpperProtocol(data)
  366. if err != nil {
  367. return ErrIPv6PacketTooShort
  368. }
  369. fp.Protocol = proto
  370. fp.Fragment = isFragment
  371. fp.FragAny = anyFragment
  372. fp.IPHdrLen = offset
  373. if isFragment {
  374. // Non-first fragments carry no transport header, so we have no ports to read
  375. fp.RemotePort = 0
  376. fp.LocalPort = 0
  377. return nil
  378. }
  379. switch proto {
  380. case iputil.IPProtocolICMPv6:
  381. // An ICMPv6 message is at least type, code and checksum, 4 bytes. Only echo carries more than we read.
  382. if dataLen < offset+4 {
  383. return ErrIPv6PacketTooShort
  384. }
  385. fp.LocalPort = 0 //incoming vs outgoing doesn't matter for icmpv6
  386. switch data[offset] { //icmp type
  387. case iputil.ICMPv6TypeEchoRequest, iputil.ICMPv6TypeEchoReply:
  388. if dataLen < offset+6 {
  389. return ErrIPv6PacketTooShort
  390. }
  391. fp.RemotePort = binary.BigEndian.Uint16(data[offset+4 : offset+6]) //identifier
  392. default:
  393. fp.RemotePort = 0
  394. }
  395. case iputil.IPProtocolTCP, iputil.IPProtocolUDP:
  396. if dataLen < offset+4 {
  397. return ErrIPv6PacketTooShort
  398. }
  399. if incoming {
  400. fp.RemotePort = binary.BigEndian.Uint16(data[offset : offset+2])
  401. fp.LocalPort = binary.BigEndian.Uint16(data[offset+2 : offset+4])
  402. } else {
  403. fp.LocalPort = binary.BigEndian.Uint16(data[offset : offset+2])
  404. fp.RemotePort = binary.BigEndian.Uint16(data[offset+2 : offset+4])
  405. }
  406. default:
  407. // don't set ports for protocols Nebula doesn't inspect
  408. fp.RemotePort = 0
  409. fp.LocalPort = 0
  410. }
  411. return nil
  412. }
  413. func parseV4(data []byte, incoming bool, fp *firewall.ParsedPacket) error {
  414. // Do we at least have an ipv4 header worth of data?
  415. if len(data) < ipv4.HeaderLen {
  416. return ErrIPv4PacketTooShort
  417. }
  418. // Adjust our start position based on the advertised ip header length
  419. ihl := int(data[0]&0x0f) << 2
  420. // Well-formed ip header length?
  421. if ihl < ipv4.HeaderLen {
  422. return ErrIPv4InvalidHeaderLength
  423. }
  424. // Check if this is the second or further fragment of a fragmented packet.
  425. flagsfrags := binary.BigEndian.Uint16(data[6:8])
  426. fp.Fragment = (flagsfrags & 0x1FFF) != 0
  427. // Any fragmentation at all (MF or offset): first fragments have readable ports for the
  428. // firewall but must never be coalesced.
  429. fp.FragAny = (flagsfrags & 0x3fff) != 0
  430. fp.IPHdrLen = ihl
  431. // Firewall handles protocol checks
  432. fp.Protocol = data[9]
  433. // Accounting for a variable header length, do we have enough data for our src/dst tuples?
  434. minLen := ihl
  435. if !fp.Fragment {
  436. if fp.Protocol == iputil.IPProtocolICMP {
  437. minLen += minFwPacketLen + 2
  438. } else {
  439. minLen += minFwPacketLen
  440. }
  441. }
  442. if len(data) < minLen {
  443. return ErrIPv4InvalidHeaderLength
  444. }
  445. if incoming { // Firewall packets are locally oriented
  446. fp.RemoteAddr, _ = netip.AddrFromSlice(data[12:16])
  447. fp.LocalAddr, _ = netip.AddrFromSlice(data[16:20])
  448. } else {
  449. fp.LocalAddr, _ = netip.AddrFromSlice(data[12:16])
  450. fp.RemoteAddr, _ = netip.AddrFromSlice(data[16:20])
  451. }
  452. if fp.Fragment {
  453. fp.RemotePort = 0
  454. fp.LocalPort = 0
  455. } else if fp.Protocol == iputil.IPProtocolICMP { //note that orientation doesn't matter on ICMP
  456. fp.RemotePort = binary.BigEndian.Uint16(data[ihl+4 : ihl+6]) //identifier
  457. fp.LocalPort = 0 //code would be uint16(data[ihl+1])
  458. } else if incoming {
  459. fp.RemotePort = binary.BigEndian.Uint16(data[ihl : ihl+2]) //src port
  460. fp.LocalPort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4]) //dst port
  461. } else {
  462. fp.LocalPort = binary.BigEndian.Uint16(data[ihl : ihl+2]) //src port
  463. fp.RemotePort = binary.BigEndian.Uint16(data[ihl+2 : ihl+4]) //dst port
  464. }
  465. return nil
  466. }
  467. func (f *Interface) handleOutsideMessagePacket(hostinfo *HostInfo, ci *ConnectionState, messageCounter uint64, out []byte, rxc *rxContext) {
  468. err := newPacket(out, true, rxc.fwPacket)
  469. if err != nil {
  470. hostinfo.logger(f.l).Warn("Error while validating inbound packet", "error", err, "packet", out)
  471. return
  472. }
  473. dropReason := f.firewall.Drop(rxc.fwPacket.Packet, true, hostinfo, f.pki.GetCAPool(), rxc.ctCache.Get())
  474. if dropReason != nil {
  475. // The reject rides the base tunnel: it is a control response, not lane
  476. // data, and the lane it arrived on says nothing about where it belongs.
  477. f.rejectOutside(out, hostinfo.ConnectionState, hostinfo, rxc.nb, rxc.scratch, rxc.q)
  478. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  479. hostinfo.logger(f.l).Debug("dropping inbound packet", "fwPacket", rxc.fwPacket, "reason", dropReason)
  480. }
  481. return
  482. }
  483. err = f.batchers[rxc.q].Commit(out, batch.SortKey{Epoch: ci.epoch, Counter: messageCounter}, rxc.fwPacket)
  484. if err != nil {
  485. f.l.Error("Failed to write to tun", "error", err)
  486. }
  487. }
  488. func (f *Interface) maybeSendRecvError(endpoint netip.AddrPort, index uint32, q int) {
  489. if f.sendRecvErrorConfig.ShouldRecvError(endpoint) {
  490. f.sendRecvError(endpoint, index, q)
  491. }
  492. }
  493. // sendRecvError replies from the socket the offending packet arrived on (q), so
  494. // the reply to lane traffic rides the reverse of the lane's own 4-tuple: the
  495. // only one the peer's NAT and stateful firewalls are known to let through. The
  496. // peer's handleRecvError accepts it from that lane's target.
  497. func (f *Interface) sendRecvError(endpoint netip.AddrPort, index uint32, q int) {
  498. f.messageMetrics.Tx(header.RecvError, 0, 1)
  499. b := header.Encode(make([]byte, header.Len), header.Version, header.RecvError, 0, index, 0)
  500. _ = f.writers[q].WriteTo(b, endpoint)
  501. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  502. f.l.Debug("Recv error sent",
  503. "index", index,
  504. "udpAddr", endpoint,
  505. )
  506. }
  507. }
  508. func (f *Interface) handleRecvError(addr netip.AddrPort, h *header.H) {
  509. if !f.acceptRecvErrorConfig.ShouldRecvError(addr) {
  510. f.l.Debug("Recv error received, ignoring",
  511. "index", h.RemoteIndex,
  512. "udpAddr", addr,
  513. )
  514. return
  515. }
  516. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  517. f.l.Debug("Recv error received",
  518. "index", h.RemoteIndex,
  519. "udpAddr", addr,
  520. )
  521. }
  522. hostinfo := f.hostMap.QueryReverseIndex(h.RemoteIndex)
  523. if hostinfo == nil {
  524. f.l.Debug("Did not find remote index in main hostmap", "remoteIndex", h.RemoteIndex)
  525. return
  526. }
  527. hr := hostinfo.GetRemote()
  528. if hr.IsValid() && hr != addr && !hostinfo.lanes.isLaneRemote(addr) {
  529. f.l.Info("Someone spoofing recv_errors?",
  530. "addr", addr,
  531. "hostinfoRemote", hr,
  532. )
  533. return
  534. }
  535. f.closeTunnel(hostinfo)
  536. // We also delete it from pending hostmap to allow for fast reconnect.
  537. f.handshakeManager.DeleteHostInfo(hostinfo)
  538. }