outside.go 20 KB

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