inside.go 13 KB

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