inside.go 13 KB

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