inside.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. _, err := f.queues[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 && fwPacket.RemoteAddr.IsMulticast() {
  46. return
  47. }
  48. hostinfo, ready := f.getOrHandshakeConsiderRouting(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, 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", fwPacket.RemoteAddr,
  56. "fwPacket", fwPacket,
  57. )
  58. }
  59. return
  60. }
  61. if !ready {
  62. return
  63. }
  64. dropReason := f.firewall.Drop(*fwPacket, false, hostinfo, f.pki.GetCAPool(), localCache)
  65. if dropReason == nil {
  66. f.sendNoMetrics(header.Message, 0, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, packet, nb, out, q)
  67. } else {
  68. f.rejectInside(packet, out, q)
  69. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  70. hostinfo.logger(f.l).Debug("dropping outbound packet",
  71. "fwPacket", fwPacket,
  72. "reason", dropReason,
  73. )
  74. }
  75. }
  76. }
  77. func (f *Interface) rejectInside(packet []byte, out []byte, q int) {
  78. if !f.firewall.OutboundSendReject {
  79. return
  80. }
  81. out = iputil.CreateRejectPacket(packet, out)
  82. if len(out) == 0 {
  83. return
  84. }
  85. _, err := f.queues[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, nb, out []byte, q int) {
  91. if !f.firewall.InboundSendReject {
  92. return
  93. }
  94. out = iputil.CreateRejectPacket(packet, out)
  95. if len(out) == 0 {
  96. return
  97. }
  98. if len(out) > 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", out,
  103. )
  104. }
  105. return
  106. }
  107. f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, out, nb, packet, 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, nb, out []byte) {
  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, nb, out, 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, nb, out []byte) {
  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, nb, out)
  220. }
  221. func (f *Interface) SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hi *HostInfo, p, nb, out []byte) {
  222. f.send(t, st, hi.ConnectionState, hi, p, nb, out)
  223. }
  224. func (f *Interface) send(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, p, nb, out []byte) {
  225. f.messageMetrics.Tx(t, st, 1)
  226. f.sendNoMetrics(t, st, ci, hostinfo, netip.AddrPort{}, p, nb, out, 0)
  227. }
  228. func (f *Interface) sendTo(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte) {
  229. f.messageMetrics.Tx(t, st, 1)
  230. f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out, 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. // via is the HostInfo through which the message is relayed.
  236. // ad is the plaintext data to authenticate, but not encrypt
  237. // nb is a buffer used to store the nonce value, re-used for performance reasons.
  238. // out is a buffer used to store the result of the Encrypt operation
  239. // q indicates which writer to use to send the packet.
  240. func (f *Interface) SendVia(via *HostInfo,
  241. relay *Relay,
  242. ad,
  243. nb,
  244. out []byte,
  245. nocopy bool,
  246. ) {
  247. if noiseutil.EncryptLockNeeded {
  248. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  249. via.ConnectionState.writeLock.Lock()
  250. }
  251. c := via.ConnectionState.messageCounter.Add(1)
  252. out = header.Encode(out, header.Version, header.Message, header.MessageRelay, relay.RemoteIndex, c)
  253. f.connectionManager.Out(via)
  254. // Authenticate the header and payload, but do not encrypt for this message type.
  255. // The payload consists of the inner, unencrypted Nebula header, as well as the end-to-end encrypted payload.
  256. if len(out)+len(ad)+via.ConnectionState.eKey.Overhead() > cap(out) {
  257. if noiseutil.EncryptLockNeeded {
  258. via.ConnectionState.writeLock.Unlock()
  259. }
  260. via.logger(f.l).Error("SendVia out buffer not large enough for relay",
  261. "outCap", cap(out),
  262. "payloadLen", len(ad),
  263. "headerLen", len(out),
  264. "cipherOverhead", via.ConnectionState.eKey.Overhead(),
  265. )
  266. return
  267. }
  268. // The header bytes are written to the 'out' slice; Grow the slice to hold the header and associated data payload.
  269. offset := len(out)
  270. out = out[:offset+len(ad)]
  271. // In one call path, the associated data _is_ already stored in out. In other call paths, the associated data must
  272. // be copied into 'out'.
  273. if !nocopy {
  274. copy(out[offset:], ad)
  275. }
  276. var err error
  277. out, err = via.ConnectionState.eKey.EncryptDanger(out, out, nil, c, nb)
  278. if noiseutil.EncryptLockNeeded {
  279. via.ConnectionState.writeLock.Unlock()
  280. }
  281. if err != nil {
  282. via.logger(f.l).Info("Failed to EncryptDanger in sendVia", "error", err)
  283. return
  284. }
  285. err = f.writers[0].WriteTo(out, via.GetRemote())
  286. if err != nil {
  287. via.logger(f.l).Info("Failed to WriteTo in sendVia", "error", err)
  288. }
  289. f.connectionManager.RelayUsed(relay.LocalIndex)
  290. }
  291. func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte, q int) {
  292. if ci.eKey == nil {
  293. return
  294. }
  295. useRelay := !remote.IsValid() && !hostinfo.GetRemote().IsValid()
  296. fullOut := out
  297. if useRelay {
  298. if len(out) < header.Len {
  299. // out always has a capacity of mtu, but not always a length greater than the header.Len.
  300. // Grow it to make sure the next operation works.
  301. out = out[:header.Len]
  302. }
  303. // Save a header's worth of data at the front of the 'out' buffer.
  304. out = out[header.Len:]
  305. }
  306. if noiseutil.EncryptLockNeeded {
  307. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  308. ci.writeLock.Lock()
  309. }
  310. c := ci.messageCounter.Add(1)
  311. //l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
  312. out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
  313. f.connectionManager.Out(hostinfo)
  314. // Query our LH if we haven't since the last time we've been rebound, this will cause the remote to punch against
  315. // all our addrs and enable a faster roaming.
  316. if t != header.CloseTunnel && hostinfo.lastRebindCount != f.rebindCount {
  317. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  318. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  319. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  320. hostinfo.lastRebindCount = f.rebindCount
  321. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  322. f.l.Debug("Lighthouse update triggered for punch due to rebind counter",
  323. "vpnAddrs", hostinfo.vpnAddrs,
  324. )
  325. }
  326. }
  327. var err error
  328. out, err = ci.eKey.EncryptDanger(out, out, p, c, nb)
  329. if noiseutil.EncryptLockNeeded {
  330. ci.writeLock.Unlock()
  331. }
  332. if err != nil {
  333. hostinfo.logger(f.l).Error("Failed to encrypt outgoing packet",
  334. "error", err,
  335. "udpAddr", remote,
  336. "counter", c,
  337. )
  338. return
  339. }
  340. if remote.IsValid() {
  341. err = f.writers[q].WriteTo(out, remote)
  342. if err != nil {
  343. hostinfo.logger(f.l).Error("Failed to write outgoing packet",
  344. "error", err,
  345. "udpAddr", remote,
  346. )
  347. }
  348. } else if hr := hostinfo.GetRemote(); hr.IsValid() {
  349. err = f.writers[q].WriteTo(out, hr)
  350. if err != nil {
  351. hostinfo.logger(f.l).Error("Failed to write outgoing packet",
  352. "error", err,
  353. "udpAddr", remote,
  354. )
  355. }
  356. } else {
  357. // Try to send via a relay
  358. for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
  359. relayHostInfo, relay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relayIP)
  360. if err != nil {
  361. hostinfo.relayState.DeleteRelay(relayIP)
  362. hostinfo.logger(f.l).Info("sendNoMetrics failed to find HostInfo",
  363. "relay", relayIP,
  364. "error", err,
  365. )
  366. continue
  367. }
  368. f.SendVia(relayHostInfo, relay, out, nb, fullOut[:header.Len+len(out)], true)
  369. break
  370. }
  371. }
  372. }