inside.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. package nebula
  2. import (
  3. "github.com/sirupsen/logrus"
  4. "github.com/slackhq/nebula/firewall"
  5. "github.com/slackhq/nebula/header"
  6. "github.com/slackhq/nebula/iputil"
  7. "github.com/slackhq/nebula/noiseutil"
  8. "github.com/slackhq/nebula/udp"
  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 && fwPacket.RemoteIP == f.localBroadcast {
  20. return
  21. }
  22. if fwPacket.RemoteIP == f.myVpnIp {
  23. // Immediately forward packets from self to self.
  24. // This should only happen on Darwin-based and FreeBSD hosts, which
  25. // routes packets from the Nebula IP to the Nebula IP through the Nebula
  26. // TUN device.
  27. if immediatelyForwardToSelf {
  28. _, err := f.readers[q].Write(packet)
  29. if err != nil {
  30. f.l.WithError(err).Error("Failed to forward to tun")
  31. }
  32. }
  33. // Otherwise, drop. On linux, we should never see these packets - Linux
  34. // routes packets from the nebula IP to the nebula IP through the loopback device.
  35. return
  36. }
  37. // Ignore broadcast packets
  38. if f.dropMulticast && isMulticast(fwPacket.RemoteIP) {
  39. return
  40. }
  41. hostinfo, ready := f.getOrHandshake(fwPacket.RemoteIP, func(h *HostInfo) {
  42. h.unlockedCachePacket(f.l, header.Message, 0, packet, f.sendMessageNow, f.cachedPacketMetrics)
  43. })
  44. if hostinfo == nil {
  45. f.rejectInside(packet, out, q)
  46. if f.l.Level >= logrus.DebugLevel {
  47. f.l.WithField("vpnIp", fwPacket.RemoteIP).
  48. WithField("fwPacket", fwPacket).
  49. Debugln("dropping outbound packet, vpnIp not in our CIDR or in unsafe routes")
  50. }
  51. return
  52. }
  53. if !ready {
  54. return
  55. }
  56. dropReason := f.firewall.Drop(packet, *fwPacket, false, hostinfo, f.pki.GetCAPool(), localCache)
  57. if dropReason == nil {
  58. f.sendNoMetrics(header.Message, 0, hostinfo.ConnectionState, hostinfo, nil, packet, nb, out, q)
  59. } else {
  60. f.rejectInside(packet, out, q)
  61. if f.l.Level >= logrus.DebugLevel {
  62. hostinfo.logger(f.l).
  63. WithField("fwPacket", fwPacket).
  64. WithField("reason", dropReason).
  65. Debugln("dropping outbound packet")
  66. }
  67. }
  68. }
  69. func (f *Interface) rejectInside(packet []byte, out []byte, q int) {
  70. if !f.firewall.InSendReject {
  71. return
  72. }
  73. out = iputil.CreateRejectPacket(packet, out)
  74. _, err := f.readers[q].Write(out)
  75. if err != nil {
  76. f.l.WithError(err).Error("Failed to write to tun")
  77. }
  78. }
  79. func (f *Interface) rejectOutside(packet []byte, ci *ConnectionState, hostinfo *HostInfo, nb, out []byte, q int) {
  80. if !f.firewall.OutSendReject {
  81. return
  82. }
  83. // Use some out buffer space to build the packet before encryption
  84. // Need 40 bytes for the reject packet (20 byte ipv4 header, 20 byte tcp rst packet)
  85. // Leave 100 bytes for the encrypted packet (60 byte Nebula header, 40 byte reject packet)
  86. out = out[:140]
  87. outPacket := iputil.CreateRejectPacket(packet, out[100:])
  88. f.sendNoMetrics(header.Message, 0, ci, hostinfo, nil, outPacket, nb, out, q)
  89. }
  90. func (f *Interface) Handshake(vpnIp iputil.VpnIp) {
  91. f.getOrHandshake(vpnIp, nil)
  92. }
  93. // getOrHandshake returns nil if the vpnIp is not routable.
  94. // If the 2nd return var is false then the hostinfo is not ready to be used in a tunnel
  95. func (f *Interface) getOrHandshake(vpnIp iputil.VpnIp, cacheCallback func(info *HostInfo)) (*HostInfo, bool) {
  96. if !ipMaskContains(f.lightHouse.myVpnIp, f.lightHouse.myVpnZeros, vpnIp) {
  97. vpnIp = f.inside.RouteFor(vpnIp)
  98. if vpnIp == 0 {
  99. return nil, false
  100. }
  101. }
  102. return f.handshakeManager.GetOrHandshake(vpnIp, cacheCallback)
  103. }
  104. func (f *Interface) sendMessageNow(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p, nb, out []byte) {
  105. fp := &firewall.Packet{}
  106. err := newPacket(p, false, fp)
  107. if err != nil {
  108. f.l.Warnf("error while parsing outgoing packet for firewall check; %v", err)
  109. return
  110. }
  111. // check if packet is in outbound fw rules
  112. dropReason := f.firewall.Drop(p, *fp, false, hostinfo, f.pki.GetCAPool(), nil)
  113. if dropReason != nil {
  114. if f.l.Level >= logrus.DebugLevel {
  115. f.l.WithField("fwPacket", fp).
  116. WithField("reason", dropReason).
  117. Debugln("dropping cached packet")
  118. }
  119. return
  120. }
  121. f.sendNoMetrics(header.Message, st, hostinfo.ConnectionState, hostinfo, nil, p, nb, out, 0)
  122. }
  123. // SendMessageToVpnIp handles real ip:port lookup and sends to the current best known address for vpnIp
  124. func (f *Interface) SendMessageToVpnIp(t header.MessageType, st header.MessageSubType, vpnIp iputil.VpnIp, p, nb, out []byte) {
  125. hostInfo, ready := f.getOrHandshake(vpnIp, func(h *HostInfo) {
  126. h.unlockedCachePacket(f.l, t, st, p, f.SendMessageToHostInfo, f.cachedPacketMetrics)
  127. })
  128. if hostInfo == nil {
  129. if f.l.Level >= logrus.DebugLevel {
  130. f.l.WithField("vpnIp", vpnIp).
  131. Debugln("dropping SendMessageToVpnIp, vpnIp not in our CIDR or in unsafe routes")
  132. }
  133. return
  134. }
  135. if !ready {
  136. return
  137. }
  138. f.SendMessageToHostInfo(t, st, hostInfo, p, nb, out)
  139. }
  140. func (f *Interface) SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hi *HostInfo, p, nb, out []byte) {
  141. f.send(t, st, hi.ConnectionState, hi, p, nb, out)
  142. }
  143. func (f *Interface) send(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, p, nb, out []byte) {
  144. f.messageMetrics.Tx(t, st, 1)
  145. f.sendNoMetrics(t, st, ci, hostinfo, nil, p, nb, out, 0)
  146. }
  147. func (f *Interface) sendTo(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote *udp.Addr, p, nb, out []byte) {
  148. f.messageMetrics.Tx(t, st, 1)
  149. f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out, 0)
  150. }
  151. // SendVia sends a payload through a Relay tunnel. No authentication or encryption is done
  152. // to the payload for the ultimate target host, making this a useful method for sending
  153. // handshake messages to peers through relay tunnels.
  154. // via is the HostInfo through which the message is relayed.
  155. // ad is the plaintext data to authenticate, but not encrypt
  156. // nb is a buffer used to store the nonce value, re-used for performance reasons.
  157. // out is a buffer used to store the result of the Encrypt operation
  158. // q indicates which writer to use to send the packet.
  159. func (f *Interface) SendVia(via *HostInfo,
  160. relay *Relay,
  161. ad,
  162. nb,
  163. out []byte,
  164. nocopy bool,
  165. ) {
  166. if noiseutil.EncryptLockNeeded {
  167. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  168. via.ConnectionState.writeLock.Lock()
  169. }
  170. c := via.ConnectionState.messageCounter.Add(1)
  171. out = header.Encode(out, header.Version, header.Message, header.MessageRelay, relay.RemoteIndex, c)
  172. f.connectionManager.Out(via.localIndexId)
  173. // Authenticate the header and payload, but do not encrypt for this message type.
  174. // The payload consists of the inner, unencrypted Nebula header, as well as the end-to-end encrypted payload.
  175. if len(out)+len(ad)+via.ConnectionState.eKey.Overhead() > cap(out) {
  176. if noiseutil.EncryptLockNeeded {
  177. via.ConnectionState.writeLock.Unlock()
  178. }
  179. via.logger(f.l).
  180. WithField("outCap", cap(out)).
  181. WithField("payloadLen", len(ad)).
  182. WithField("headerLen", len(out)).
  183. WithField("cipherOverhead", via.ConnectionState.eKey.Overhead()).
  184. Error("SendVia out buffer not large enough for relay")
  185. return
  186. }
  187. // The header bytes are written to the 'out' slice; Grow the slice to hold the header and associated data payload.
  188. offset := len(out)
  189. out = out[:offset+len(ad)]
  190. // In one call path, the associated data _is_ already stored in out. In other call paths, the associated data must
  191. // be copied into 'out'.
  192. if !nocopy {
  193. copy(out[offset:], ad)
  194. }
  195. var err error
  196. out, err = via.ConnectionState.eKey.EncryptDanger(out, out, nil, c, nb)
  197. if noiseutil.EncryptLockNeeded {
  198. via.ConnectionState.writeLock.Unlock()
  199. }
  200. if err != nil {
  201. via.logger(f.l).WithError(err).Info("Failed to EncryptDanger in sendVia")
  202. return
  203. }
  204. err = f.writers[0].WriteTo(out, via.remote)
  205. if err != nil {
  206. via.logger(f.l).WithError(err).Info("Failed to WriteTo in sendVia")
  207. }
  208. f.connectionManager.RelayUsed(relay.LocalIndex)
  209. }
  210. func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote *udp.Addr, p, nb, out []byte, q int) {
  211. if ci.eKey == nil {
  212. //TODO: log warning
  213. return
  214. }
  215. useRelay := remote == nil && hostinfo.remote == nil
  216. fullOut := out
  217. if useRelay {
  218. if len(out) < header.Len {
  219. // out always has a capacity of mtu, but not always a length greater than the header.Len.
  220. // Grow it to make sure the next operation works.
  221. out = out[:header.Len]
  222. }
  223. // Save a header's worth of data at the front of the 'out' buffer.
  224. out = out[header.Len:]
  225. }
  226. if noiseutil.EncryptLockNeeded {
  227. // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
  228. ci.writeLock.Lock()
  229. }
  230. c := ci.messageCounter.Add(1)
  231. //l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
  232. out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
  233. f.connectionManager.Out(hostinfo.localIndexId)
  234. // Query our LH if we haven't since the last time we've been rebound, this will cause the remote to punch against
  235. // all our IPs and enable a faster roaming.
  236. if t != header.CloseTunnel && hostinfo.lastRebindCount != f.rebindCount {
  237. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  238. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  239. f.lightHouse.QueryServer(hostinfo.vpnIp, f)
  240. hostinfo.lastRebindCount = f.rebindCount
  241. if f.l.Level >= logrus.DebugLevel {
  242. f.l.WithField("vpnIp", hostinfo.vpnIp).Debug("Lighthouse update triggered for punch due to rebind counter")
  243. }
  244. }
  245. var err error
  246. out, err = ci.eKey.EncryptDanger(out, out, p, c, nb)
  247. if noiseutil.EncryptLockNeeded {
  248. ci.writeLock.Unlock()
  249. }
  250. if err != nil {
  251. hostinfo.logger(f.l).WithError(err).
  252. WithField("udpAddr", remote).WithField("counter", c).
  253. WithField("attemptedCounter", c).
  254. Error("Failed to encrypt outgoing packet")
  255. return
  256. }
  257. if remote != nil {
  258. err = f.writers[q].WriteTo(out, remote)
  259. if err != nil {
  260. hostinfo.logger(f.l).WithError(err).
  261. WithField("udpAddr", remote).Error("Failed to write outgoing packet")
  262. }
  263. } else if hostinfo.remote != nil {
  264. err = f.writers[q].WriteTo(out, hostinfo.remote)
  265. if err != nil {
  266. hostinfo.logger(f.l).WithError(err).
  267. WithField("udpAddr", remote).Error("Failed to write outgoing packet")
  268. }
  269. } else {
  270. // Try to send via a relay
  271. for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
  272. relayHostInfo, relay, err := f.hostMap.QueryVpnIpRelayFor(hostinfo.vpnIp, relayIP)
  273. if err != nil {
  274. hostinfo.relayState.DeleteRelay(relayIP)
  275. hostinfo.logger(f.l).WithField("relay", relayIP).WithError(err).Info("sendNoMetrics failed to find HostInfo")
  276. continue
  277. }
  278. f.SendVia(relayHostInfo, relay, out, nb, fullOut[:header.Len+len(out)], true)
  279. break
  280. }
  281. }
  282. }
  283. func isMulticast(ip iputil.VpnIp) bool {
  284. // Class D multicast
  285. return (((ip >> 24) & 0xff) & 0xf0) == 0xe0
  286. }