inside.go 15 KB

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