inside.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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/routing"
  10. )
  11. func (f *Interface) consumeInsidePacket(buf *WireBuffer, q int, localCache firewall.ConntrackCache) {
  12. packet := buf.IPPacket()
  13. err := newPacket(packet, false, buf.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(buf.FwPacket.RemoteAddr) {
  26. return
  27. }
  28. }
  29. if f.myVpnAddrsTable.Contains(buf.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. _, err := f.readers[q].Write(packet)
  36. if err != nil {
  37. f.l.Error("Failed to forward to tun", "error", err)
  38. }
  39. }
  40. // Otherwise, drop. On linux, we should never see these packets - Linux
  41. // routes packets from the nebula addr to the nebula addr through the loopback device.
  42. return
  43. }
  44. // Ignore multicast packets
  45. if f.dropMulticast && buf.FwPacket.RemoteAddr.IsMulticast() {
  46. return
  47. }
  48. hostinfo, ready := f.getOrHandshakeConsiderRouting(buf.FwPacket, func(hh *HandshakeHostInfo) {
  49. hh.cachePacket(f.l, header.Message, 0, packet, f.sendMessageNow, f.cachedPacketMetrics)
  50. })
  51. if hostinfo == nil {
  52. f.rejectInside(packet, buf.Out, q)
  53. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  54. f.l.Debug("dropping outbound packet, vpnAddr not in our vpn networks or in unsafe networks",
  55. "vpnAddr", buf.FwPacket.RemoteAddr,
  56. "fwPacket", buf.FwPacket,
  57. )
  58. }
  59. return
  60. }
  61. if !ready {
  62. return
  63. }
  64. dropReason := f.firewall.Drop(*buf.FwPacket, false, hostinfo, f.pki.GetCAPool(), localCache)
  65. if dropReason == nil {
  66. f.sendNoMetrics(header.Message, 0, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, packet, buf, q)
  67. } else {
  68. f.rejectInside(packet, buf.Out, q)
  69. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  70. hostinfo.logger(f.l).Debug("dropping outbound packet",
  71. "fwPacket", buf.FwPacket,
  72. "reason", dropReason,
  73. )
  74. }
  75. }
  76. }
  77. func (f *Interface) rejectInside(packet []byte, out []byte, q int) {
  78. if !f.firewall.InSendReject {
  79. return
  80. }
  81. out = iputil.CreateRejectPacket(packet, out)
  82. if len(out) == 0 {
  83. return
  84. }
  85. _, err := f.readers[q].Write(out)
  86. if err != nil {
  87. f.l.Error("Failed to write to tun", "error", err)
  88. }
  89. }
  90. func (f *Interface) rejectOutside(packet []byte, ci *ConnectionState, hostinfo *HostInfo, scratch []byte, buf *WireBuffer, q int) {
  91. if !f.firewall.OutSendReject {
  92. return
  93. }
  94. rejectIP := iputil.CreateRejectPacket(packet, scratch)
  95. if len(rejectIP) == 0 {
  96. return
  97. }
  98. if len(rejectIP) > iputil.MaxRejectPacketSize {
  99. if f.l.Enabled(context.Background(), slog.LevelInfo) {
  100. f.l.Info("rejectOutside: packet too big, not sending",
  101. "packet", packet,
  102. "outPacket", rejectIP,
  103. )
  104. }
  105. return
  106. }
  107. f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, rejectIP, buf, q)
  108. }
  109. // 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
  110. // it does not check if it is within our vpn networks!
  111. func (f *Interface) Handshake(vpnAddr netip.Addr) {
  112. f.handshakeManager.GetOrHandshake(vpnAddr, nil)
  113. }
  114. // getOrHandshakeNoRouting returns nil if the vpnAddr is not routable.
  115. // If the 2nd return var is false then the hostinfo is not ready to be used in a tunnel
  116. func (f *Interface) getOrHandshakeNoRouting(vpnAddr netip.Addr, cacheCallback func(*HandshakeHostInfo)) (*HostInfo, bool) {
  117. if f.myVpnNetworksTable.Contains(vpnAddr) {
  118. return f.handshakeManager.GetOrHandshake(vpnAddr, cacheCallback)
  119. }
  120. return nil, false
  121. }
  122. // getOrHandshakeConsiderRouting will try to find the HostInfo to handle this packet, starting a handshake if necessary.
  123. // If the 2nd return var is false then the hostinfo is not ready to be used in a tunnel.
  124. func (f *Interface) getOrHandshakeConsiderRouting(fwPacket *firewall.Packet, cacheCallback func(*HandshakeHostInfo)) (*HostInfo, bool) {
  125. destinationAddr := fwPacket.RemoteAddr
  126. hostinfo, ready := f.getOrHandshakeNoRouting(destinationAddr, cacheCallback)
  127. // Host is inside the mesh, no routing required
  128. if hostinfo != nil {
  129. return hostinfo, ready
  130. }
  131. gateways := f.inside.RoutesFor(destinationAddr)
  132. switch len(gateways) {
  133. case 0:
  134. return nil, false
  135. case 1:
  136. // Single gateway route
  137. return f.handshakeManager.GetOrHandshake(gateways[0].Addr(), cacheCallback)
  138. default:
  139. // Multi gateway route, perform ECMP categorization
  140. gatewayAddr, balancingOk := routing.BalancePacket(fwPacket, gateways)
  141. if !balancingOk {
  142. // This happens if the gateway buckets were not calculated, this _should_ never happen
  143. f.l.Error("Gateway buckets not calculated, fallback from ECMP to random routing. Please report this bug.")
  144. }
  145. var handshakeInfoForChosenGateway *HandshakeHostInfo
  146. var hhReceiver = func(hh *HandshakeHostInfo) {
  147. handshakeInfoForChosenGateway = hh
  148. }
  149. // Store the handshakeHostInfo for later.
  150. // If this node is not reachable we will attempt other nodes, if none are reachable we will
  151. // cache the packet for this gateway.
  152. if hostinfo, ready = f.handshakeManager.GetOrHandshake(gatewayAddr, hhReceiver); ready {
  153. return hostinfo, true
  154. }
  155. // It appears the selected gateway cannot be reached, find another gateway to fallback on.
  156. // The current implementation breaks ECMP but that seems better than no connectivity.
  157. // If ECMP is also required when a gateway is down then connectivity status
  158. // for each gateway needs to be kept and the weights recalculated when they go up or down.
  159. // This would also need to interact with unsafe_route updates through reloading the config or
  160. // use of the use_system_route_table option
  161. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  162. f.l.Debug("Calculated gateway for ECMP not available, attempting other gateways",
  163. "destination", destinationAddr,
  164. "originalGateway", gatewayAddr,
  165. )
  166. }
  167. for i := range gateways {
  168. // Skip the gateway that failed previously
  169. if gateways[i].Addr() == gatewayAddr {
  170. continue
  171. }
  172. // We do not need the HandshakeHostInfo since we cache the packet in the originally chosen gateway
  173. if hostinfo, ready = f.handshakeManager.GetOrHandshake(gateways[i].Addr(), nil); ready {
  174. return hostinfo, true
  175. }
  176. }
  177. // No gateways reachable, cache the packet in the originally chosen gateway
  178. cacheCallback(handshakeInfoForChosenGateway)
  179. return hostinfo, false
  180. }
  181. }
  182. func (f *Interface) sendMessageNow(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p []byte, buf *WireBuffer) {
  183. fp := &firewall.Packet{}
  184. err := newPacket(p, false, fp)
  185. if err != nil {
  186. f.l.Warn("error while parsing outgoing packet for firewall check", "error", err)
  187. return
  188. }
  189. // check if packet is in outbound fw rules
  190. dropReason := f.firewall.Drop(*fp, false, hostinfo, f.pki.GetCAPool(), nil)
  191. if dropReason != nil {
  192. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  193. f.l.Debug("dropping cached packet",
  194. "fwPacket", fp,
  195. "reason", dropReason,
  196. )
  197. }
  198. return
  199. }
  200. f.sendNoMetrics(header.Message, st, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, p, buf, 0)
  201. }
  202. // SendMessageToVpnAddr handles real addr:port lookup and sends to the current best known address for vpnAddr.
  203. // This function ignores myVpnNetworksTable, and will always attempt to treat the address as a vpnAddr
  204. func (f *Interface) SendMessageToVpnAddr(t header.MessageType, st header.MessageSubType, vpnAddr netip.Addr, p []byte, buf *WireBuffer) {
  205. hostInfo, ready := f.handshakeManager.GetOrHandshake(vpnAddr, func(hh *HandshakeHostInfo) {
  206. hh.cachePacket(f.l, t, st, p, f.SendMessageToHostInfo, f.cachedPacketMetrics)
  207. })
  208. if hostInfo == nil {
  209. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  210. f.l.Debug("dropping SendMessageToVpnAddr, vpnAddr not in our vpn networks or in unsafe routes",
  211. "vpnAddr", vpnAddr,
  212. )
  213. }
  214. return
  215. }
  216. if !ready {
  217. return
  218. }
  219. f.SendMessageToHostInfo(t, st, hostInfo, p, buf)
  220. }
  221. func (f *Interface) SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hi *HostInfo, p []byte, buf *WireBuffer) {
  222. f.send(t, st, hi.ConnectionState, hi, p, buf)
  223. }
  224. func (f *Interface) send(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, p []byte, buf *WireBuffer) {
  225. f.messageMetrics.Tx(t, st, 1)
  226. f.sendNoMetrics(t, st, ci, hostinfo, netip.AddrPort{}, p, buf, 0)
  227. }
  228. func (f *Interface) sendTo(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p []byte, buf *WireBuffer) {
  229. f.messageMetrics.Tx(t, st, 1)
  230. f.sendNoMetrics(t, st, ci, hostinfo, remote, p, buf, 0)
  231. }
  232. // SendVia sends a payload through a Relay tunnel. No authentication or encryption is done
  233. // to the payload for the ultimate target host, making this a useful method for sending
  234. // handshake messages to peers through relay tunnels.
  235. //
  236. // via is the HostInfo through which the message is relayed. ad is staged into
  237. // the inner-payload slot of buf and then AAD-only sealed under via's key by
  238. // SealRelayInPlace. The sendNoMetrics relay-forward path skips this entry
  239. // point and calls sendViaInPlace directly because its inner ciphertext is
  240. // already in place from the encrypt step.
  241. func (f *Interface) SendVia(via *HostInfo, relay *Relay, ad []byte, buf *WireBuffer) {
  242. if header.Len+len(ad)+via.ConnectionState.eKey.Overhead() > cap(buf.Out) {
  243. via.logger(f.l).Error("SendVia out buffer not large enough for relay",
  244. "outCap", cap(buf.Out),
  245. "payloadLen", len(ad),
  246. "headerLen", header.Len,
  247. "cipherOverhead", via.ConnectionState.eKey.Overhead(),
  248. )
  249. return
  250. }
  251. buf.StageRelayInner(ad)
  252. f.sendViaInPlace(via, relay, len(ad), buf)
  253. }
  254. // sendViaInPlace stamps the outer relay header, AAD-seals over the [outer
  255. // header | inner-already-staged] region, and writes the result to via.remote.
  256. // Called from SendVia (after staging ad) and from sendNoMetrics' relay-forward
  257. // path (where the inner ciphertext is already in place from SealForRelay).
  258. func (f *Interface) sendViaInPlace(via *HostInfo, relay *Relay, innerLen int, buf *WireBuffer) {
  259. f.connectionManager.Out(via)
  260. out, err := buf.SealRelayInPlace(via.ConnectionState, relay.RemoteIndex, innerLen)
  261. if err != nil {
  262. via.logger(f.l).Info("Failed to EncryptDanger in sendVia", "error", err)
  263. return
  264. }
  265. if err := f.writers[0].WriteTo(out, via.remote); err != nil {
  266. via.logger(f.l).Info("Failed to WriteTo in sendVia", "error", err)
  267. }
  268. f.connectionManager.RelayUsed(relay.LocalIndex)
  269. }
  270. // sendNoMetrics encrypts and writes one outbound nebula packet (data, control,
  271. // lighthouse, etc) using buf as the per-call wire scratch. When the hostinfo
  272. // has no direct remote we encrypt into the relay-reserved slot via
  273. // SealForRelay so sendViaInPlace can wrap it without an extra copy.
  274. func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p []byte, buf *WireBuffer, q int) {
  275. if ci.eKey == nil {
  276. return
  277. }
  278. useRelay := !remote.IsValid() && !hostinfo.remote.IsValid()
  279. f.connectionManager.Out(hostinfo)
  280. // Query our LH if we haven't since the last time we've been rebound, this will cause the remote to punch against
  281. // all our addrs and enable a faster roaming.
  282. if t != header.CloseTunnel && hostinfo.lastRebindCount != f.rebindCount {
  283. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  284. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  285. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  286. hostinfo.lastRebindCount = f.rebindCount
  287. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  288. f.l.Debug("Lighthouse update triggered for punch due to rebind counter",
  289. "vpnAddrs", hostinfo.vpnAddrs,
  290. )
  291. }
  292. }
  293. var out []byte
  294. var err error
  295. if useRelay {
  296. out, err = buf.SealForRelay(ci, t, st, hostinfo.remoteIndexId, p)
  297. } else {
  298. out, err = buf.Seal(ci, t, st, hostinfo.remoteIndexId, p)
  299. }
  300. if err != nil {
  301. hostinfo.logger(f.l).Error("Failed to encrypt outgoing packet",
  302. "error", err,
  303. "udpAddr", remote,
  304. )
  305. return
  306. }
  307. switch {
  308. case remote.IsValid():
  309. if err := f.writers[q].WriteTo(out, remote); err != nil {
  310. hostinfo.logger(f.l).Error("Failed to write outgoing packet", "error", err, "udpAddr", remote)
  311. }
  312. case hostinfo.remote.IsValid():
  313. if err := f.writers[q].WriteTo(out, hostinfo.remote); err != nil {
  314. hostinfo.logger(f.l).Error("Failed to write outgoing packet", "error", err, "udpAddr", hostinfo.remote)
  315. }
  316. default:
  317. // SealForRelay placed the inner ciphertext at buf.Out[header.Len:],
  318. // so sendViaInPlace can wrap it with the outer relay header without
  319. // an extra copy.
  320. for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
  321. relayHostInfo, relay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relayIP)
  322. if err != nil {
  323. hostinfo.relayState.DeleteRelay(relayIP)
  324. hostinfo.logger(f.l).Info("sendNoMetrics failed to find HostInfo", "relay", relayIP, "error", err)
  325. continue
  326. }
  327. f.sendViaInPlace(relayHostInfo, relay, len(out), buf)
  328. break
  329. }
  330. }
  331. }