inside.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. package nebula
  2. import (
  3. "net/netip"
  4. "time"
  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/packet"
  11. "github.com/slackhq/nebula/routing"
  12. )
  13. func (f *Interface) consumeInsidePacket(packet []byte, fwPacket *firewall.Packet, nb []byte, out *packet.Packet, q int, localCache firewall.ConntrackCache, now time.Time) {
  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.Payload, q) //todo vector?
  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, now)
  62. if dropReason == nil {
  63. f.sendNoMetricsDelayed(header.Message, 0, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, packet, nb, out, q)
  64. } else {
  65. f.rejectInside(packet, out.Payload, q) //todo vector?
  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. This is a no-op if the tunnel is already established or being established
  107. // it does not check if it is within our vpn networks!
  108. func (f *Interface) Handshake(vpnAddr netip.Addr) {
  109. f.handshakeManager.GetOrHandshake(vpnAddr, nil)
  110. }
  111. // getOrHandshakeNoRouting returns nil if the vpnAddr is not routable.
  112. // If the 2nd return var is false then the hostinfo is not ready to be used in a tunnel
  113. func (f *Interface) getOrHandshakeNoRouting(vpnAddr netip.Addr, cacheCallback func(*HandshakeHostInfo)) (*HostInfo, bool) {
  114. if f.myVpnNetworksTable.Contains(vpnAddr) {
  115. return f.handshakeManager.GetOrHandshake(vpnAddr, cacheCallback)
  116. }
  117. return nil, false
  118. }
  119. // getOrHandshakeConsiderRouting will try to find the HostInfo to handle this packet, starting a handshake if necessary.
  120. // If the 2nd return var is false then the hostinfo is not ready to be used in a tunnel.
  121. func (f *Interface) getOrHandshakeConsiderRouting(fwPacket *firewall.Packet, cacheCallback func(*HandshakeHostInfo)) (*HostInfo, bool) {
  122. destinationAddr := fwPacket.RemoteAddr
  123. hostinfo, ready := f.getOrHandshakeNoRouting(destinationAddr, cacheCallback)
  124. // Host is inside the mesh, no routing required
  125. if hostinfo != nil {
  126. return hostinfo, ready
  127. }
  128. gateways := f.inside.RoutesFor(destinationAddr)
  129. switch len(gateways) {
  130. case 0:
  131. return nil, false
  132. case 1:
  133. // Single gateway route
  134. return f.handshakeManager.GetOrHandshake(gateways[0].Addr(), cacheCallback)
  135. default:
  136. // Multi gateway route, perform ECMP categorization
  137. gatewayAddr, balancingOk := routing.BalancePacket(fwPacket, gateways)
  138. if !balancingOk {
  139. // This happens if the gateway buckets were not calculated, this _should_ never happen
  140. f.l.Error("Gateway buckets not calculated, fallback from ECMP to random routing. Please report this bug.")
  141. }
  142. var handshakeInfoForChosenGateway *HandshakeHostInfo
  143. var hhReceiver = func(hh *HandshakeHostInfo) {
  144. handshakeInfoForChosenGateway = hh
  145. }
  146. // Store the handshakeHostInfo for later.
  147. // If this node is not reachable we will attempt other nodes, if none are reachable we will
  148. // cache the packet for this gateway.
  149. if hostinfo, ready = f.handshakeManager.GetOrHandshake(gatewayAddr, hhReceiver); ready {
  150. return hostinfo, true
  151. }
  152. // It appears the selected gateway cannot be reached, find another gateway to fallback on.
  153. // The current implementation breaks ECMP but that seems better than no connectivity.
  154. // If ECMP is also required when a gateway is down then connectivity status
  155. // for each gateway needs to be kept and the weights recalculated when they go up or down.
  156. // This would also need to interact with unsafe_route updates through reloading the config or
  157. // use of the use_system_route_table option
  158. if f.l.Level >= logrus.DebugLevel {
  159. f.l.WithField("destination", destinationAddr).
  160. WithField("originalGateway", gatewayAddr).
  161. Debugln("Calculated gateway for ECMP not available, attempting other gateways")
  162. }
  163. for i := range gateways {
  164. // Skip the gateway that failed previously
  165. if gateways[i].Addr() == gatewayAddr {
  166. continue
  167. }
  168. // We do not need the HandshakeHostInfo since we cache the packet in the originally chosen gateway
  169. if hostinfo, ready = f.handshakeManager.GetOrHandshake(gateways[i].Addr(), nil); ready {
  170. return hostinfo, true
  171. }
  172. }
  173. // No gateways reachable, cache the packet in the originally chosen gateway
  174. cacheCallback(handshakeInfoForChosenGateway)
  175. return hostinfo, false
  176. }
  177. }
  178. func (f *Interface) sendMessageNow(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p, nb, out []byte) {
  179. fp := &firewall.Packet{}
  180. err := newPacket(p, false, fp)
  181. if err != nil {
  182. f.l.Warnf("error while parsing outgoing packet for firewall check; %v", err)
  183. return
  184. }
  185. // check if packet is in outbound fw rules
  186. dropReason := f.firewall.Drop(*fp, false, hostinfo, f.pki.GetCAPool(), nil, time.Now())
  187. if dropReason != nil {
  188. if f.l.Level >= logrus.DebugLevel {
  189. f.l.WithField("fwPacket", fp).
  190. WithField("reason", dropReason).
  191. Debugln("dropping cached packet")
  192. }
  193. return
  194. }
  195. f.sendNoMetrics(header.Message, st, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, p, nb, out, 0)
  196. }
  197. // SendMessageToVpnAddr handles real addr:port lookup and sends to the current best known address for vpnAddr.
  198. // This function ignores myVpnNetworksTable, and will always attempt to treat the address as a vpnAddr
  199. func (f *Interface) SendMessageToVpnAddr(t header.MessageType, st header.MessageSubType, vpnAddr netip.Addr, p, nb, out []byte) {
  200. hostInfo, ready := f.handshakeManager.GetOrHandshake(vpnAddr, func(hh *HandshakeHostInfo) {
  201. hh.cachePacket(f.l, t, st, p, f.SendMessageToHostInfo, f.cachedPacketMetrics)
  202. })
  203. if hostInfo == nil {
  204. if f.l.Level >= logrus.DebugLevel {
  205. f.l.WithField("vpnAddr", vpnAddr).
  206. Debugln("dropping SendMessageToVpnAddr, vpnAddr not in our vpn networks or in unsafe routes")
  207. }
  208. return
  209. }
  210. if !ready {
  211. return
  212. }
  213. f.SendMessageToHostInfo(t, st, hostInfo, p, nb, out)
  214. }
  215. func (f *Interface) SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hi *HostInfo, p, nb, out []byte) {
  216. f.send(t, st, hi.ConnectionState, hi, p, nb, out)
  217. }
  218. func (f *Interface) send(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, p, nb, out []byte) {
  219. f.messageMetrics.Tx(t, st, 1)
  220. f.sendNoMetrics(t, st, ci, hostinfo, netip.AddrPort{}, p, nb, out, 0)
  221. }
  222. func (f *Interface) sendTo(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte) {
  223. f.messageMetrics.Tx(t, st, 1)
  224. f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out, 0)
  225. }
  226. // SendVia sends a payload through a Relay tunnel. No authentication or encryption is done
  227. // to the payload for the ultimate target host, making this a useful method for sending
  228. // handshake messages to peers through relay tunnels.
  229. // via is the HostInfo through which the message is relayed.
  230. // ad is the plaintext data to authenticate, but not encrypt
  231. // nb is a buffer used to store the nonce value, re-used for performance reasons.
  232. // out is a buffer used to store the result of the Encrypt operation
  233. // q indicates which writer to use to send the packet.
  234. func (f *Interface) SendVia(via *HostInfo,
  235. relay *Relay,
  236. ad,
  237. nb,
  238. out []byte,
  239. nocopy bool,
  240. ) {
  241. if noiseutil.EncryptLockNeeded {
  242. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  243. via.ConnectionState.writeLock.Lock()
  244. }
  245. c := via.ConnectionState.messageCounter.Add(1)
  246. out = header.Encode(out, header.Version, header.Message, header.MessageRelay, relay.RemoteIndex, c)
  247. f.connectionManager.Out(via)
  248. // Authenticate the header and payload, but do not encrypt for this message type.
  249. // The payload consists of the inner, unencrypted Nebula header, as well as the end-to-end encrypted payload.
  250. if len(out)+len(ad)+via.ConnectionState.eKey.Overhead() > cap(out) {
  251. if noiseutil.EncryptLockNeeded {
  252. via.ConnectionState.writeLock.Unlock()
  253. }
  254. via.logger(f.l).
  255. WithField("outCap", cap(out)).
  256. WithField("payloadLen", len(ad)).
  257. WithField("headerLen", len(out)).
  258. WithField("cipherOverhead", via.ConnectionState.eKey.Overhead()).
  259. Error("SendVia out buffer not large enough for relay")
  260. return
  261. }
  262. // The header bytes are written to the 'out' slice; Grow the slice to hold the header and associated data payload.
  263. offset := len(out)
  264. out = out[:offset+len(ad)]
  265. // In one call path, the associated data _is_ already stored in out. In other call paths, the associated data must
  266. // be copied into 'out'.
  267. if !nocopy {
  268. copy(out[offset:], ad)
  269. }
  270. var err error
  271. out, err = via.ConnectionState.eKey.EncryptDanger(out, out, nil, c, nb)
  272. if noiseutil.EncryptLockNeeded {
  273. via.ConnectionState.writeLock.Unlock()
  274. }
  275. if err != nil {
  276. via.logger(f.l).WithError(err).Info("Failed to EncryptDanger in sendVia")
  277. return
  278. }
  279. err = f.writers[0].WriteTo(out, via.remote)
  280. if err != nil {
  281. via.logger(f.l).WithError(err).Info("Failed to WriteTo in sendVia")
  282. }
  283. f.connectionManager.RelayUsed(relay.LocalIndex)
  284. }
  285. func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte, q int) {
  286. if ci.eKey == nil {
  287. return
  288. }
  289. useRelay := !remote.IsValid() && !hostinfo.remote.IsValid()
  290. fullOut := out
  291. if useRelay {
  292. if len(out) < header.Len {
  293. // out always has a capacity of mtu, but not always a length greater than the header.Len.
  294. // Grow it to make sure the next operation works.
  295. out = out[:header.Len]
  296. }
  297. // Save a header's worth of data at the front of the 'out' buffer.
  298. out = out[header.Len:]
  299. }
  300. if noiseutil.EncryptLockNeeded {
  301. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  302. ci.writeLock.Lock()
  303. }
  304. c := ci.messageCounter.Add(1)
  305. //l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
  306. out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
  307. f.connectionManager.Out(hostinfo)
  308. // Query our LH if we haven't since the last time we've been rebound, this will cause the remote to punch against
  309. // all our addrs and enable a faster roaming.
  310. if t != header.CloseTunnel && hostinfo.lastRebindCount != f.rebindCount {
  311. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  312. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  313. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  314. hostinfo.lastRebindCount = f.rebindCount
  315. if f.l.Level >= logrus.DebugLevel {
  316. f.l.WithField("vpnAddrs", hostinfo.vpnAddrs).Debug("Lighthouse update triggered for punch due to rebind counter")
  317. }
  318. }
  319. var err error
  320. out, err = ci.eKey.EncryptDanger(out, out, p, c, nb)
  321. if noiseutil.EncryptLockNeeded {
  322. ci.writeLock.Unlock()
  323. }
  324. if err != nil {
  325. hostinfo.logger(f.l).WithError(err).
  326. WithField("udpAddr", remote).WithField("counter", c).
  327. WithField("attemptedCounter", c).
  328. Error("Failed to encrypt outgoing packet")
  329. return
  330. }
  331. if remote.IsValid() {
  332. err = f.writers[q].WriteTo(out, remote)
  333. if err != nil {
  334. hostinfo.logger(f.l).WithError(err).
  335. WithField("udpAddr", remote).Error("Failed to write outgoing packet")
  336. }
  337. } else if hostinfo.remote.IsValid() {
  338. err = f.writers[q].WriteTo(out, hostinfo.remote)
  339. if err != nil {
  340. hostinfo.logger(f.l).WithError(err).
  341. WithField("udpAddr", remote).Error("Failed to write outgoing packet")
  342. }
  343. } else {
  344. // Try to send via a relay
  345. for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
  346. relayHostInfo, relay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relayIP)
  347. if err != nil {
  348. hostinfo.relayState.DeleteRelay(relayIP)
  349. hostinfo.logger(f.l).WithField("relay", relayIP).WithError(err).Info("sendNoMetrics failed to find HostInfo")
  350. continue
  351. }
  352. f.SendVia(relayHostInfo, relay, out, nb, fullOut[:header.Len+len(out)], true)
  353. break
  354. }
  355. }
  356. }
  357. func (f *Interface) sendNoMetricsDelayed(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb []byte, out *packet.Packet, q int) {
  358. if ci.eKey == nil {
  359. return
  360. }
  361. useRelay := !remote.IsValid() && !hostinfo.remote.IsValid()
  362. fullOut := out.Payload
  363. if useRelay {
  364. if len(out.Payload) < header.Len {
  365. // out always has a capacity of mtu, but not always a length greater than the header.Len.
  366. // Grow it to make sure the next operation works.
  367. out.Payload = out.Payload[:header.Len]
  368. }
  369. // Save a header's worth of data at the front of the 'out' buffer.
  370. out.Payload = out.Payload[header.Len:]
  371. }
  372. if noiseutil.EncryptLockNeeded {
  373. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  374. ci.writeLock.Lock()
  375. }
  376. c := ci.messageCounter.Add(1)
  377. //l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
  378. out.Payload = header.Encode(out.Payload, header.Version, t, st, hostinfo.remoteIndexId, c)
  379. f.connectionManager.Out(hostinfo)
  380. // Query our LH if we haven't since the last time we've been rebound, this will cause the remote to punch against
  381. // all our addrs and enable a faster roaming.
  382. if t != header.CloseTunnel && hostinfo.lastRebindCount != f.rebindCount {
  383. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  384. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  385. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  386. hostinfo.lastRebindCount = f.rebindCount
  387. if f.l.Level >= logrus.DebugLevel {
  388. f.l.WithField("vpnAddrs", hostinfo.vpnAddrs).Debug("Lighthouse update triggered for punch due to rebind counter")
  389. }
  390. }
  391. var err error
  392. out.Payload, err = ci.eKey.EncryptDanger(out.Payload, out.Payload, p, c, nb)
  393. if noiseutil.EncryptLockNeeded {
  394. ci.writeLock.Unlock()
  395. }
  396. if err != nil {
  397. hostinfo.logger(f.l).WithError(err).
  398. WithField("udpAddr", remote).WithField("counter", c).
  399. WithField("attemptedCounter", c).
  400. Error("Failed to encrypt outgoing packet")
  401. return
  402. }
  403. if remote.IsValid() {
  404. err = f.writers[q].Prep(out, remote)
  405. if err != nil {
  406. hostinfo.logger(f.l).WithError(err).WithField("udpAddr", remote).Error("Failed to write outgoing packet")
  407. }
  408. } else if hostinfo.remote.IsValid() {
  409. err = f.writers[q].Prep(out, hostinfo.remote)
  410. if err != nil {
  411. hostinfo.logger(f.l).WithError(err).WithField("udpAddr", remote).Error("Failed to write outgoing packet")
  412. }
  413. } else {
  414. // Try to send via a relay
  415. for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
  416. relayHostInfo, relay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relayIP)
  417. if err != nil {
  418. hostinfo.relayState.DeleteRelay(relayIP)
  419. hostinfo.logger(f.l).WithField("relay", relayIP).WithError(err).Info("sendNoMetrics failed to find HostInfo")
  420. continue
  421. }
  422. //todo vector!!
  423. f.SendVia(relayHostInfo, relay, out.Payload, nb, fullOut[:header.Len+len(out.Payload)], true)
  424. break
  425. }
  426. }
  427. }