inside.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. "github.com/slackhq/nebula/udp"
  12. )
  13. func (f *Interface) consumeInsidePacket(packet []byte, fwPacket *firewall.Packet, nb, out []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, 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, fwPacket)
  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, nil)
  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, nil)
  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, nil)
  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, nil)
  232. }
  233. // SendVia sends a payload through a Relay tunnel. No authentication or encryption is done
  234. // to the payload for the ultimate target host, making this a useful method for sending
  235. // handshake messages to peers through relay tunnels.
  236. // via is the HostInfo through which the message is relayed.
  237. // ad is the plaintext data to authenticate, but not encrypt
  238. // nb is a buffer used to store the nonce value, re-used for performance reasons.
  239. // out is a buffer used to store the result of the Encrypt operation
  240. // q indicates which writer to use to send the packet.
  241. func (f *Interface) SendVia(via *HostInfo,
  242. relay *Relay,
  243. ad,
  244. nb,
  245. out []byte,
  246. nocopy bool,
  247. ) {
  248. if noiseutil.EncryptLockNeeded {
  249. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  250. via.ConnectionState.writeLock.Lock()
  251. }
  252. c := via.ConnectionState.messageCounter.Add(1)
  253. out = header.Encode(out, header.Version, header.Message, header.MessageRelay, relay.RemoteIndex, c)
  254. f.connectionManager.Out(via)
  255. // Authenticate the header and payload, but do not encrypt for this message type.
  256. // The payload consists of the inner, unencrypted Nebula header, as well as the end-to-end encrypted payload.
  257. if len(out)+len(ad)+via.ConnectionState.eKey.Overhead() > cap(out) {
  258. if noiseutil.EncryptLockNeeded {
  259. via.ConnectionState.writeLock.Unlock()
  260. }
  261. via.logger(f.l).Error("SendVia out buffer not large enough for relay",
  262. "outCap", cap(out),
  263. "payloadLen", len(ad),
  264. "headerLen", len(out),
  265. "cipherOverhead", via.ConnectionState.eKey.Overhead(),
  266. )
  267. return
  268. }
  269. // The header bytes are written to the 'out' slice; Grow the slice to hold the header and associated data payload.
  270. offset := len(out)
  271. out = out[:offset+len(ad)]
  272. // In one call path, the associated data _is_ already stored in out. In other call paths, the associated data must
  273. // be copied into 'out'.
  274. if !nocopy {
  275. copy(out[offset:], ad)
  276. }
  277. var err error
  278. out, err = via.ConnectionState.eKey.EncryptDanger(out, out, nil, c, nb)
  279. if noiseutil.EncryptLockNeeded {
  280. via.ConnectionState.writeLock.Unlock()
  281. }
  282. if err != nil {
  283. via.logger(f.l).Info("Failed to EncryptDanger in sendVia", "error", err)
  284. return
  285. }
  286. err = f.writers[0].WriteTo(out, via.GetRemote())
  287. if err != nil {
  288. via.logger(f.l).Info("Failed to WriteTo in sendVia", "error", err)
  289. }
  290. f.connectionManager.RelayUsed(relay.LocalIndex)
  291. }
  292. func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte, q int, udpPortGetter udp.SendPortGetter) {
  293. if ci.eKey == nil {
  294. return
  295. }
  296. multiport := f.multiPort.Tx && hostinfo.multiportTx
  297. rawOut := out
  298. if multiport {
  299. if len(out) < udp.RawOverhead {
  300. // NOTE: This is because some spots in the code send us `out[:0]`, so
  301. // we need to expand the slice back out to get our 8 bytes back.
  302. out = out[:udp.RawOverhead]
  303. }
  304. // Preserve bytes needed for the raw socket
  305. out = out[udp.RawOverhead:]
  306. if udpPortGetter == nil {
  307. udpPortGetter = udp.RandomSendPort
  308. }
  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 := ci.messageCounter.Add(1)
  326. //l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
  327. out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
  328. f.connectionManager.Out(hostinfo)
  329. // Query our LH if we haven't since the last time we've been rebound, this will cause the remote to punch against
  330. // all our addrs and enable a faster roaming.
  331. if t != header.CloseTunnel && hostinfo.lastRebindCount != f.rebindCount {
  332. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  333. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  334. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  335. hostinfo.lastRebindCount = f.rebindCount
  336. if f.l.Enabled(context.Background(), slog.LevelDebug) {
  337. f.l.Debug("Lighthouse update triggered for punch due to rebind counter",
  338. "vpnAddrs", hostinfo.vpnAddrs,
  339. )
  340. }
  341. }
  342. var err error
  343. out, err = ci.eKey.EncryptDanger(out, out, p, c, nb)
  344. if noiseutil.EncryptLockNeeded {
  345. ci.writeLock.Unlock()
  346. }
  347. if err != nil {
  348. hostinfo.logger(f.l).Error("Failed to encrypt outgoing packet",
  349. "error", err,
  350. "udpAddr", remote,
  351. "counter", c,
  352. )
  353. return
  354. }
  355. if remote.IsValid() {
  356. if multiport {
  357. rawOut = rawOut[:len(out)+udp.RawOverhead]
  358. port := udpPortGetter.UDPSendPort(f.multiPort.TxPorts)
  359. err = f.udpRaw.WriteTo(rawOut, port, remote)
  360. } else {
  361. err = f.writers[q].WriteTo(out, remote)
  362. }
  363. if err != nil {
  364. hostinfo.logger(f.l).Error("Failed to write outgoing packet",
  365. "error", err,
  366. "udpAddr", remote,
  367. )
  368. }
  369. } else if hr := hostinfo.GetRemote(); hr.IsValid() {
  370. if multiport {
  371. rawOut = rawOut[:len(out)+udp.RawOverhead]
  372. port := udpPortGetter.UDPSendPort(f.multiPort.TxPorts)
  373. err = f.udpRaw.WriteTo(rawOut, port, hr)
  374. } else {
  375. err = f.writers[q].WriteTo(out, hr)
  376. }
  377. if err != nil {
  378. hostinfo.logger(f.l).Error("Failed to write outgoing packet",
  379. "error", err,
  380. "udpAddr", hr,
  381. )
  382. }
  383. } else {
  384. // Try to send via a relay
  385. for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
  386. relayHostInfo, relay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relayIP)
  387. if err != nil {
  388. hostinfo.relayState.DeleteRelay(relayIP)
  389. hostinfo.logger(f.l).Info("sendNoMetrics failed to find HostInfo",
  390. "relay", relayIP,
  391. "error", err,
  392. )
  393. continue
  394. }
  395. f.SendVia(relayHostInfo, relay, out, nb, fullOut[:header.Len+len(out)], true)
  396. break
  397. }
  398. }
  399. }