outside.go 21 KB

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