inside.go 15 KB

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