outside.go 20 KB

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