inside.go 7.5 KB

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