1
0

outside.go 19 KB

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