inside.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. package nebula
  2. import (
  3. "sync/atomic"
  4. "github.com/flynn/noise"
  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/udp"
  10. )
  11. func (f *Interface) consumeInsidePacket(packet []byte, fwPacket *firewall.Packet, nb, out []byte, q int, localCache firewall.ConntrackCache) {
  12. err := newPacket(packet, false, fwPacket)
  13. if err != nil {
  14. if f.l.Level >= logrus.DebugLevel {
  15. f.l.WithField("packet", packet).Debugf("Error while validating outbound packet: %s", err)
  16. }
  17. return
  18. }
  19. // Ignore local broadcast packets
  20. if f.dropLocalBroadcast && fwPacket.RemoteIP == f.localBroadcast {
  21. return
  22. }
  23. if fwPacket.RemoteIP == f.myVpnIp {
  24. // Immediately forward packets from self to self.
  25. // This should only happen on Darwin-based hosts, which routes packets from
  26. // the Nebula IP to the Nebula IP through the Nebula 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 := f.getOrHandshake(fwPacket.RemoteIP)
  42. if hostinfo == nil {
  43. if f.l.Level >= logrus.DebugLevel {
  44. f.l.WithField("vpnIp", fwPacket.RemoteIP).
  45. WithField("fwPacket", fwPacket).
  46. Debugln("dropping outbound packet, vpnIp not in our CIDR or in unsafe routes")
  47. }
  48. return
  49. }
  50. ci := hostinfo.ConnectionState
  51. if ci.ready == false {
  52. // Because we might be sending stored packets, lock here to stop new things going to
  53. // the packet queue.
  54. ci.queueLock.Lock()
  55. if !ci.ready {
  56. hostinfo.cachePacket(f.l, header.Message, 0, packet, f.sendMessageNow, f.cachedPacketMetrics)
  57. ci.queueLock.Unlock()
  58. return
  59. }
  60. ci.queueLock.Unlock()
  61. }
  62. dropReason := f.firewall.Drop(packet, *fwPacket, false, hostinfo, f.caPool, localCache)
  63. if dropReason == nil {
  64. f.sendNoMetrics(header.Message, 0, ci, hostinfo, nil, packet, nb, out, q)
  65. } else 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. func (f *Interface) Handshake(vpnIp iputil.VpnIp) {
  73. f.getOrHandshake(vpnIp)
  74. }
  75. // getOrHandshake returns nil if the vpnIp is not routable
  76. func (f *Interface) getOrHandshake(vpnIp iputil.VpnIp) *HostInfo {
  77. //TODO: we can find contains without converting back to bytes
  78. if f.hostMap.vpnCIDR.Contains(vpnIp.ToIP()) == false {
  79. vpnIp = f.inside.RouteFor(vpnIp)
  80. if vpnIp == 0 {
  81. return nil
  82. }
  83. }
  84. hostinfo, err := f.hostMap.PromoteBestQueryVpnIp(vpnIp, f)
  85. //if err != nil || hostinfo.ConnectionState == nil {
  86. if err != nil {
  87. hostinfo, err = f.handshakeManager.pendingHostMap.QueryVpnIp(vpnIp)
  88. if err != nil {
  89. hostinfo = f.handshakeManager.AddVpnIp(vpnIp, f.initHostInfo)
  90. }
  91. }
  92. ci := hostinfo.ConnectionState
  93. if ci != nil && ci.eKey != nil && ci.ready {
  94. return hostinfo
  95. }
  96. // Handshake is not ready, we need to grab the lock now before we start the handshake process
  97. hostinfo.Lock()
  98. defer hostinfo.Unlock()
  99. // Double check, now that we have the lock
  100. ci = hostinfo.ConnectionState
  101. if ci != nil && ci.eKey != nil && ci.ready {
  102. return hostinfo
  103. }
  104. // If we have already created the handshake packet, we don't want to call the function at all.
  105. if !hostinfo.HandshakeReady {
  106. ixHandshakeStage0(f, vpnIp, hostinfo)
  107. // FIXME: Maybe make XX selectable, but probably not since psk makes it nearly pointless for us.
  108. //xx_handshakeStage0(f, ip, hostinfo)
  109. // If this is a static host, we don't need to wait for the HostQueryReply
  110. // We can trigger the handshake right now
  111. if _, ok := f.lightHouse.GetStaticHostList()[vpnIp]; ok {
  112. select {
  113. case f.handshakeManager.trigger <- vpnIp:
  114. default:
  115. }
  116. }
  117. }
  118. return hostinfo
  119. }
  120. // initHostInfo is the init function to pass to (*HandshakeManager).AddVpnIP that
  121. // will create the initial Noise ConnectionState
  122. func (f *Interface) initHostInfo(hostinfo *HostInfo) {
  123. hostinfo.ConnectionState = f.newConnectionState(f.l, true, noise.HandshakeIX, []byte{}, 0)
  124. }
  125. func (f *Interface) sendMessageNow(t header.MessageType, st header.MessageSubType, hostInfo *HostInfo, p, nb, out []byte) {
  126. fp := &firewall.Packet{}
  127. err := newPacket(p, false, fp)
  128. if err != nil {
  129. f.l.Warnf("error while parsing outgoing packet for firewall check; %v", err)
  130. return
  131. }
  132. // check if packet is in outbound fw rules
  133. dropReason := f.firewall.Drop(p, *fp, false, hostInfo, f.caPool, nil)
  134. if dropReason != nil {
  135. if f.l.Level >= logrus.DebugLevel {
  136. f.l.WithField("fwPacket", fp).
  137. WithField("reason", dropReason).
  138. Debugln("dropping cached packet")
  139. }
  140. return
  141. }
  142. f.sendNoMetrics(header.Message, st, hostInfo.ConnectionState, hostInfo, nil, p, nb, out, 0)
  143. }
  144. // SendMessageToVpnIp handles real ip:port lookup and sends to the current best known address for vpnIp
  145. func (f *Interface) SendMessageToVpnIp(t header.MessageType, st header.MessageSubType, vpnIp iputil.VpnIp, p, nb, out []byte) {
  146. hostInfo := f.getOrHandshake(vpnIp)
  147. if hostInfo == nil {
  148. if f.l.Level >= logrus.DebugLevel {
  149. f.l.WithField("vpnIp", vpnIp).
  150. Debugln("dropping SendMessageToVpnIp, vpnIp not in our CIDR or in unsafe routes")
  151. }
  152. return
  153. }
  154. if !hostInfo.ConnectionState.ready {
  155. // Because we might be sending stored packets, lock here to stop new things going to
  156. // the packet queue.
  157. hostInfo.ConnectionState.queueLock.Lock()
  158. if !hostInfo.ConnectionState.ready {
  159. hostInfo.cachePacket(f.l, t, st, p, f.sendMessageToVpnIp, f.cachedPacketMetrics)
  160. hostInfo.ConnectionState.queueLock.Unlock()
  161. return
  162. }
  163. hostInfo.ConnectionState.queueLock.Unlock()
  164. }
  165. f.sendMessageToVpnIp(t, st, hostInfo, p, nb, out)
  166. return
  167. }
  168. func (f *Interface) sendMessageToVpnIp(t header.MessageType, st header.MessageSubType, hostInfo *HostInfo, p, nb, out []byte) {
  169. f.send(t, st, hostInfo.ConnectionState, hostInfo, p, nb, out)
  170. }
  171. func (f *Interface) send(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, p, nb, out []byte) {
  172. f.messageMetrics.Tx(t, st, 1)
  173. f.sendNoMetrics(t, st, ci, hostinfo, nil, p, nb, out, 0)
  174. }
  175. func (f *Interface) sendTo(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote *udp.Addr, p, nb, out []byte) {
  176. f.messageMetrics.Tx(t, st, 1)
  177. f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out, 0)
  178. }
  179. // sendVia sends a payload through a Relay tunnel. No authentication or encryption is done
  180. // to the payload for the ultimate target host, making this a useful method for sending
  181. // handshake messages to peers through relay tunnels.
  182. // via is the HostInfo through which the message is relayed.
  183. // ad is the plaintext data to authenticate, but not encrypt
  184. // nb is a buffer used to store the nonce value, re-used for performance reasons.
  185. // out is a buffer used to store the result of the Encrypt operation
  186. // q indicates which writer to use to send the packet.
  187. func (f *Interface) SendVia(viaIfc interface{},
  188. relayIfc interface{},
  189. ad,
  190. nb,
  191. out []byte,
  192. nocopy bool,
  193. ) {
  194. via := viaIfc.(*HostInfo)
  195. relay := relayIfc.(*Relay)
  196. c := atomic.AddUint64(&via.ConnectionState.atomicMessageCounter, 1)
  197. out = header.Encode(out, header.Version, header.Message, header.MessageRelay, relay.RemoteIndex, c)
  198. f.connectionManager.Out(via.vpnIp)
  199. // Authenticate the header and payload, but do not encrypt for this message type.
  200. // The payload consists of the inner, unencrypted Nebula header, as well as the end-to-end encrypted payload.
  201. if len(out)+len(ad)+via.ConnectionState.eKey.Overhead() > cap(out) {
  202. via.logger(f.l).
  203. WithField("outCap", cap(out)).
  204. WithField("payloadLen", len(ad)).
  205. WithField("headerLen", len(out)).
  206. WithField("cipherOverhead", via.ConnectionState.eKey.Overhead()).
  207. Error("SendVia out buffer not large enough for relay")
  208. return
  209. }
  210. // The header bytes are written to the 'out' slice; Grow the slice to hold the header and associated data payload.
  211. offset := len(out)
  212. out = out[:offset+len(ad)]
  213. // In one call path, the associated data _is_ already stored in out. In other call paths, the associated data must
  214. // be copied into 'out'.
  215. if !nocopy {
  216. copy(out[offset:], ad)
  217. }
  218. var err error
  219. out, err = via.ConnectionState.eKey.EncryptDanger(out, out, nil, c, nb)
  220. if err != nil {
  221. via.logger(f.l).WithError(err).Info("Failed to EncryptDanger in sendVia")
  222. return
  223. }
  224. err = f.writers[0].WriteTo(out, via.remote)
  225. if err != nil {
  226. via.logger(f.l).WithError(err).Info("Failed to WriteTo in sendVia")
  227. }
  228. }
  229. func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote *udp.Addr, p, nb, out []byte, q int) {
  230. if ci.eKey == nil {
  231. //TODO: log warning
  232. return
  233. }
  234. useRelay := remote == nil && hostinfo.remote == nil
  235. fullOut := out
  236. if useRelay {
  237. if len(out) < header.Len {
  238. // out always has a capacity of mtu, but not always a length greater than the header.Len.
  239. // Grow it to make sure the next operation works.
  240. out = out[:header.Len]
  241. }
  242. // Save a header's worth of data at the front of the 'out' buffer.
  243. out = out[header.Len:]
  244. }
  245. //TODO: enable if we do more than 1 tun queue
  246. //ci.writeLock.Lock()
  247. c := atomic.AddUint64(&ci.atomicMessageCounter, 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.vpnIp)
  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 IPs 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.vpnIp, f)
  257. hostinfo.lastRebindCount = f.rebindCount
  258. if f.l.Level >= logrus.DebugLevel {
  259. f.l.WithField("vpnIp", hostinfo.vpnIp).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. //TODO: see above note on lock
  265. //ci.writeLock.Unlock()
  266. if err != nil {
  267. hostinfo.logger(f.l).WithError(err).
  268. WithField("udpAddr", remote).WithField("counter", c).
  269. WithField("attemptedCounter", c).
  270. Error("Failed to encrypt outgoing packet")
  271. return
  272. }
  273. if remote != nil {
  274. err = f.writers[q].WriteTo(out, remote)
  275. if err != nil {
  276. hostinfo.logger(f.l).WithError(err).
  277. WithField("udpAddr", remote).Error("Failed to write outgoing packet")
  278. }
  279. } else if hostinfo.remote != nil {
  280. err = f.writers[q].WriteTo(out, hostinfo.remote)
  281. if err != nil {
  282. hostinfo.logger(f.l).WithError(err).
  283. WithField("udpAddr", remote).Error("Failed to write outgoing packet")
  284. }
  285. } else {
  286. // Try to send via a relay
  287. for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
  288. relayHostInfo, err := f.hostMap.QueryVpnIp(relayIP)
  289. if err != nil {
  290. hostinfo.logger(f.l).WithField("relayIp", relayIP).WithError(err).Info("sendNoMetrics failed to find HostInfo")
  291. continue
  292. }
  293. relay, ok := relayHostInfo.relayState.QueryRelayForByIp(hostinfo.vpnIp)
  294. if !ok {
  295. hostinfo.logger(f.l).
  296. WithField("relayIp", relayHostInfo.vpnIp).
  297. WithField("relayTarget", hostinfo.vpnIp).
  298. Info("sendNoMetrics relay missing object for target")
  299. continue
  300. }
  301. f.SendVia(relayHostInfo, relay, out, nb, fullOut[:header.Len+len(out)], true)
  302. break
  303. }
  304. }
  305. return
  306. }
  307. func isMulticast(ip iputil.VpnIp) bool {
  308. // Class D multicast
  309. if (((ip >> 24) & 0xff) & 0xf0) == 0xe0 {
  310. return true
  311. }
  312. return false
  313. }