inside.go 14 KB

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