inside.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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 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 := 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. if !ipMaskContains(f.lightHouse.myVpnIp, f.lightHouse.myVpnZeros, vpnIp) {
  78. vpnIp = f.inside.RouteFor(vpnIp)
  79. if vpnIp == 0 {
  80. return nil
  81. }
  82. }
  83. hostinfo, err := f.hostMap.PromoteBestQueryVpnIp(vpnIp, f)
  84. //if err != nil || hostinfo.ConnectionState == nil {
  85. if err != nil {
  86. hostinfo, err = f.handshakeManager.pendingHostMap.QueryVpnIp(vpnIp)
  87. if err != nil {
  88. hostinfo = f.handshakeManager.AddVpnIp(vpnIp, f.initHostInfo)
  89. }
  90. }
  91. ci := hostinfo.ConnectionState
  92. if ci != nil && ci.eKey != nil && ci.ready {
  93. return hostinfo
  94. }
  95. // Handshake is not ready, we need to grab the lock now before we start the handshake process
  96. hostinfo.Lock()
  97. defer hostinfo.Unlock()
  98. // Double check, now that we have the lock
  99. ci = hostinfo.ConnectionState
  100. if ci != nil && ci.eKey != nil && ci.ready {
  101. return hostinfo
  102. }
  103. // If we have already created the handshake packet, we don't want to call the function at all.
  104. if !hostinfo.HandshakeReady {
  105. ixHandshakeStage0(f, vpnIp, hostinfo)
  106. // FIXME: Maybe make XX selectable, but probably not since psk makes it nearly pointless for us.
  107. //xx_handshakeStage0(f, ip, hostinfo)
  108. // If this is a static host, we don't need to wait for the HostQueryReply
  109. // We can trigger the handshake right now
  110. if _, ok := f.lightHouse.GetStaticHostList()[vpnIp]; ok {
  111. select {
  112. case f.handshakeManager.trigger <- vpnIp:
  113. default:
  114. }
  115. }
  116. }
  117. return hostinfo
  118. }
  119. // initHostInfo is the init function to pass to (*HandshakeManager).AddVpnIP that
  120. // will create the initial Noise ConnectionState
  121. func (f *Interface) initHostInfo(hostinfo *HostInfo) {
  122. hostinfo.ConnectionState = f.newConnectionState(f.l, true, noise.HandshakeIX, []byte{}, 0)
  123. }
  124. func (f *Interface) sendMessageNow(t header.MessageType, st header.MessageSubType, hostInfo *HostInfo, p, nb, out []byte) {
  125. fp := &firewall.Packet{}
  126. err := newPacket(p, false, fp)
  127. if err != nil {
  128. f.l.Warnf("error while parsing outgoing packet for firewall check; %v", err)
  129. return
  130. }
  131. // check if packet is in outbound fw rules
  132. dropReason := f.firewall.Drop(p, *fp, false, hostInfo, f.caPool, nil)
  133. if dropReason != nil {
  134. if f.l.Level >= logrus.DebugLevel {
  135. f.l.WithField("fwPacket", fp).
  136. WithField("reason", dropReason).
  137. Debugln("dropping cached packet")
  138. }
  139. return
  140. }
  141. f.sendNoMetrics(header.Message, st, hostInfo.ConnectionState, hostInfo, nil, p, nb, out, 0)
  142. }
  143. // SendMessageToVpnIp handles real ip:port lookup and sends to the current best known address for vpnIp
  144. func (f *Interface) SendMessageToVpnIp(t header.MessageType, st header.MessageSubType, vpnIp iputil.VpnIp, p, nb, out []byte) {
  145. hostInfo := f.getOrHandshake(vpnIp)
  146. if hostInfo == nil {
  147. if f.l.Level >= logrus.DebugLevel {
  148. f.l.WithField("vpnIp", vpnIp).
  149. Debugln("dropping SendMessageToVpnIp, vpnIp not in our CIDR or in unsafe routes")
  150. }
  151. return
  152. }
  153. if !hostInfo.ConnectionState.ready {
  154. // Because we might be sending stored packets, lock here to stop new things going to
  155. // the packet queue.
  156. hostInfo.ConnectionState.queueLock.Lock()
  157. if !hostInfo.ConnectionState.ready {
  158. hostInfo.cachePacket(f.l, t, st, p, f.sendMessageToVpnIp, f.cachedPacketMetrics)
  159. hostInfo.ConnectionState.queueLock.Unlock()
  160. return
  161. }
  162. hostInfo.ConnectionState.queueLock.Unlock()
  163. }
  164. f.sendMessageToVpnIp(t, st, hostInfo, p, nb, out)
  165. return
  166. }
  167. func (f *Interface) sendMessageToVpnIp(t header.MessageType, st header.MessageSubType, hostInfo *HostInfo, p, nb, out []byte) {
  168. f.send(t, st, hostInfo.ConnectionState, hostInfo, p, nb, out)
  169. }
  170. func (f *Interface) send(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, p, nb, out []byte) {
  171. f.messageMetrics.Tx(t, st, 1)
  172. f.sendNoMetrics(t, st, ci, hostinfo, nil, p, nb, out, 0)
  173. }
  174. func (f *Interface) sendTo(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote *udp.Addr, p, nb, out []byte) {
  175. f.messageMetrics.Tx(t, st, 1)
  176. f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out, 0)
  177. }
  178. // sendVia sends a payload through a Relay tunnel. No authentication or encryption is done
  179. // to the payload for the ultimate target host, making this a useful method for sending
  180. // handshake messages to peers through relay tunnels.
  181. // via is the HostInfo through which the message is relayed.
  182. // ad is the plaintext data to authenticate, but not encrypt
  183. // nb is a buffer used to store the nonce value, re-used for performance reasons.
  184. // out is a buffer used to store the result of the Encrypt operation
  185. // q indicates which writer to use to send the packet.
  186. func (f *Interface) SendVia(viaIfc interface{},
  187. relayIfc interface{},
  188. ad,
  189. nb,
  190. out []byte,
  191. nocopy bool,
  192. ) {
  193. via := viaIfc.(*HostInfo)
  194. relay := relayIfc.(*Relay)
  195. c := via.ConnectionState.messageCounter.Add(1)
  196. out = header.Encode(out, header.Version, header.Message, header.MessageRelay, relay.RemoteIndex, c)
  197. f.connectionManager.Out(via.vpnIp)
  198. // Authenticate the header and payload, but do not encrypt for this message type.
  199. // The payload consists of the inner, unencrypted Nebula header, as well as the end-to-end encrypted payload.
  200. if len(out)+len(ad)+via.ConnectionState.eKey.Overhead() > cap(out) {
  201. via.logger(f.l).
  202. WithField("outCap", cap(out)).
  203. WithField("payloadLen", len(ad)).
  204. WithField("headerLen", len(out)).
  205. WithField("cipherOverhead", via.ConnectionState.eKey.Overhead()).
  206. Error("SendVia out buffer not large enough for relay")
  207. return
  208. }
  209. // The header bytes are written to the 'out' slice; Grow the slice to hold the header and associated data payload.
  210. offset := len(out)
  211. out = out[:offset+len(ad)]
  212. // In one call path, the associated data _is_ already stored in out. In other call paths, the associated data must
  213. // be copied into 'out'.
  214. if !nocopy {
  215. copy(out[offset:], ad)
  216. }
  217. var err error
  218. out, err = via.ConnectionState.eKey.EncryptDanger(out, out, nil, c, nb)
  219. if err != nil {
  220. via.logger(f.l).WithError(err).Info("Failed to EncryptDanger in sendVia")
  221. return
  222. }
  223. err = f.writers[0].WriteTo(out, via.remote)
  224. if err != nil {
  225. via.logger(f.l).WithError(err).Info("Failed to WriteTo in sendVia")
  226. }
  227. }
  228. func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote *udp.Addr, p, nb, out []byte, q int) {
  229. if ci.eKey == nil {
  230. //TODO: log warning
  231. return
  232. }
  233. useRelay := remote == nil && hostinfo.remote == nil
  234. fullOut := out
  235. if useRelay {
  236. if len(out) < header.Len {
  237. // out always has a capacity of mtu, but not always a length greater than the header.Len.
  238. // Grow it to make sure the next operation works.
  239. out = out[:header.Len]
  240. }
  241. // Save a header's worth of data at the front of the 'out' buffer.
  242. out = out[header.Len:]
  243. }
  244. //TODO: enable if we do more than 1 tun queue
  245. //ci.writeLock.Lock()
  246. c := ci.messageCounter.Add(1)
  247. //l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
  248. out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
  249. f.connectionManager.Out(hostinfo.vpnIp)
  250. // Query our LH if we haven't since the last time we've been rebound, this will cause the remote to punch against
  251. // all our IPs and enable a faster roaming.
  252. if t != header.CloseTunnel && hostinfo.lastRebindCount != f.rebindCount {
  253. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  254. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  255. f.lightHouse.QueryServer(hostinfo.vpnIp, f)
  256. hostinfo.lastRebindCount = f.rebindCount
  257. if f.l.Level >= logrus.DebugLevel {
  258. f.l.WithField("vpnIp", hostinfo.vpnIp).Debug("Lighthouse update triggered for punch due to rebind counter")
  259. }
  260. }
  261. var err error
  262. out, err = ci.eKey.EncryptDanger(out, out, p, c, nb)
  263. //TODO: see above note on lock
  264. //ci.writeLock.Unlock()
  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 != nil {
  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 != nil {
  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, err := f.hostMap.QueryVpnIp(relayIP)
  288. if err != nil {
  289. hostinfo.logger(f.l).WithField("relayIp", relayIP).WithError(err).Info("sendNoMetrics failed to find HostInfo")
  290. continue
  291. }
  292. relay, ok := relayHostInfo.relayState.QueryRelayForByIp(hostinfo.vpnIp)
  293. if !ok {
  294. hostinfo.logger(f.l).
  295. WithField("relayIp", relayHostInfo.vpnIp).
  296. WithField("relayTarget", hostinfo.vpnIp).
  297. Info("sendNoMetrics relay missing object for target")
  298. continue
  299. }
  300. f.SendVia(relayHostInfo, relay, out, nb, fullOut[:header.Len+len(out)], true)
  301. break
  302. }
  303. }
  304. return
  305. }
  306. func isMulticast(ip iputil.VpnIp) bool {
  307. // Class D multicast
  308. if (((ip >> 24) & 0xff) & 0xf0) == 0xe0 {
  309. return true
  310. }
  311. return false
  312. }