outside.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. package nebula
  2. import (
  3. "context"
  4. "errors"
  5. "log/slog"
  6. "net/netip"
  7. "time"
  8. "github.com/slackhq/nebula/firewall"
  9. "github.com/slackhq/nebula/header"
  10. "github.com/slackhq/nebula/overlay/batch"
  11. "github.com/slackhq/nebula/udp"
  12. )
  13. var ErrOutOfWindow = errors.New("out of window packet")
  14. func (f *Interface) readOutsidePackets(via ViaSender, out []byte, packet []byte, h *header.H, fwPacket *firewall.Packet, parsedRx *batch.RxParsed, lhf *LightHouseHandler, nb []byte, q int, localCache firewall.ConntrackCache, meta udp.RxMeta) {
  15. err := h.Parse(packet)
  16. if err != nil {
  17. // Hole punch packets are 0 or 1 byte big, so lets ignore printing those errors
  18. // TODO: record metrics for rx holepunch/punchy packets?
  19. if len(packet) > 1 {
  20. f.messageMetrics.RxInvalid(1)
  21. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  22. f.l.Debug("Error while parsing inbound packet",
  23. "from", via,
  24. "error", err,
  25. "packet", packet,
  26. )
  27. }
  28. }
  29. return
  30. }
  31. if h.Version != header.Version {
  32. f.messageMetrics.RxInvalid(1)
  33. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  34. f.l.Debug("Unexpected header version received", "from", via)
  35. }
  36. return
  37. }
  38. // Check before processing to see if this is a expected type/subtype
  39. if !h.IsValidSubType() {
  40. f.messageMetrics.RxInvalid(1)
  41. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  42. f.l.Debug("Unexpected packet received", "from", via)
  43. }
  44. return
  45. }
  46. if !via.IsRelayed {
  47. if f.myVpnNetworksTable.Contains(via.UdpAddr.Addr()) {
  48. f.messageMetrics.RxInvalid(1)
  49. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  50. f.l.Debug("Refusing to process double encrypted packet", "from", via)
  51. }
  52. return
  53. }
  54. }
  55. // don't keep Rx metrics for message type, since you can see those in the tun metrics
  56. if h.Type != header.Message {
  57. f.messageMetrics.Rx(h.Type, h.Subtype, 1)
  58. }
  59. // Unencrypted packets
  60. switch h.Type {
  61. case header.Handshake:
  62. f.handshakeManager.HandleIncoming(via, packet, h)
  63. return
  64. case header.RecvError:
  65. f.handleRecvError(via.UdpAddr, h)
  66. return
  67. }
  68. // Relay packets are special
  69. isMessageRelay := (h.Type == header.Message && h.Subtype == header.MessageRelay)
  70. var hostinfo *HostInfo
  71. if isMessageRelay {
  72. hostinfo = f.hostMap.QueryRelayIndex(h.RemoteIndex)
  73. } else {
  74. hostinfo = f.hostMap.QueryIndex(h.RemoteIndex)
  75. }
  76. // At this point we should have a valid existing tunnel, verify and send
  77. // recvError if necessary
  78. if hostinfo == nil || hostinfo.ConnectionState == nil {
  79. if !via.IsRelayed {
  80. f.maybeSendRecvError(via.UdpAddr, h.RemoteIndex)
  81. }
  82. return
  83. }
  84. // All remaining packets are encrypted
  85. ci := hostinfo.ConnectionState
  86. if !ci.window.Check(f.l, h.MessageCounter) {
  87. return
  88. }
  89. // Relay packets are special
  90. if isMessageRelay {
  91. f.handleOutsideRelayPacket(hostinfo, via, out, packet, h, fwPacket, parsedRx, lhf, nb, q, localCache, meta)
  92. return
  93. }
  94. out, err = f.decrypt(hostinfo, h.MessageCounter, out, packet, h, nb)
  95. if err != nil {
  96. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  97. hostinfo.logger(f.l).Debug("Failed to decrypt packet",
  98. "error", err,
  99. "from", via,
  100. "header", h,
  101. )
  102. }
  103. return
  104. }
  105. // Roam before we respond
  106. f.handleHostRoaming(hostinfo, via)
  107. f.connectionManager.In(hostinfo)
  108. switch h.Type {
  109. case header.Message:
  110. switch h.Subtype {
  111. case header.MessageNone:
  112. f.handleOutsideMessagePacket(hostinfo, out, packet, fwPacket, parsedRx, nb, q, localCache, meta)
  113. default:
  114. hostinfo.logger(f.l).Error("IsValidSubType was true, but unexpected message subtype seen", "from", via, "header", h)
  115. return
  116. }
  117. case header.LightHouse:
  118. //TODO: assert via is not relayed
  119. lhf.HandleRequest(via.UdpAddr, hostinfo.vpnAddrs, out, f)
  120. case header.Test:
  121. switch h.Subtype {
  122. case header.TestReply:
  123. // No-op, useful for the Roaming and connectionManager side-effects above
  124. case header.TestRequest:
  125. f.send(header.Test, header.TestReply, ci, hostinfo, out, nb, out)
  126. default:
  127. hostinfo.logger(f.l).Error("IsValidSubType was true, but unexpected test subtype seen", "from", via, "header", h)
  128. return
  129. }
  130. case header.CloseTunnel:
  131. hostinfo.logger(f.l).Info("Close tunnel received, tearing down.", "from", via)
  132. f.closeTunnel(hostinfo)
  133. case header.Control:
  134. f.relayManager.HandleControlMsg(hostinfo, out, f)
  135. default:
  136. hostinfo.logger(f.l).Error("IsValidSubType was true, but unexpected message type seen", "from", via, "header", h)
  137. }
  138. }
  139. func (f *Interface) handleOutsideRelayPacket(hostinfo *HostInfo, via ViaSender, out []byte, packet []byte, h *header.H, fwPacket *firewall.Packet, parsedRx *batch.RxParsed, lhf *LightHouseHandler, nb []byte, q int, localCache firewall.ConntrackCache, meta udp.RxMeta) {
  140. // The entire body is sent as AD, not encrypted.
  141. // The packet consists of a 16-byte parsed Nebula header, Associated Data-protected payload, and a trailing 16-byte AEAD signature value.
  142. // 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
  143. // otherwise malformed (meaning, there is no trailing 16 byte AEAD value), then this will result in at worst a 0-length slice
  144. // which will gracefully fail in the DecryptDanger call.
  145. signedPayload := packet[:len(packet)-hostinfo.ConnectionState.dKey.Overhead()]
  146. signatureValue := packet[len(packet)-hostinfo.ConnectionState.dKey.Overhead():]
  147. var err error
  148. out, err = hostinfo.ConnectionState.dKey.DecryptDanger(out, signedPayload, signatureValue, h.MessageCounter, nb)
  149. if err != nil {
  150. return
  151. }
  152. // Successfully validated the thing. Get rid of the Relay header.
  153. signedPayload = signedPayload[header.Len:]
  154. // Pull the Roaming parts up here, and return in all call paths.
  155. f.handleHostRoaming(hostinfo, via)
  156. // Track usage of both the HostInfo and the Relay for the received & authenticated packet
  157. f.connectionManager.In(hostinfo)
  158. f.connectionManager.RelayUsed(h.RemoteIndex)
  159. relay, ok := hostinfo.relayState.QueryRelayForByIdx(h.RemoteIndex)
  160. if !ok {
  161. // The only way this happens is if hostmap has an index to the correct HostInfo, but the HostInfo is missing
  162. // its internal mapping. This should never happen.
  163. hostinfo.logger(f.l).Error("HostInfo missing remote relay index",
  164. "vpnAddrs", hostinfo.vpnAddrs,
  165. "remoteIndex", h.RemoteIndex,
  166. )
  167. return
  168. }
  169. switch relay.Type {
  170. case TerminalType:
  171. // If I am the target of this relay, process the unwrapped packet
  172. // From this recursive point, all these variables are 'burned'. We shouldn't rely on them again.
  173. via = ViaSender{
  174. UdpAddr: via.UdpAddr,
  175. relayHI: hostinfo,
  176. remoteIdx: relay.RemoteIndex,
  177. relay: relay,
  178. IsRelayed: true,
  179. }
  180. f.readOutsidePackets(via, out[:0], signedPayload, h, fwPacket, parsedRx, lhf, nb, q, localCache, meta)
  181. return
  182. case ForwardingType:
  183. // Find the target HostInfo relay object
  184. targetHI, targetRelay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relay.PeerAddr)
  185. if err != nil {
  186. hostinfo.logger(f.l).Info("Failed to find target host info by ip",
  187. "relayTo", relay.PeerAddr,
  188. "error", err,
  189. "hostinfo.vpnAddrs", hostinfo.vpnAddrs,
  190. )
  191. return
  192. }
  193. // If that relay is Established, forward the payload through it
  194. if targetRelay.State == Established {
  195. switch targetRelay.Type {
  196. case ForwardingType:
  197. // Forward this packet through the relay tunnel
  198. // Find the target HostInfo //todo it would potentially be nice to batch these
  199. f.SendVia(targetHI, targetRelay, signedPayload, nb, out, false)
  200. case TerminalType:
  201. hostinfo.logger(f.l).Error("Unexpected Relay Type of Terminal")
  202. return
  203. default:
  204. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  205. hostinfo.logger(f.l).Debug("Unexpected targetRelay Type", "from", via, "relayType", targetRelay.Type)
  206. }
  207. return
  208. }
  209. } else {
  210. hostinfo.logger(f.l).Info("Unexpected target relay state",
  211. "relayTo", relay.PeerAddr,
  212. "relayFrom", hostinfo.vpnAddrs[0],
  213. "targetRelayState", targetRelay.State,
  214. )
  215. return
  216. }
  217. default:
  218. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  219. hostinfo.logger(f.l).Debug("Unexpected relay type", "from", via, "relayType", relay.Type)
  220. }
  221. }
  222. }
  223. // closeTunnel closes a tunnel locally, it does not send a closeTunnel packet to the remote
  224. func (f *Interface) closeTunnel(hostInfo *HostInfo) {
  225. final := f.hostMap.DeleteHostInfo(hostInfo)
  226. if final {
  227. // We no longer have any tunnels with this vpn addr, clear learned lighthouse state to lower memory usage
  228. f.lightHouse.DeleteVpnAddrs(hostInfo.vpnAddrs)
  229. }
  230. }
  231. // sendCloseTunnel is a helper function to send a proper close tunnel packet to a remote
  232. func (f *Interface) sendCloseTunnel(h *HostInfo) {
  233. f.send(header.CloseTunnel, 0, h.ConnectionState, h, []byte{}, make([]byte, 12, 12), make([]byte, mtu))
  234. }
  235. func (f *Interface) handleHostRoaming(hostinfo *HostInfo, via ViaSender) {
  236. if !via.IsRelayed && hostinfo.remote != via.UdpAddr {
  237. if !f.lightHouse.GetRemoteAllowList().AllowAll(hostinfo.vpnAddrs, via.UdpAddr.Addr()) {
  238. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  239. hostinfo.logger(f.l).Debug("lighthouse.remote_allow_list denied roaming", "newAddr", via.UdpAddr)
  240. }
  241. return
  242. }
  243. if !hostinfo.lastRoam.IsZero() && via.UdpAddr == hostinfo.lastRoamRemote && time.Since(hostinfo.lastRoam) < RoamingSuppressSeconds*time.Second {
  244. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  245. hostinfo.logger(f.l).Debug("Suppressing roam back to previous remote",
  246. "suppressSeconds", RoamingSuppressSeconds,
  247. "udpAddr", hostinfo.remote,
  248. "newAddr", via.UdpAddr,
  249. )
  250. }
  251. return
  252. }
  253. hostinfo.logger(f.l).Info("Host roamed to new udp ip/port.",
  254. "udpAddr", hostinfo.remote,
  255. "newAddr", via.UdpAddr,
  256. )
  257. hostinfo.lastRoam = time.Now()
  258. hostinfo.lastRoamRemote = hostinfo.remote
  259. hostinfo.SetRemote(via.UdpAddr)
  260. }
  261. }
  262. var (
  263. ErrPacketTooShort = errors.New("packet is too short")
  264. ErrUnknownIPVersion = errors.New("packet is an unknown ip version")
  265. ErrIPv4InvalidHeaderLength = errors.New("invalid ipv4 header length")
  266. ErrIPv4PacketTooShort = errors.New("ipv4 packet is too short")
  267. ErrIPv6PacketTooShort = errors.New("ipv6 packet is too short")
  268. ErrIPv6CouldNotFindPayload = errors.New("could not find payload in ipv6 packet")
  269. )
  270. // newPacket validates and parses the interesting bits for the firewall out of the ip and sub protocol headers
  271. // newPacket parses data into a fully-hydrated firewall.Packet — kept as a
  272. // thin wrapper around newPacketKey + Hydrate so there's one source of
  273. // parse logic. Callers that don't need the netip.Addr-rich form (e.g.
  274. // conntrack-only paths) should use newPacketKey directly.
  275. func newPacket(data []byte, incoming bool, fp *firewall.Packet) error {
  276. var parsed batch.RxParsed
  277. if err := batch.ParsePacket(data, incoming, &parsed); err != nil {
  278. return err
  279. }
  280. parsed.Key.Hydrate(fp)
  281. return nil
  282. }
  283. func (f *Interface) decrypt(hostinfo *HostInfo, mc uint64, out []byte, packet []byte, h *header.H, nb []byte) ([]byte, error) {
  284. var err error
  285. out, err = hostinfo.ConnectionState.dKey.DecryptDanger(out, packet[:header.Len], packet[header.Len:], mc, nb)
  286. if err != nil {
  287. return nil, err
  288. }
  289. if !hostinfo.ConnectionState.window.Update(f.l, mc) {
  290. return nil, ErrOutOfWindow
  291. }
  292. return out, nil
  293. }
  294. // 2-bit IP-level ECN codepoints (lower bits of IPv4 ToS / IPv6 TC).
  295. const (
  296. ecnNotECT = 0x00
  297. ecnECT1 = 0x01
  298. ecnECT0 = 0x02
  299. ecnCE = 0x03
  300. )
  301. // applyOuterECN folds an outer CE mark from the underlay into the inner
  302. // IP header per RFC 6040 normal mode. It mutates pkt[1] in place. Other
  303. // codepoints are advisory only and leave the inner unchanged.
  304. //
  305. // Merge cases (outer × inner → action):
  306. //
  307. // outer != CE : no-op (inner is authoritative)
  308. // outer == CE, inner Not-ECT : log; cannot propagate to a non-ECN host
  309. // outer == CE, inner ECT/CE : rewrite inner ECN to CE
  310. func applyOuterECN(pkt []byte, outerECN byte, hostinfo *HostInfo, l *slog.Logger) {
  311. if outerECN&ecnCE != ecnCE || len(pkt) < 2 {
  312. return
  313. }
  314. switch pkt[0] >> 4 {
  315. case 4:
  316. switch pkt[1] & 0x03 {
  317. case ecnNotECT:
  318. if l.Enabled(context.Background(), slog.LevelDebug) {
  319. hostinfo.logger(l).Debug("RFC 6040: outer CE on inner Not-ECT, leaving inner unchanged")
  320. }
  321. case ecnCE:
  322. // Already CE.
  323. default:
  324. pkt[1] = (pkt[1] &^ 0x03) | ecnCE
  325. }
  326. case 6:
  327. switch (pkt[1] >> 4) & 0x03 {
  328. case ecnNotECT:
  329. if l.Enabled(context.Background(), slog.LevelDebug) {
  330. hostinfo.logger(l).Debug("RFC 6040: outer CE on inner Not-ECT, leaving inner unchanged")
  331. }
  332. case ecnCE:
  333. // Already CE.
  334. default:
  335. pkt[1] = (pkt[1] &^ 0x30) | (ecnCE << 4)
  336. }
  337. }
  338. }
  339. func (f *Interface) handleOutsideMessagePacket(hostinfo *HostInfo, out []byte, packet []byte, fwPacket *firewall.Packet, parsedRx *batch.RxParsed, nb []byte, q int, localCache firewall.ConntrackCache, meta udp.RxMeta) {
  340. // RFC 6040 normal-mode combine: fold any outer CE mark stamped by the
  341. // underlay into the inner header before firewall + TUN write. Other
  342. // outer codepoints are advisory only — we keep the inner unchanged.
  343. if f.ecnEnabled.Load() {
  344. applyOuterECN(out, meta.OuterECN, hostinfo, f.l)
  345. }
  346. // Single IP+L4 walk feeds the firewall conntrack key (parsedRx.Key)
  347. // and the batcher hint (parsedRx.tcp/udp). Replaces newPacket — and
  348. // pointedly does NOT fill fwPacket.LocalAddr/RemoteAddr, since
  349. // firewall.Drop's fast path uses Key alone and only hydrates fwPacket
  350. // from Key on the slow path.
  351. *fwPacket = firewall.Packet{}
  352. err := batch.ParsePacket(out, true, parsedRx)
  353. if err != nil {
  354. hostinfo.logger(f.l).Warn("Error while validating inbound packet",
  355. "error", err,
  356. "packet", out,
  357. )
  358. return
  359. }
  360. dropReason := f.firewall.Drop(parsedRx.Key, fwPacket, true, hostinfo, f.pki.GetCAPool(), localCache)
  361. if dropReason != nil {
  362. // NOTE: We give `packet` as the `out` here since we already decrypted from it and we don't need it anymore
  363. // This gives us a buffer to build the reject packet in
  364. f.rejectOutside(out, hostinfo.ConnectionState, hostinfo, nb, packet, q)
  365. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  366. hostinfo.logger(f.l).Debug("dropping inbound packet",
  367. "fwPacket", fwPacket,
  368. "reason", dropReason,
  369. )
  370. }
  371. return
  372. }
  373. err = f.batchers[q].CommitInbound(out, parsedRx)
  374. if err != nil {
  375. f.l.Error("Failed to write to tun", "error", err)
  376. }
  377. }
  378. func (f *Interface) maybeSendRecvError(endpoint netip.AddrPort, index uint32) {
  379. if f.sendRecvErrorConfig.ShouldRecvError(endpoint) {
  380. f.sendRecvError(endpoint, index)
  381. }
  382. }
  383. func (f *Interface) sendRecvError(endpoint netip.AddrPort, index uint32) {
  384. f.messageMetrics.Tx(header.RecvError, 0, 1)
  385. b := header.Encode(make([]byte, header.Len), header.Version, header.RecvError, 0, index, 0)
  386. _ = f.outside.WriteTo(b, endpoint)
  387. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  388. f.l.Debug("Recv error sent",
  389. "index", index,
  390. "udpAddr", endpoint,
  391. )
  392. }
  393. }
  394. func (f *Interface) handleRecvError(addr netip.AddrPort, h *header.H) {
  395. if !f.acceptRecvErrorConfig.ShouldRecvError(addr) {
  396. f.l.Debug("Recv error received, ignoring",
  397. "index", h.RemoteIndex,
  398. "udpAddr", addr,
  399. )
  400. return
  401. }
  402. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  403. f.l.Debug("Recv error received",
  404. "index", h.RemoteIndex,
  405. "udpAddr", addr,
  406. )
  407. }
  408. hostinfo := f.hostMap.QueryReverseIndex(h.RemoteIndex)
  409. if hostinfo == nil {
  410. f.l.Debug("Did not find remote index in main hostmap", "remoteIndex", h.RemoteIndex)
  411. return
  412. }
  413. if hostinfo.remote.IsValid() && hostinfo.remote != addr {
  414. f.l.Info("Someone spoofing recv_errors?",
  415. "addr", addr,
  416. "hostinfoRemote", hostinfo.remote,
  417. )
  418. return
  419. }
  420. f.closeTunnel(hostinfo)
  421. // We also delete it from pending hostmap to allow for fast reconnect.
  422. f.handshakeManager.DeleteHostInfo(hostinfo)
  423. }