inside.go 15 KB

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