inside.go 8.8 KB

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