inside.go 13 KB

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