2
0

inside.go 11 KB

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