inside.go 14 KB

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