inside.go 13 KB

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