inside.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. "github.com/slackhq/nebula/udp"
  11. )
  12. func (f *Interface) consumeInsidePacket(packet []byte, fwPacket *firewall.Packet, nb, out []byte, q int, localCache firewall.ConntrackCache) {
  13. err := newPacket(packet, false, fwPacket)
  14. if err != nil {
  15. if f.l.Level >= logrus.DebugLevel {
  16. f.l.WithField("packet", packet).Debugf("Error while validating outbound packet: %s", err)
  17. }
  18. return
  19. }
  20. // Ignore local broadcast packets
  21. if f.dropLocalBroadcast {
  22. if f.myBroadcastAddrsTable.Contains(fwPacket.RemoteAddr) {
  23. return
  24. }
  25. }
  26. if f.myVpnAddrsTable.Contains(fwPacket.RemoteAddr) {
  27. // Immediately forward packets from self to self.
  28. // This should only happen on Darwin-based and FreeBSD hosts, which
  29. // routes packets from the Nebula addr to the Nebula addr through the Nebula
  30. // TUN device.
  31. if immediatelyForwardToSelf {
  32. _, err := f.readers[q].Write(packet)
  33. if err != nil {
  34. f.l.WithError(err).Error("Failed to forward to tun")
  35. }
  36. }
  37. // Otherwise, drop. On linux, we should never see these packets - Linux
  38. // routes packets from the nebula addr to the nebula addr through the loopback device.
  39. return
  40. }
  41. // Ignore multicast packets
  42. if f.dropMulticast && fwPacket.RemoteAddr.IsMulticast() {
  43. return
  44. }
  45. hostinfo, ready := f.getOrHandshakeConsiderRouting(fwPacket, func(hh *HandshakeHostInfo) {
  46. hh.cachePacket(f.l, header.Message, 0, packet, f.sendMessageNow, f.cachedPacketMetrics)
  47. })
  48. if hostinfo == nil {
  49. f.rejectInside(packet, out, q)
  50. if f.l.Level >= logrus.DebugLevel {
  51. f.l.WithField("vpnAddr", fwPacket.RemoteAddr).
  52. WithField("fwPacket", fwPacket).
  53. Debugln("dropping outbound packet, vpnAddr not in our vpn networks or in unsafe networks")
  54. }
  55. return
  56. }
  57. if !ready {
  58. return
  59. }
  60. dropReason := f.firewall.Drop(*fwPacket, false, hostinfo, f.pki.GetCAPool(), localCache)
  61. if dropReason == nil {
  62. f.sendNoMetrics(header.Message, 0, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, packet, nb, out, q, fwPacket)
  63. } else {
  64. f.rejectInside(packet, out, q)
  65. if f.l.Level >= logrus.DebugLevel {
  66. hostinfo.logger(f.l).
  67. WithField("fwPacket", fwPacket).
  68. WithField("reason", dropReason).
  69. Debugln("dropping outbound packet")
  70. }
  71. }
  72. }
  73. func (f *Interface) rejectInside(packet []byte, out []byte, q int) {
  74. if !f.firewall.InSendReject {
  75. return
  76. }
  77. out = iputil.CreateRejectPacket(packet, out)
  78. if len(out) == 0 {
  79. return
  80. }
  81. _, err := f.readers[q].Write(out)
  82. if err != nil {
  83. f.l.WithError(err).Error("Failed to write to tun")
  84. }
  85. }
  86. func (f *Interface) rejectOutside(packet []byte, ci *ConnectionState, hostinfo *HostInfo, nb, out []byte, q int) {
  87. if !f.firewall.OutSendReject {
  88. return
  89. }
  90. out = iputil.CreateRejectPacket(packet, out)
  91. if len(out) == 0 {
  92. return
  93. }
  94. if len(out) > iputil.MaxRejectPacketSize {
  95. if f.l.GetLevel() >= logrus.InfoLevel {
  96. f.l.
  97. WithField("packet", packet).
  98. WithField("outPacket", out).
  99. Info("rejectOutside: packet too big, not sending")
  100. }
  101. return
  102. }
  103. f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, out, nb, packet, q, nil)
  104. }
  105. // 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
  106. func (f *Interface) Handshake(vpnAddr netip.Addr) {
  107. f.getOrHandshakeNoRouting(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. err := newPacket(p, false, fp)
  179. if err != nil {
  180. f.l.Warnf("error while parsing outgoing packet for firewall check; %v", err)
  181. return
  182. }
  183. // check if packet is in outbound fw rules
  184. dropReason := f.firewall.Drop(*fp, false, hostinfo, f.pki.GetCAPool(), nil)
  185. if dropReason != nil {
  186. if f.l.Level >= logrus.DebugLevel {
  187. f.l.WithField("fwPacket", fp).
  188. WithField("reason", dropReason).
  189. Debugln("dropping cached packet")
  190. }
  191. return
  192. }
  193. f.sendNoMetrics(header.Message, st, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, p, nb, out, 0, nil)
  194. }
  195. // SendMessageToVpnAddr handles real addr:port lookup and sends to the current best known address for vpnAddr
  196. func (f *Interface) SendMessageToVpnAddr(t header.MessageType, st header.MessageSubType, vpnAddr netip.Addr, p, nb, out []byte) {
  197. hostInfo, ready := f.getOrHandshakeNoRouting(vpnAddr, func(hh *HandshakeHostInfo) {
  198. hh.cachePacket(f.l, t, st, p, f.SendMessageToHostInfo, f.cachedPacketMetrics)
  199. })
  200. if hostInfo == nil {
  201. if f.l.Level >= logrus.DebugLevel {
  202. f.l.WithField("vpnAddr", vpnAddr).
  203. Debugln("dropping SendMessageToVpnAddr, vpnAddr not in our vpn networks or in unsafe routes")
  204. }
  205. return
  206. }
  207. if !ready {
  208. return
  209. }
  210. f.SendMessageToHostInfo(t, st, hostInfo, p, nb, out)
  211. }
  212. func (f *Interface) SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hi *HostInfo, p, nb, out []byte) {
  213. f.send(t, st, hi.ConnectionState, hi, p, nb, out)
  214. }
  215. func (f *Interface) send(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, p, nb, out []byte) {
  216. f.messageMetrics.Tx(t, st, 1)
  217. f.sendNoMetrics(t, st, ci, hostinfo, netip.AddrPort{}, p, nb, out, 0, nil)
  218. }
  219. func (f *Interface) sendTo(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte) {
  220. f.messageMetrics.Tx(t, st, 1)
  221. f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out, 0, nil)
  222. }
  223. // SendVia sends a payload through a Relay tunnel. No authentication or encryption is done
  224. // to the payload for the ultimate target host, making this a useful method for sending
  225. // handshake messages to peers through relay tunnels.
  226. // via is the HostInfo through which the message is relayed.
  227. // ad is the plaintext data to authenticate, but not encrypt
  228. // nb is a buffer used to store the nonce value, re-used for performance reasons.
  229. // out is a buffer used to store the result of the Encrypt operation
  230. // q indicates which writer to use to send the packet.
  231. func (f *Interface) SendVia(via *HostInfo,
  232. relay *Relay,
  233. ad,
  234. nb,
  235. out []byte,
  236. nocopy bool,
  237. ) {
  238. if noiseutil.EncryptLockNeeded {
  239. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  240. via.ConnectionState.writeLock.Lock()
  241. }
  242. c := via.ConnectionState.messageCounter.Add(1)
  243. out = header.Encode(out, header.Version, header.Message, header.MessageRelay, relay.RemoteIndex, c)
  244. f.connectionManager.Out(via)
  245. // Authenticate the header and payload, but do not encrypt for this message type.
  246. // The payload consists of the inner, unencrypted Nebula header, as well as the end-to-end encrypted payload.
  247. if len(out)+len(ad)+via.ConnectionState.eKey.Overhead() > cap(out) {
  248. if noiseutil.EncryptLockNeeded {
  249. via.ConnectionState.writeLock.Unlock()
  250. }
  251. via.logger(f.l).
  252. WithField("outCap", cap(out)).
  253. WithField("payloadLen", len(ad)).
  254. WithField("headerLen", len(out)).
  255. WithField("cipherOverhead", via.ConnectionState.eKey.Overhead()).
  256. Error("SendVia out buffer not large enough for relay")
  257. return
  258. }
  259. // The header bytes are written to the 'out' slice; Grow the slice to hold the header and associated data payload.
  260. offset := len(out)
  261. out = out[:offset+len(ad)]
  262. // In one call path, the associated data _is_ already stored in out. In other call paths, the associated data must
  263. // be copied into 'out'.
  264. if !nocopy {
  265. copy(out[offset:], ad)
  266. }
  267. var err error
  268. out, err = via.ConnectionState.eKey.EncryptDanger(out, out, nil, c, nb)
  269. if noiseutil.EncryptLockNeeded {
  270. via.ConnectionState.writeLock.Unlock()
  271. }
  272. if err != nil {
  273. via.logger(f.l).WithError(err).Info("Failed to EncryptDanger in sendVia")
  274. return
  275. }
  276. err = f.writers[0].WriteTo(out, via.remote)
  277. if err != nil {
  278. via.logger(f.l).WithError(err).Info("Failed to WriteTo in sendVia")
  279. }
  280. f.connectionManager.RelayUsed(relay.LocalIndex)
  281. }
  282. func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte, q int, udpPortGetter udp.SendPortGetter) {
  283. if ci.eKey == nil {
  284. return
  285. }
  286. multiport := f.multiPort.Tx && hostinfo.multiportTx
  287. rawOut := out
  288. if multiport {
  289. if len(out) < udp.RawOverhead {
  290. // NOTE: This is because some spots in the code send us `out[:0]`, so
  291. // we need to expand the slice back out to get our 8 bytes back.
  292. out = out[:udp.RawOverhead]
  293. }
  294. // Preserve bytes needed for the raw socket
  295. out = out[udp.RawOverhead:]
  296. if udpPortGetter == nil {
  297. udpPortGetter = udp.RandomSendPort
  298. }
  299. }
  300. useRelay := !remote.IsValid() && !hostinfo.remote.IsValid()
  301. fullOut := out
  302. if useRelay {
  303. if len(out) < header.Len {
  304. // out always has a capacity of mtu, but not always a length greater than the header.Len.
  305. // Grow it to make sure the next operation works.
  306. out = out[:header.Len]
  307. }
  308. // Save a header's worth of data at the front of the 'out' buffer.
  309. out = out[header.Len:]
  310. }
  311. if noiseutil.EncryptLockNeeded {
  312. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  313. ci.writeLock.Lock()
  314. }
  315. c := ci.messageCounter.Add(1)
  316. //l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
  317. out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
  318. f.connectionManager.Out(hostinfo)
  319. // Query our LH if we haven't since the last time we've been rebound, this will cause the remote to punch against
  320. // all our addrs and enable a faster roaming.
  321. if t != header.CloseTunnel && hostinfo.lastRebindCount != f.rebindCount {
  322. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  323. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  324. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  325. hostinfo.lastRebindCount = f.rebindCount
  326. if f.l.Level >= logrus.DebugLevel {
  327. f.l.WithField("vpnAddrs", hostinfo.vpnAddrs).Debug("Lighthouse update triggered for punch due to rebind counter")
  328. }
  329. }
  330. var err error
  331. out, err = ci.eKey.EncryptDanger(out, out, p, c, nb)
  332. if noiseutil.EncryptLockNeeded {
  333. ci.writeLock.Unlock()
  334. }
  335. if err != nil {
  336. hostinfo.logger(f.l).WithError(err).
  337. WithField("udpAddr", remote).WithField("counter", c).
  338. WithField("attemptedCounter", c).
  339. Error("Failed to encrypt outgoing packet")
  340. return
  341. }
  342. if remote.IsValid() {
  343. if multiport {
  344. rawOut = rawOut[:len(out)+udp.RawOverhead]
  345. port := udpPortGetter.UDPSendPort(f.multiPort.TxPorts)
  346. err = f.udpRaw.WriteTo(rawOut, port, remote)
  347. } else {
  348. err = f.writers[q].WriteTo(out, remote)
  349. }
  350. if err != nil {
  351. hostinfo.logger(f.l).WithError(err).
  352. WithField("udpAddr", remote).Error("Failed to write outgoing packet")
  353. }
  354. } else if hostinfo.remote.IsValid() {
  355. if multiport {
  356. rawOut = rawOut[:len(out)+udp.RawOverhead]
  357. port := udpPortGetter.UDPSendPort(f.multiPort.TxPorts)
  358. err = f.udpRaw.WriteTo(rawOut, port, hostinfo.remote)
  359. } else {
  360. err = f.writers[q].WriteTo(out, hostinfo.remote)
  361. }
  362. if err != nil {
  363. hostinfo.logger(f.l).WithError(err).
  364. WithField("udpAddr", remote).Error("Failed to write outgoing packet")
  365. }
  366. } else {
  367. // Try to send via a relay
  368. for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
  369. relayHostInfo, relay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relayIP)
  370. if err != nil {
  371. hostinfo.relayState.DeleteRelay(relayIP)
  372. hostinfo.logger(f.l).WithField("relay", relayIP).WithError(err).Info("sendNoMetrics failed to find HostInfo")
  373. continue
  374. }
  375. f.SendVia(relayHostInfo, relay, out, nb, fullOut[:header.Len+len(out)], true)
  376. break
  377. }
  378. }
  379. }