outside.go 17 KB

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