inside.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. )
  10. func (f *Interface) consumeInsidePacket(packet []byte, fwPacket *firewall.Packet, nb, out []byte, q int, localCache firewall.ConntrackCache) {
  11. err := newPacket(packet, false, fwPacket)
  12. if err != nil {
  13. if f.l.Level >= logrus.DebugLevel {
  14. f.l.WithField("packet", packet).Debugf("Error while validating outbound packet: %s", err)
  15. }
  16. return
  17. }
  18. // Ignore local broadcast packets
  19. if f.dropLocalBroadcast {
  20. _, found := f.myBroadcastAddrsTable.Lookup(fwPacket.RemoteAddr)
  21. if found {
  22. return
  23. }
  24. }
  25. //TODO: seems like a huge bummer
  26. _, found := f.myVpnAddrsTable.Lookup(fwPacket.RemoteAddr)
  27. if found {
  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.getOrHandshake(fwPacket.RemoteAddr, 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, q)
  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)
  62. if dropReason == nil {
  63. f.sendNoMetrics(header.Message, 0, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, packet, nb, out, q)
  64. } else {
  65. f.rejectInside(packet, out, q)
  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. func (f *Interface) Handshake(vpnAddr netip.Addr) {
  107. f.getOrHandshake(vpnAddr, nil)
  108. }
  109. // getOrHandshake 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) getOrHandshake(vpnAddr netip.Addr, cacheCallback func(*HandshakeHostInfo)) (*HostInfo, bool) {
  112. _, found := f.myVpnNetworksTable.Lookup(vpnAddr)
  113. if !found {
  114. vpnAddr = f.inside.RouteFor(vpnAddr)
  115. if !vpnAddr.IsValid() {
  116. return nil, false
  117. }
  118. }
  119. return f.handshakeManager.GetOrHandshake(vpnAddr, cacheCallback)
  120. }
  121. func (f *Interface) sendMessageNow(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p, nb, out []byte) {
  122. fp := &firewall.Packet{}
  123. err := newPacket(p, false, fp)
  124. if err != nil {
  125. f.l.Warnf("error while parsing outgoing packet for firewall check; %v", err)
  126. return
  127. }
  128. // check if packet is in outbound fw rules
  129. dropReason := f.firewall.Drop(*fp, false, hostinfo, f.pki.GetCAPool(), nil)
  130. if dropReason != nil {
  131. if f.l.Level >= logrus.DebugLevel {
  132. f.l.WithField("fwPacket", fp).
  133. WithField("reason", dropReason).
  134. Debugln("dropping cached packet")
  135. }
  136. return
  137. }
  138. f.sendNoMetrics(header.Message, st, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, p, nb, out, 0)
  139. }
  140. // SendMessageToVpnAddr handles real addr:port lookup and sends to the current best known address for vpnAddr
  141. func (f *Interface) SendMessageToVpnAddr(t header.MessageType, st header.MessageSubType, vpnAddr netip.Addr, p, nb, out []byte) {
  142. hostInfo, ready := f.getOrHandshake(vpnAddr, func(hh *HandshakeHostInfo) {
  143. hh.cachePacket(f.l, t, st, p, f.SendMessageToHostInfo, f.cachedPacketMetrics)
  144. })
  145. if hostInfo == nil {
  146. if f.l.Level >= logrus.DebugLevel {
  147. f.l.WithField("vpnAddr", vpnAddr).
  148. Debugln("dropping SendMessageToVpnAddr, vpnAddr not in our vpn networks or in unsafe routes")
  149. }
  150. return
  151. }
  152. if !ready {
  153. return
  154. }
  155. f.SendMessageToHostInfo(t, st, hostInfo, p, nb, out)
  156. }
  157. func (f *Interface) SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hi *HostInfo, p, nb, out []byte) {
  158. f.send(t, st, hi.ConnectionState, hi, p, nb, out)
  159. }
  160. func (f *Interface) send(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, p, nb, out []byte) {
  161. f.messageMetrics.Tx(t, st, 1)
  162. f.sendNoMetrics(t, st, ci, hostinfo, netip.AddrPort{}, p, nb, out, 0)
  163. }
  164. func (f *Interface) sendTo(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte) {
  165. f.messageMetrics.Tx(t, st, 1)
  166. f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out, 0)
  167. }
  168. // SendVia sends a payload through a Relay tunnel. No authentication or encryption is done
  169. // to the payload for the ultimate target host, making this a useful method for sending
  170. // handshake messages to peers through relay tunnels.
  171. // via is the HostInfo through which the message is relayed.
  172. // ad is the plaintext data to authenticate, but not encrypt
  173. // nb is a buffer used to store the nonce value, re-used for performance reasons.
  174. // out is a buffer used to store the result of the Encrypt operation
  175. // q indicates which writer to use to send the packet.
  176. func (f *Interface) SendVia(via *HostInfo,
  177. relay *Relay,
  178. ad,
  179. nb,
  180. out []byte,
  181. nocopy bool,
  182. ) {
  183. if noiseutil.EncryptLockNeeded {
  184. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  185. via.ConnectionState.writeLock.Lock()
  186. }
  187. c := via.ConnectionState.messageCounter.Add(1)
  188. out = header.Encode(out, header.Version, header.Message, header.MessageRelay, relay.RemoteIndex, c)
  189. f.connectionManager.Out(via.localIndexId)
  190. // Authenticate the header and payload, but do not encrypt for this message type.
  191. // The payload consists of the inner, unencrypted Nebula header, as well as the end-to-end encrypted payload.
  192. if len(out)+len(ad)+via.ConnectionState.eKey.Overhead() > cap(out) {
  193. if noiseutil.EncryptLockNeeded {
  194. via.ConnectionState.writeLock.Unlock()
  195. }
  196. via.logger(f.l).
  197. WithField("outCap", cap(out)).
  198. WithField("payloadLen", len(ad)).
  199. WithField("headerLen", len(out)).
  200. WithField("cipherOverhead", via.ConnectionState.eKey.Overhead()).
  201. Error("SendVia out buffer not large enough for relay")
  202. return
  203. }
  204. // The header bytes are written to the 'out' slice; Grow the slice to hold the header and associated data payload.
  205. offset := len(out)
  206. out = out[:offset+len(ad)]
  207. // In one call path, the associated data _is_ already stored in out. In other call paths, the associated data must
  208. // be copied into 'out'.
  209. if !nocopy {
  210. copy(out[offset:], ad)
  211. }
  212. var err error
  213. out, err = via.ConnectionState.eKey.EncryptDanger(out, out, nil, c, nb)
  214. if noiseutil.EncryptLockNeeded {
  215. via.ConnectionState.writeLock.Unlock()
  216. }
  217. if err != nil {
  218. via.logger(f.l).WithError(err).Info("Failed to EncryptDanger in sendVia")
  219. return
  220. }
  221. err = f.writers[0].WriteTo(out, via.remote)
  222. if err != nil {
  223. via.logger(f.l).WithError(err).Info("Failed to WriteTo in sendVia")
  224. }
  225. f.connectionManager.RelayUsed(relay.LocalIndex)
  226. }
  227. func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte, q int) {
  228. if ci.eKey == nil {
  229. //TODO: log warning
  230. return
  231. }
  232. useRelay := !remote.IsValid() && !hostinfo.remote.IsValid()
  233. fullOut := out
  234. if useRelay {
  235. if len(out) < header.Len {
  236. // out always has a capacity of mtu, but not always a length greater than the header.Len.
  237. // Grow it to make sure the next operation works.
  238. out = out[:header.Len]
  239. }
  240. // Save a header's worth of data at the front of the 'out' buffer.
  241. out = out[header.Len:]
  242. }
  243. if noiseutil.EncryptLockNeeded {
  244. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  245. ci.writeLock.Lock()
  246. }
  247. c := ci.messageCounter.Add(1)
  248. //l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
  249. out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
  250. f.connectionManager.Out(hostinfo.localIndexId)
  251. // Query our LH if we haven't since the last time we've been rebound, this will cause the remote to punch against
  252. // all our addrs and enable a faster roaming.
  253. if t != header.CloseTunnel && hostinfo.lastRebindCount != f.rebindCount {
  254. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  255. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  256. f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
  257. hostinfo.lastRebindCount = f.rebindCount
  258. if f.l.Level >= logrus.DebugLevel {
  259. f.l.WithField("vpnAddrs", hostinfo.vpnAddrs).Debug("Lighthouse update triggered for punch due to rebind counter")
  260. }
  261. }
  262. var err error
  263. out, err = ci.eKey.EncryptDanger(out, out, p, c, nb)
  264. if noiseutil.EncryptLockNeeded {
  265. ci.writeLock.Unlock()
  266. }
  267. if err != nil {
  268. hostinfo.logger(f.l).WithError(err).
  269. WithField("udpAddr", remote).WithField("counter", c).
  270. WithField("attemptedCounter", c).
  271. Error("Failed to encrypt outgoing packet")
  272. return
  273. }
  274. if remote.IsValid() {
  275. err = f.writers[q].WriteTo(out, remote)
  276. if err != nil {
  277. hostinfo.logger(f.l).WithError(err).
  278. WithField("udpAddr", remote).Error("Failed to write outgoing packet")
  279. }
  280. } else if hostinfo.remote.IsValid() {
  281. err = f.writers[q].WriteTo(out, hostinfo.remote)
  282. if err != nil {
  283. hostinfo.logger(f.l).WithError(err).
  284. WithField("udpAddr", remote).Error("Failed to write outgoing packet")
  285. }
  286. } else {
  287. // Try to send via a relay
  288. for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
  289. relayHostInfo, relay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relayIP)
  290. if err != nil {
  291. hostinfo.relayState.DeleteRelay(relayIP)
  292. hostinfo.logger(f.l).WithField("relay", relayIP).WithError(err).Info("sendNoMetrics failed to find HostInfo")
  293. continue
  294. }
  295. f.SendVia(relayHostInfo, relay, out, nb, fullOut[:header.Len+len(out)], true)
  296. break
  297. }
  298. }
  299. }