inside.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. package nebula
  2. import (
  3. "sync/atomic"
  4. "github.com/flynn/noise"
  5. "github.com/sirupsen/logrus"
  6. "github.com/slackhq/nebula/firewall"
  7. "github.com/slackhq/nebula/header"
  8. "github.com/slackhq/nebula/iputil"
  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. f.l.WithField("packet", packet).Debugf("Error while validating outbound packet: %s", err)
  15. return
  16. }
  17. // Ignore local broadcast packets
  18. if f.dropLocalBroadcast && fwPacket.RemoteIP == f.localBroadcast {
  19. return
  20. }
  21. // Ignore packets from self to self
  22. if fwPacket.RemoteIP == f.myVpnIp {
  23. return
  24. }
  25. // Ignore broadcast packets
  26. if f.dropMulticast && isMulticast(fwPacket.RemoteIP) {
  27. return
  28. }
  29. hostinfo := f.getOrHandshake(fwPacket.RemoteIP)
  30. if hostinfo == nil {
  31. if f.l.Level >= logrus.DebugLevel {
  32. f.l.WithField("vpnIp", fwPacket.RemoteIP).
  33. WithField("fwPacket", fwPacket).
  34. Debugln("dropping outbound packet, vpnIp not in our CIDR or in unsafe routes")
  35. }
  36. return
  37. }
  38. ci := hostinfo.ConnectionState
  39. if ci.ready == false {
  40. // Because we might be sending stored packets, lock here to stop new things going to
  41. // the packet queue.
  42. ci.queueLock.Lock()
  43. if !ci.ready {
  44. hostinfo.cachePacket(f.l, header.Message, 0, packet, f.sendMessageNow, f.cachedPacketMetrics)
  45. ci.queueLock.Unlock()
  46. return
  47. }
  48. ci.queueLock.Unlock()
  49. }
  50. dropReason := f.firewall.Drop(packet, *fwPacket, false, hostinfo, f.caPool, localCache)
  51. if dropReason == nil {
  52. f.sendNoMetrics(header.Message, 0, ci, hostinfo, hostinfo.remote, packet, nb, out, q)
  53. } else if f.l.Level >= logrus.DebugLevel {
  54. hostinfo.logger(f.l).
  55. WithField("fwPacket", fwPacket).
  56. WithField("reason", dropReason).
  57. Debugln("dropping outbound packet")
  58. }
  59. }
  60. // getOrHandshake returns nil if the vpnIp is not routable
  61. func (f *Interface) getOrHandshake(vpnIp iputil.VpnIp) *HostInfo {
  62. //TODO: we can find contains without converting back to bytes
  63. if f.hostMap.vpnCIDR.Contains(vpnIp.ToIP()) == false {
  64. vpnIp = f.hostMap.queryUnsafeRoute(vpnIp)
  65. if vpnIp == 0 {
  66. return nil
  67. }
  68. }
  69. hostinfo, err := f.hostMap.PromoteBestQueryVpnIp(vpnIp, f)
  70. //if err != nil || hostinfo.ConnectionState == nil {
  71. if err != nil {
  72. hostinfo, err = f.handshakeManager.pendingHostMap.QueryVpnIp(vpnIp)
  73. if err != nil {
  74. hostinfo = f.handshakeManager.AddVpnIp(vpnIp)
  75. }
  76. }
  77. ci := hostinfo.ConnectionState
  78. if ci != nil && ci.eKey != nil && ci.ready {
  79. return hostinfo
  80. }
  81. // Handshake is not ready, we need to grab the lock now before we start the handshake process
  82. hostinfo.Lock()
  83. defer hostinfo.Unlock()
  84. // Double check, now that we have the lock
  85. ci = hostinfo.ConnectionState
  86. if ci != nil && ci.eKey != nil && ci.ready {
  87. return hostinfo
  88. }
  89. if ci == nil {
  90. // if we don't have a connection state, then send a handshake initiation
  91. ci = f.newConnectionState(f.l, true, noise.HandshakeIX, []byte{}, 0)
  92. // FIXME: Maybe make XX selectable, but probably not since psk makes it nearly pointless for us.
  93. //ci = f.newConnectionState(true, noise.HandshakeXX, []byte{}, 0)
  94. hostinfo.ConnectionState = ci
  95. } else if ci.eKey == nil {
  96. // if we don't have any state at all, create it
  97. }
  98. // If we have already created the handshake packet, we don't want to call the function at all.
  99. if !hostinfo.HandshakeReady {
  100. ixHandshakeStage0(f, vpnIp, hostinfo)
  101. // FIXME: Maybe make XX selectable, but probably not since psk makes it nearly pointless for us.
  102. //xx_handshakeStage0(f, ip, hostinfo)
  103. // If this is a static host, we don't need to wait for the HostQueryReply
  104. // We can trigger the handshake right now
  105. if _, ok := f.lightHouse.staticList[vpnIp]; ok {
  106. select {
  107. case f.handshakeManager.trigger <- vpnIp:
  108. default:
  109. }
  110. }
  111. }
  112. return hostinfo
  113. }
  114. func (f *Interface) sendMessageNow(t header.MessageType, st header.MessageSubType, hostInfo *HostInfo, p, nb, out []byte) {
  115. fp := &firewall.Packet{}
  116. err := newPacket(p, false, fp)
  117. if err != nil {
  118. f.l.Warnf("error while parsing outgoing packet for firewall check; %v", err)
  119. return
  120. }
  121. // check if packet is in outbound fw rules
  122. dropReason := f.firewall.Drop(p, *fp, false, hostInfo, f.caPool, nil)
  123. if dropReason != nil {
  124. if f.l.Level >= logrus.DebugLevel {
  125. f.l.WithField("fwPacket", fp).
  126. WithField("reason", dropReason).
  127. Debugln("dropping cached packet")
  128. }
  129. return
  130. }
  131. f.sendNoMetrics(header.Message, st, hostInfo.ConnectionState, hostInfo, hostInfo.remote, p, nb, out, 0)
  132. }
  133. // SendMessageToVpnIp handles real ip:port lookup and sends to the current best known address for vpnIp
  134. func (f *Interface) SendMessageToVpnIp(t header.MessageType, st header.MessageSubType, vpnIp iputil.VpnIp, p, nb, out []byte) {
  135. hostInfo := f.getOrHandshake(vpnIp)
  136. if hostInfo == nil {
  137. if f.l.Level >= logrus.DebugLevel {
  138. f.l.WithField("vpnIp", vpnIp).
  139. Debugln("dropping SendMessageToVpnIp, vpnIp not in our CIDR or in unsafe routes")
  140. }
  141. return
  142. }
  143. if !hostInfo.ConnectionState.ready {
  144. // Because we might be sending stored packets, lock here to stop new things going to
  145. // the packet queue.
  146. hostInfo.ConnectionState.queueLock.Lock()
  147. if !hostInfo.ConnectionState.ready {
  148. hostInfo.cachePacket(f.l, t, st, p, f.sendMessageToVpnIp, f.cachedPacketMetrics)
  149. hostInfo.ConnectionState.queueLock.Unlock()
  150. return
  151. }
  152. hostInfo.ConnectionState.queueLock.Unlock()
  153. }
  154. f.sendMessageToVpnIp(t, st, hostInfo, p, nb, out)
  155. return
  156. }
  157. func (f *Interface) sendMessageToVpnIp(t header.MessageType, st header.MessageSubType, hostInfo *HostInfo, p, nb, out []byte) {
  158. f.send(t, st, hostInfo.ConnectionState, hostInfo, hostInfo.remote, p, nb, out)
  159. }
  160. func (f *Interface) send(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote *udp.Addr, p, nb, out []byte) {
  161. f.messageMetrics.Tx(t, st, 1)
  162. f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out, 0)
  163. }
  164. func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote *udp.Addr, p, nb, out []byte, q int) {
  165. if ci.eKey == nil {
  166. //TODO: log warning
  167. return
  168. }
  169. var err error
  170. //TODO: enable if we do more than 1 tun queue
  171. //ci.writeLock.Lock()
  172. c := atomic.AddUint64(&ci.atomicMessageCounter, 1)
  173. //l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
  174. out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
  175. f.connectionManager.Out(hostinfo.vpnIp)
  176. // Query our LH if we haven't since the last time we've been rebound, this will cause the remote to punch against
  177. // all our IPs and enable a faster roaming.
  178. if t != header.CloseTunnel && hostinfo.lastRebindCount != f.rebindCount {
  179. //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
  180. // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
  181. f.lightHouse.QueryServer(hostinfo.vpnIp, f)
  182. hostinfo.lastRebindCount = f.rebindCount
  183. if f.l.Level >= logrus.DebugLevel {
  184. f.l.WithField("vpnIp", hostinfo.vpnIp).Debug("Lighthouse update triggered for punch due to rebind counter")
  185. }
  186. }
  187. out, err = ci.eKey.EncryptDanger(out, out, p, c, nb)
  188. //TODO: see above note on lock
  189. //ci.writeLock.Unlock()
  190. if err != nil {
  191. hostinfo.logger(f.l).WithError(err).
  192. WithField("udpAddr", remote).WithField("counter", c).
  193. WithField("attemptedCounter", c).
  194. Error("Failed to encrypt outgoing packet")
  195. return
  196. }
  197. err = f.writers[q].WriteTo(out, remote)
  198. if err != nil {
  199. hostinfo.logger(f.l).WithError(err).
  200. WithField("udpAddr", remote).Error("Failed to write outgoing packet")
  201. }
  202. return
  203. }
  204. func isMulticast(ip iputil.VpnIp) bool {
  205. // Class D multicast
  206. if (((ip >> 24) & 0xff) & 0xf0) == 0xe0 {
  207. return true
  208. }
  209. return false
  210. }