1
0

inside.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. package nebula
  2. import (
  3. "context"
  4. "log/slog"
  5. "net/netip"
  6. "github.com/slackhq/nebula/firewall"
  7. "github.com/slackhq/nebula/header"
  8. "github.com/slackhq/nebula/iputil"
  9. "github.com/slackhq/nebula/noiseutil"
  10. "github.com/slackhq/nebula/overlay/batch"
  11. "github.com/slackhq/nebula/routing"
  12. )
  13. func (f *Interface) consumeInsidePacket(packet []byte, fwPacket *firewall.Packet, nb []byte, sendBatch batch.TxBatcher, rejectBuf []byte, q int, localCache firewall.ConntrackCache) {
  14. err := newPacket(packet, false, fwPacket)
  15. if err != nil {
  16. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  17. f.l.Debug("Error while validating outbound packet",
  18. "packet", packet,
  19. "error", err,
  20. )
  21. }
  22. return
  23. }
  24. // Ignore local broadcast packets
  25. if f.dropLocalBroadcast {
  26. if f.myBroadcastAddrsTable.Contains(fwPacket.RemoteAddr) {
  27. return
  28. }
  29. }
  30. if f.myVpnAddrsTable.Contains(fwPacket.RemoteAddr) {
  31. // Immediately forward packets from self to self.
  32. // This should only happen on Darwin-based and FreeBSD hosts, which
  33. // routes packets from the Nebula addr to the Nebula addr through the Nebula
  34. // TUN device.
  35. if immediatelyForwardToSelf {
  36. _, err := f.readers[q].Write(packet)
  37. if err != nil {
  38. f.l.Error("Failed to forward to tun", "error", err)
  39. }
  40. }
  41. // Otherwise, drop. On linux, we should never see these packets - Linux
  42. // routes packets from the nebula addr to the nebula addr through the loopback device.
  43. return
  44. }
  45. // Ignore multicast packets
  46. if f.dropMulticast && fwPacket.RemoteAddr.IsMulticast() {
  47. return
  48. }
  49. hostinfo, ready := f.getOrHandshakeConsiderRouting(fwPacket, func(hh *HandshakeHostInfo) {
  50. hh.cachePacket(f.l, header.Message, 0, packet, f.sendMessageNow, f.cachedPacketMetrics)
  51. })
  52. if hostinfo == nil {
  53. f.rejectInside(packet, rejectBuf, q)
  54. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  55. f.l.Debug("dropping outbound packet, vpnAddr not in our vpn networks or in unsafe networks",
  56. "vpnAddr", fwPacket.RemoteAddr,
  57. "fwPacket", fwPacket,
  58. )
  59. }
  60. return
  61. }
  62. if !ready {
  63. return
  64. }
  65. dropReason := f.firewall.Drop(*fwPacket, false, hostinfo, f.pki.GetCAPool(), localCache)
  66. if dropReason == nil {
  67. f.sendInsideMessage(hostinfo, packet, nb, sendBatch, rejectBuf, q)
  68. } else {
  69. f.rejectInside(packet, rejectBuf, q)
  70. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  71. hostinfo.logger(f.l).Debug("dropping outbound packet",
  72. "fwPacket", fwPacket,
  73. "reason", dropReason,
  74. )
  75. }
  76. }
  77. }
  78. // sendInsideMessage encrypts a firewall-approved inside packet into the
  79. // caller's batch slot for later sendmmsg flush. When hostinfo.remote is not
  80. // valid we fall through to the relay slow path via the unbatched sendNoMetrics
  81. // so relay behavior is unchanged.
  82. func (f *Interface) sendInsideMessage(hostinfo *HostInfo, p, nb []byte, sendBatch batch.TxBatcher, rejectBuf []byte, q int) {
  83. ci := hostinfo.ConnectionState
  84. if ci.eKey == nil {
  85. return
  86. }
  87. if !hostinfo.remote.IsValid() {
  88. // Slow path: relay fallback. Reuse rejectBuf as the ciphertext
  89. // scratch; sendNoMetrics arranges header space for SendVia.
  90. f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, p, nb, rejectBuf, q)
  91. return
  92. }
  93. scratch := sendBatch.Next()
  94. if scratch == nil {
  95. // Batch full: bypass batching and send this packet directly so we
  96. // never drop traffic on over-subscribed iterations.
  97. f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, p, nb, rejectBuf, q)
  98. return
  99. }
  100. if noiseutil.EncryptLockNeeded {
  101. ci.writeLock.Lock()
  102. }
  103. c := ci.messageCounter.Add(1)
  104. out := header.Encode(scratch, header.Version, header.Message, 0, hostinfo.remoteIndexId, c)
  105. f.connectionManager.Out(hostinfo)
  106. if hostinfo.lastRebindCount != f.rebindCount {
  107. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  108. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  109. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  110. hostinfo.lastRebindCount = f.rebindCount
  111. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  112. hostinfo.logger(f.l).Debug("Lighthouse update triggered for punch due to rebind counter",
  113. "vpnAddrs", hostinfo.vpnAddrs,
  114. )
  115. }
  116. }
  117. out, err := ci.eKey.EncryptDanger(out, out, p, c, nb)
  118. if noiseutil.EncryptLockNeeded {
  119. ci.writeLock.Unlock()
  120. }
  121. if err != nil {
  122. hostinfo.logger(f.l).Error("Failed to encrypt outgoing packet",
  123. "error", err,
  124. "udpAddr", hostinfo.remote,
  125. "counter", c,
  126. )
  127. return
  128. }
  129. sendBatch.Commit(len(out), hostinfo.remote)
  130. }
  131. func (f *Interface) rejectInside(packet []byte, out []byte, q int) {
  132. if !f.firewall.InSendReject {
  133. return
  134. }
  135. out = iputil.CreateRejectPacket(packet, out)
  136. if len(out) == 0 {
  137. return
  138. }
  139. _, err := f.readers[q].Write(out)
  140. if err != nil {
  141. f.l.Error("Failed to write to tun", "error", err)
  142. }
  143. }
  144. func (f *Interface) rejectOutside(packet []byte, ci *ConnectionState, hostinfo *HostInfo, nb, out []byte, q int) {
  145. if !f.firewall.OutSendReject {
  146. return
  147. }
  148. out = iputil.CreateRejectPacket(packet, out)
  149. if len(out) == 0 {
  150. return
  151. }
  152. if len(out) > iputil.MaxRejectPacketSize {
  153. if f.l.Enabled(context.Background(), slog.LevelInfo) {
  154. f.l.Info("rejectOutside: packet too big, not sending",
  155. "packet", packet,
  156. "outPacket", out,
  157. )
  158. }
  159. return
  160. }
  161. f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, out, nb, packet, q)
  162. }
  163. // Handshake will attempt to initiate a tunnel with the provided vpn address. This is a no-op if the tunnel is already established or being established
  164. // it does not check if it is within our vpn networks!
  165. func (f *Interface) Handshake(vpnAddr netip.Addr) {
  166. f.handshakeManager.GetOrHandshake(vpnAddr, nil)
  167. }
  168. // getOrHandshakeNoRouting returns nil if the vpnAddr is not routable.
  169. // If the 2nd return var is false then the hostinfo is not ready to be used in a tunnel
  170. func (f *Interface) getOrHandshakeNoRouting(vpnAddr netip.Addr, cacheCallback func(*HandshakeHostInfo)) (*HostInfo, bool) {
  171. if f.myVpnNetworksTable.Contains(vpnAddr) {
  172. return f.handshakeManager.GetOrHandshake(vpnAddr, cacheCallback)
  173. }
  174. return nil, false
  175. }
  176. // getOrHandshakeConsiderRouting will try to find the HostInfo to handle this packet, starting a handshake if necessary.
  177. // If the 2nd return var is false then the hostinfo is not ready to be used in a tunnel.
  178. func (f *Interface) getOrHandshakeConsiderRouting(fwPacket *firewall.Packet, cacheCallback func(*HandshakeHostInfo)) (*HostInfo, bool) {
  179. destinationAddr := fwPacket.RemoteAddr
  180. hostinfo, ready := f.getOrHandshakeNoRouting(destinationAddr, cacheCallback)
  181. // Host is inside the mesh, no routing required
  182. if hostinfo != nil {
  183. return hostinfo, ready
  184. }
  185. gateways := f.inside.RoutesFor(destinationAddr)
  186. switch len(gateways) {
  187. case 0:
  188. return nil, false
  189. case 1:
  190. // Single gateway route
  191. return f.handshakeManager.GetOrHandshake(gateways[0].Addr(), cacheCallback)
  192. default:
  193. // Multi gateway route, perform ECMP categorization
  194. gatewayAddr, balancingOk := routing.BalancePacket(fwPacket, gateways)
  195. if !balancingOk {
  196. // This happens if the gateway buckets were not calculated, this _should_ never happen
  197. f.l.Error("Gateway buckets not calculated, fallback from ECMP to random routing. Please report this bug.")
  198. }
  199. var handshakeInfoForChosenGateway *HandshakeHostInfo
  200. var hhReceiver = func(hh *HandshakeHostInfo) {
  201. handshakeInfoForChosenGateway = hh
  202. }
  203. // Store the handshakeHostInfo for later.
  204. // If this node is not reachable we will attempt other nodes, if none are reachable we will
  205. // cache the packet for this gateway.
  206. if hostinfo, ready = f.handshakeManager.GetOrHandshake(gatewayAddr, hhReceiver); ready {
  207. return hostinfo, true
  208. }
  209. // It appears the selected gateway cannot be reached, find another gateway to fallback on.
  210. // The current implementation breaks ECMP but that seems better than no connectivity.
  211. // If ECMP is also required when a gateway is down then connectivity status
  212. // for each gateway needs to be kept and the weights recalculated when they go up or down.
  213. // This would also need to interact with unsafe_route updates through reloading the config or
  214. // use of the use_system_route_table option
  215. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  216. f.l.Debug("Calculated gateway for ECMP not available, attempting other gateways",
  217. "destination", destinationAddr,
  218. "originalGateway", gatewayAddr,
  219. )
  220. }
  221. for i := range gateways {
  222. // Skip the gateway that failed previously
  223. if gateways[i].Addr() == gatewayAddr {
  224. continue
  225. }
  226. // We do not need the HandshakeHostInfo since we cache the packet in the originally chosen gateway
  227. if hostinfo, ready = f.handshakeManager.GetOrHandshake(gateways[i].Addr(), nil); ready {
  228. return hostinfo, true
  229. }
  230. }
  231. // No gateways reachable, cache the packet in the originally chosen gateway
  232. cacheCallback(handshakeInfoForChosenGateway)
  233. return hostinfo, false
  234. }
  235. }
  236. func (f *Interface) sendMessageNow(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p, nb, out []byte) {
  237. fp := &firewall.Packet{}
  238. err := newPacket(p, false, fp)
  239. if err != nil {
  240. f.l.Warn("error while parsing outgoing packet for firewall check", "error", err)
  241. return
  242. }
  243. // check if packet is in outbound fw rules
  244. dropReason := f.firewall.Drop(*fp, false, hostinfo, f.pki.GetCAPool(), nil)
  245. if dropReason != nil {
  246. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  247. f.l.Debug("dropping cached packet",
  248. "fwPacket", fp,
  249. "reason", dropReason,
  250. )
  251. }
  252. return
  253. }
  254. f.sendNoMetrics(header.Message, st, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, p, nb, out, 0)
  255. }
  256. // SendMessageToVpnAddr handles real addr:port lookup and sends to the current best known address for vpnAddr.
  257. // This function ignores myVpnNetworksTable, and will always attempt to treat the address as a vpnAddr
  258. func (f *Interface) SendMessageToVpnAddr(t header.MessageType, st header.MessageSubType, vpnAddr netip.Addr, p, nb, out []byte) {
  259. hostInfo, ready := f.handshakeManager.GetOrHandshake(vpnAddr, func(hh *HandshakeHostInfo) {
  260. hh.cachePacket(f.l, t, st, p, f.SendMessageToHostInfo, f.cachedPacketMetrics)
  261. })
  262. if hostInfo == nil {
  263. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  264. f.l.Debug("dropping SendMessageToVpnAddr, vpnAddr not in our vpn networks or in unsafe routes",
  265. "vpnAddr", vpnAddr,
  266. )
  267. }
  268. return
  269. }
  270. if !ready {
  271. return
  272. }
  273. f.SendMessageToHostInfo(t, st, hostInfo, p, nb, out)
  274. }
  275. func (f *Interface) SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hi *HostInfo, p, nb, out []byte) {
  276. f.send(t, st, hi.ConnectionState, hi, p, nb, out)
  277. }
  278. func (f *Interface) send(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, p, nb, out []byte) {
  279. f.messageMetrics.Tx(t, st, 1)
  280. f.sendNoMetrics(t, st, ci, hostinfo, netip.AddrPort{}, p, nb, out, 0)
  281. }
  282. func (f *Interface) sendTo(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte) {
  283. f.messageMetrics.Tx(t, st, 1)
  284. f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out, 0)
  285. }
  286. // SendVia sends a payload through a Relay tunnel. No authentication or encryption is done
  287. // to the payload for the ultimate target host, making this a useful method for sending
  288. // handshake messages to peers through relay tunnels.
  289. // via is the HostInfo through which the message is relayed.
  290. // ad is the plaintext data to authenticate, but not encrypt
  291. // nb is a buffer used to store the nonce value, re-used for performance reasons.
  292. // out is a buffer used to store the result of the Encrypt operation
  293. // q indicates which writer to use to send the packet.
  294. func (f *Interface) SendVia(via *HostInfo,
  295. relay *Relay,
  296. ad,
  297. nb,
  298. out []byte,
  299. nocopy bool,
  300. ) {
  301. if noiseutil.EncryptLockNeeded {
  302. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  303. via.ConnectionState.writeLock.Lock()
  304. }
  305. c := via.ConnectionState.messageCounter.Add(1)
  306. out = header.Encode(out, header.Version, header.Message, header.MessageRelay, relay.RemoteIndex, c)
  307. f.connectionManager.Out(via)
  308. // Authenticate the header and payload, but do not encrypt for this message type.
  309. // The payload consists of the inner, unencrypted Nebula header, as well as the end-to-end encrypted payload.
  310. if len(out)+len(ad)+via.ConnectionState.eKey.Overhead() > cap(out) {
  311. if noiseutil.EncryptLockNeeded {
  312. via.ConnectionState.writeLock.Unlock()
  313. }
  314. via.logger(f.l).Error("SendVia out buffer not large enough for relay",
  315. "outCap", cap(out),
  316. "payloadLen", len(ad),
  317. "headerLen", len(out),
  318. "cipherOverhead", via.ConnectionState.eKey.Overhead(),
  319. )
  320. return
  321. }
  322. // The header bytes are written to the 'out' slice; Grow the slice to hold the header and associated data payload.
  323. offset := len(out)
  324. out = out[:offset+len(ad)]
  325. // In one call path, the associated data _is_ already stored in out. In other call paths, the associated data must
  326. // be copied into 'out'.
  327. if !nocopy {
  328. copy(out[offset:], ad)
  329. }
  330. var err error
  331. out, err = via.ConnectionState.eKey.EncryptDanger(out, out, nil, c, nb)
  332. if noiseutil.EncryptLockNeeded {
  333. via.ConnectionState.writeLock.Unlock()
  334. }
  335. if err != nil {
  336. via.logger(f.l).Info("Failed to EncryptDanger in sendVia", "error", err)
  337. return
  338. }
  339. err = f.writers[0].WriteTo(out, via.remote)
  340. if err != nil {
  341. via.logger(f.l).Info("Failed to WriteTo in sendVia", "error", err)
  342. }
  343. f.connectionManager.RelayUsed(relay.LocalIndex)
  344. }
  345. func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte, q int) {
  346. if ci.eKey == nil {
  347. return
  348. }
  349. useRelay := !remote.IsValid() && !hostinfo.remote.IsValid()
  350. fullOut := out
  351. if useRelay {
  352. if len(out) < header.Len {
  353. // out always has a capacity of mtu, but not always a length greater than the header.Len.
  354. // Grow it to make sure the next operation works.
  355. out = out[:header.Len]
  356. }
  357. // Save a header's worth of data at the front of the 'out' buffer.
  358. out = out[header.Len:]
  359. }
  360. if noiseutil.EncryptLockNeeded {
  361. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  362. ci.writeLock.Lock()
  363. }
  364. c := ci.messageCounter.Add(1)
  365. //l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
  366. out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
  367. f.connectionManager.Out(hostinfo)
  368. // Query our LH if we haven't since the last time we've been rebound, this will cause the remote to punch against
  369. // all our addrs and enable a faster roaming.
  370. if t != header.CloseTunnel && hostinfo.lastRebindCount != f.rebindCount {
  371. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  372. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  373. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  374. hostinfo.lastRebindCount = f.rebindCount
  375. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  376. f.l.Debug("Lighthouse update triggered for punch due to rebind counter",
  377. "vpnAddrs", hostinfo.vpnAddrs,
  378. )
  379. }
  380. }
  381. var err error
  382. out, err = ci.eKey.EncryptDanger(out, out, p, c, nb)
  383. if noiseutil.EncryptLockNeeded {
  384. ci.writeLock.Unlock()
  385. }
  386. if err != nil {
  387. hostinfo.logger(f.l).Error("Failed to encrypt outgoing packet",
  388. "error", err,
  389. "udpAddr", remote,
  390. "counter", c,
  391. "attemptedCounter", c,
  392. )
  393. return
  394. }
  395. if remote.IsValid() {
  396. err = f.writers[q].WriteTo(out, remote)
  397. if err != nil {
  398. hostinfo.logger(f.l).Error("Failed to write outgoing packet",
  399. "error", err,
  400. "udpAddr", remote,
  401. )
  402. }
  403. } else if hostinfo.remote.IsValid() {
  404. err = f.writers[q].WriteTo(out, hostinfo.remote)
  405. if err != nil {
  406. hostinfo.logger(f.l).Error("Failed to write outgoing packet",
  407. "error", err,
  408. "udpAddr", remote,
  409. )
  410. }
  411. } else {
  412. // Try to send via a relay
  413. for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
  414. relayHostInfo, relay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relayIP)
  415. if err != nil {
  416. hostinfo.relayState.DeleteRelay(relayIP)
  417. hostinfo.logger(f.l).Info("sendNoMetrics failed to find HostInfo",
  418. "relay", relayIP,
  419. "error", err,
  420. )
  421. continue
  422. }
  423. f.SendVia(relayHostInfo, relay, out, nb, fullOut[:header.Len+len(out)], true)
  424. break
  425. }
  426. }
  427. }