outside.go 17 KB

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