inside.go 12 KB

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