inside.go 16 KB

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