connection_manager.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. package nebula
  2. import (
  3. "bytes"
  4. "context"
  5. "sync"
  6. "time"
  7. "github.com/rcrowley/go-metrics"
  8. "github.com/sirupsen/logrus"
  9. "github.com/slackhq/nebula/header"
  10. "github.com/slackhq/nebula/iputil"
  11. "github.com/slackhq/nebula/udp"
  12. )
  13. type trafficDecision int
  14. const (
  15. doNothing trafficDecision = 0
  16. deleteTunnel trafficDecision = 1 // delete the hostinfo on our side, do not notify the remote
  17. closeTunnel trafficDecision = 2 // delete the hostinfo and notify the remote
  18. swapPrimary trafficDecision = 3
  19. migrateRelays trafficDecision = 4
  20. )
  21. type connectionManager struct {
  22. in map[uint32]struct{}
  23. inLock *sync.RWMutex
  24. out map[uint32]struct{}
  25. outLock *sync.RWMutex
  26. // relayUsed holds which relay localIndexs are in use
  27. relayUsed map[uint32]struct{}
  28. relayUsedLock *sync.RWMutex
  29. hostMap *HostMap
  30. trafficTimer *LockingTimerWheel[uint32]
  31. intf *Interface
  32. pendingDeletion map[uint32]struct{}
  33. punchy *Punchy
  34. checkInterval time.Duration
  35. pendingDeletionInterval time.Duration
  36. metricsTxPunchy metrics.Counter
  37. l *logrus.Logger
  38. }
  39. func newConnectionManager(ctx context.Context, l *logrus.Logger, intf *Interface, checkInterval, pendingDeletionInterval time.Duration, punchy *Punchy) *connectionManager {
  40. var max time.Duration
  41. if checkInterval < pendingDeletionInterval {
  42. max = pendingDeletionInterval
  43. } else {
  44. max = checkInterval
  45. }
  46. nc := &connectionManager{
  47. hostMap: intf.hostMap,
  48. in: make(map[uint32]struct{}),
  49. inLock: &sync.RWMutex{},
  50. out: make(map[uint32]struct{}),
  51. outLock: &sync.RWMutex{},
  52. relayUsed: make(map[uint32]struct{}),
  53. relayUsedLock: &sync.RWMutex{},
  54. trafficTimer: NewLockingTimerWheel[uint32](time.Millisecond*500, max),
  55. intf: intf,
  56. pendingDeletion: make(map[uint32]struct{}),
  57. checkInterval: checkInterval,
  58. pendingDeletionInterval: pendingDeletionInterval,
  59. punchy: punchy,
  60. metricsTxPunchy: metrics.GetOrRegisterCounter("messages.tx.punchy", nil),
  61. l: l,
  62. }
  63. nc.Start(ctx)
  64. return nc
  65. }
  66. func (n *connectionManager) In(localIndex uint32) {
  67. n.inLock.RLock()
  68. // If this already exists, return
  69. if _, ok := n.in[localIndex]; ok {
  70. n.inLock.RUnlock()
  71. return
  72. }
  73. n.inLock.RUnlock()
  74. n.inLock.Lock()
  75. n.in[localIndex] = struct{}{}
  76. n.inLock.Unlock()
  77. }
  78. func (n *connectionManager) Out(localIndex uint32) {
  79. n.outLock.RLock()
  80. // If this already exists, return
  81. if _, ok := n.out[localIndex]; ok {
  82. n.outLock.RUnlock()
  83. return
  84. }
  85. n.outLock.RUnlock()
  86. n.outLock.Lock()
  87. n.out[localIndex] = struct{}{}
  88. n.outLock.Unlock()
  89. }
  90. func (n *connectionManager) RelayUsed(localIndex uint32) {
  91. n.relayUsedLock.RLock()
  92. // If this already exists, return
  93. if _, ok := n.relayUsed[localIndex]; ok {
  94. n.relayUsedLock.RUnlock()
  95. return
  96. }
  97. n.relayUsedLock.RUnlock()
  98. n.relayUsedLock.Lock()
  99. n.relayUsed[localIndex] = struct{}{}
  100. n.relayUsedLock.Unlock()
  101. }
  102. // getAndResetTrafficCheck returns if there was any inbound or outbound traffic within the last tick and
  103. // resets the state for this local index
  104. func (n *connectionManager) getAndResetTrafficCheck(localIndex uint32) (bool, bool) {
  105. n.inLock.Lock()
  106. n.outLock.Lock()
  107. _, in := n.in[localIndex]
  108. _, out := n.out[localIndex]
  109. delete(n.in, localIndex)
  110. delete(n.out, localIndex)
  111. n.inLock.Unlock()
  112. n.outLock.Unlock()
  113. return in, out
  114. }
  115. func (n *connectionManager) AddTrafficWatch(localIndex uint32) {
  116. // Use a write lock directly because it should be incredibly rare that we are ever already tracking this index
  117. n.outLock.Lock()
  118. if _, ok := n.out[localIndex]; ok {
  119. n.outLock.Unlock()
  120. return
  121. }
  122. n.out[localIndex] = struct{}{}
  123. n.trafficTimer.Add(localIndex, n.checkInterval)
  124. n.outLock.Unlock()
  125. }
  126. func (n *connectionManager) Start(ctx context.Context) {
  127. go n.Run(ctx)
  128. }
  129. func (n *connectionManager) Run(ctx context.Context) {
  130. //TODO: this tick should be based on the min wheel tick? Check firewall
  131. clockSource := time.NewTicker(500 * time.Millisecond)
  132. defer clockSource.Stop()
  133. p := []byte("")
  134. nb := make([]byte, 12, 12)
  135. out := make([]byte, mtu)
  136. for {
  137. select {
  138. case <-ctx.Done():
  139. return
  140. case now := <-clockSource.C:
  141. n.trafficTimer.Advance(now)
  142. for {
  143. localIndex, has := n.trafficTimer.Purge()
  144. if !has {
  145. break
  146. }
  147. n.doTrafficCheck(localIndex, p, nb, out, now)
  148. }
  149. }
  150. }
  151. }
  152. func (n *connectionManager) doTrafficCheck(localIndex uint32, p, nb, out []byte, now time.Time) {
  153. decision, hostinfo, primary := n.makeTrafficDecision(localIndex, p, nb, out, now)
  154. switch decision {
  155. case deleteTunnel:
  156. n.hostMap.DeleteHostInfo(hostinfo)
  157. case closeTunnel:
  158. n.intf.sendCloseTunnel(hostinfo)
  159. n.intf.closeTunnel(hostinfo)
  160. case swapPrimary:
  161. n.swapPrimary(hostinfo, primary)
  162. case migrateRelays:
  163. n.migrateRelayUsed(hostinfo, primary)
  164. }
  165. n.resetRelayTrafficCheck(hostinfo)
  166. }
  167. func (n *connectionManager) resetRelayTrafficCheck(hostinfo *HostInfo) {
  168. if hostinfo != nil {
  169. n.relayUsedLock.Lock()
  170. defer n.relayUsedLock.Unlock()
  171. // No need to migrate any relays, delete usage info now.
  172. for _, idx := range hostinfo.relayState.CopyRelayForIdxs() {
  173. delete(n.relayUsed, idx)
  174. }
  175. }
  176. }
  177. func (n *connectionManager) migrateRelayUsed(oldhostinfo, newhostinfo *HostInfo) {
  178. relayFor := oldhostinfo.relayState.CopyAllRelayFor()
  179. for _, r := range relayFor {
  180. existing, ok := newhostinfo.relayState.QueryRelayForByIp(r.PeerIp)
  181. var index uint32
  182. var relayFrom iputil.VpnIp
  183. var relayTo iputil.VpnIp
  184. switch {
  185. case ok && existing.State == Established:
  186. // This relay already exists in newhostinfo, then do nothing.
  187. continue
  188. case ok && existing.State == Requested:
  189. // The relay exists in a Requested state; re-send the request
  190. index = existing.LocalIndex
  191. switch r.Type {
  192. case TerminalType:
  193. relayFrom = newhostinfo.vpnIp
  194. relayTo = existing.PeerIp
  195. case ForwardingType:
  196. relayFrom = existing.PeerIp
  197. relayTo = newhostinfo.vpnIp
  198. default:
  199. // should never happen
  200. }
  201. case !ok:
  202. n.relayUsedLock.RLock()
  203. if _, relayUsed := n.relayUsed[r.LocalIndex]; !relayUsed {
  204. // The relay hasn't been used; don't migrate it.
  205. n.relayUsedLock.RUnlock()
  206. continue
  207. }
  208. n.relayUsedLock.RUnlock()
  209. // The relay doesn't exist at all; create some relay state and send the request.
  210. var err error
  211. index, err = AddRelay(n.l, newhostinfo, n.hostMap, r.PeerIp, nil, r.Type, Requested)
  212. if err != nil {
  213. n.l.WithError(err).Error("failed to migrate relay to new hostinfo")
  214. continue
  215. }
  216. switch r.Type {
  217. case TerminalType:
  218. relayFrom = newhostinfo.vpnIp
  219. relayTo = r.PeerIp
  220. case ForwardingType:
  221. relayFrom = r.PeerIp
  222. relayTo = newhostinfo.vpnIp
  223. default:
  224. // should never happen
  225. }
  226. }
  227. // Send a CreateRelayRequest to the peer.
  228. req := NebulaControl{
  229. Type: NebulaControl_CreateRelayRequest,
  230. InitiatorRelayIndex: index,
  231. RelayFromIp: uint32(relayFrom),
  232. RelayToIp: uint32(relayTo),
  233. }
  234. msg, err := req.Marshal()
  235. if err != nil {
  236. n.l.WithError(err).Error("failed to marshal Control message to migrate relay")
  237. } else {
  238. n.intf.SendMessageToHostInfo(header.Control, 0, newhostinfo, msg, make([]byte, 12), make([]byte, mtu))
  239. n.l.WithFields(logrus.Fields{
  240. "relayFrom": iputil.VpnIp(req.RelayFromIp),
  241. "relayTo": iputil.VpnIp(req.RelayToIp),
  242. "initiatorRelayIndex": req.InitiatorRelayIndex,
  243. "responderRelayIndex": req.ResponderRelayIndex,
  244. "vpnIp": newhostinfo.vpnIp}).
  245. Info("send CreateRelayRequest")
  246. }
  247. }
  248. }
  249. func (n *connectionManager) makeTrafficDecision(localIndex uint32, p, nb, out []byte, now time.Time) (trafficDecision, *HostInfo, *HostInfo) {
  250. n.hostMap.RLock()
  251. defer n.hostMap.RUnlock()
  252. hostinfo := n.hostMap.Indexes[localIndex]
  253. if hostinfo == nil {
  254. n.l.WithField("localIndex", localIndex).Debugf("Not found in hostmap")
  255. delete(n.pendingDeletion, localIndex)
  256. return doNothing, nil, nil
  257. }
  258. if n.isInvalidCertificate(now, hostinfo) {
  259. delete(n.pendingDeletion, hostinfo.localIndexId)
  260. return closeTunnel, hostinfo, nil
  261. }
  262. primary := n.hostMap.Hosts[hostinfo.vpnIp]
  263. mainHostInfo := true
  264. if primary != nil && primary != hostinfo {
  265. mainHostInfo = false
  266. }
  267. // Check for traffic on this hostinfo
  268. inTraffic, outTraffic := n.getAndResetTrafficCheck(localIndex)
  269. // A hostinfo is determined alive if there is incoming traffic
  270. if inTraffic {
  271. decision := doNothing
  272. if n.l.Level >= logrus.DebugLevel {
  273. hostinfo.logger(n.l).
  274. WithField("tunnelCheck", m{"state": "alive", "method": "passive"}).
  275. Debug("Tunnel status")
  276. }
  277. delete(n.pendingDeletion, hostinfo.localIndexId)
  278. if mainHostInfo {
  279. n.tryRehandshake(hostinfo)
  280. } else {
  281. if n.shouldSwapPrimary(hostinfo, primary) {
  282. decision = swapPrimary
  283. } else {
  284. // migrate the relays to the primary, if in use.
  285. decision = migrateRelays
  286. }
  287. }
  288. n.trafficTimer.Add(hostinfo.localIndexId, n.checkInterval)
  289. if !outTraffic {
  290. // Send a punch packet to keep the NAT state alive
  291. n.sendPunch(hostinfo)
  292. }
  293. return decision, hostinfo, primary
  294. }
  295. if _, ok := n.pendingDeletion[hostinfo.localIndexId]; ok {
  296. // We have already sent a test packet and nothing was returned, this hostinfo is dead
  297. hostinfo.logger(n.l).
  298. WithField("tunnelCheck", m{"state": "dead", "method": "active"}).
  299. Info("Tunnel status")
  300. delete(n.pendingDeletion, hostinfo.localIndexId)
  301. return deleteTunnel, hostinfo, nil
  302. }
  303. if hostinfo != nil && hostinfo.ConnectionState != nil && mainHostInfo {
  304. if !outTraffic {
  305. // If we aren't sending or receiving traffic then its an unused tunnel and we don't to test the tunnel.
  306. // Just maintain NAT state if configured to do so.
  307. n.sendPunch(hostinfo)
  308. n.trafficTimer.Add(hostinfo.localIndexId, n.checkInterval)
  309. return doNothing, nil, nil
  310. }
  311. if n.punchy.GetTargetEverything() {
  312. // This is similar to the old punchy behavior with a slight optimization.
  313. // We aren't receiving traffic but we are sending it, punch on all known
  314. // ips in case we need to re-prime NAT state
  315. n.sendPunch(hostinfo)
  316. }
  317. if n.intf.lightHouse.IsLighthouseIP(hostinfo.vpnIp) {
  318. // We are sending traffic to the lighthouse, let recv_error sort out any issues instead of testing the tunnel
  319. n.trafficTimer.Add(hostinfo.localIndexId, n.checkInterval)
  320. return doNothing, nil, nil
  321. }
  322. if n.l.Level >= logrus.DebugLevel {
  323. hostinfo.logger(n.l).
  324. WithField("tunnelCheck", m{"state": "testing", "method": "active"}).
  325. Debug("Tunnel status")
  326. }
  327. // Send a test packet to trigger an authenticated tunnel test, this should suss out any lingering tunnel issues
  328. n.intf.SendMessageToHostInfo(header.Test, header.TestRequest, hostinfo, p, nb, out)
  329. } else {
  330. if n.l.Level >= logrus.DebugLevel {
  331. hostinfo.logger(n.l).Debugf("Hostinfo sadness")
  332. }
  333. }
  334. n.pendingDeletion[hostinfo.localIndexId] = struct{}{}
  335. n.trafficTimer.Add(hostinfo.localIndexId, n.pendingDeletionInterval)
  336. return doNothing, nil, nil
  337. }
  338. func (n *connectionManager) shouldSwapPrimary(current, primary *HostInfo) bool {
  339. // The primary tunnel is the most recent handshake to complete locally and should work entirely fine.
  340. // If we are here then we have multiple tunnels for a host pair and neither side believes the same tunnel is primary.
  341. // Let's sort this out.
  342. if current.vpnIp < n.intf.myVpnIp {
  343. // Only one side should flip primary because if both flip then we may never resolve to a single tunnel.
  344. // vpn ip is static across all tunnels for this host pair so lets use that to determine who is flipping.
  345. // The remotes vpn ip is lower than mine. I will not flip.
  346. return false
  347. }
  348. certState := n.intf.certState.Load()
  349. return bytes.Equal(current.ConnectionState.certState.certificate.Signature, certState.certificate.Signature)
  350. }
  351. func (n *connectionManager) swapPrimary(current, primary *HostInfo) {
  352. n.hostMap.Lock()
  353. // Make sure the primary is still the same after the write lock. This avoids a race with a rehandshake.
  354. if n.hostMap.Hosts[current.vpnIp] == primary {
  355. n.hostMap.unlockedMakePrimary(current)
  356. }
  357. n.hostMap.Unlock()
  358. }
  359. // isInvalidCertificate will check if we should destroy a tunnel if pki.disconnect_invalid is true and
  360. // the certificate is no longer valid
  361. func (n *connectionManager) isInvalidCertificate(now time.Time, hostinfo *HostInfo) bool {
  362. if !n.intf.disconnectInvalid {
  363. return false
  364. }
  365. remoteCert := hostinfo.GetCert()
  366. if remoteCert == nil {
  367. return false
  368. }
  369. valid, err := remoteCert.Verify(now, n.intf.caPool)
  370. if valid {
  371. return false
  372. }
  373. fingerprint, _ := remoteCert.Sha256Sum()
  374. hostinfo.logger(n.l).WithError(err).
  375. WithField("fingerprint", fingerprint).
  376. Info("Remote certificate is no longer valid, tearing down the tunnel")
  377. return true
  378. }
  379. func (n *connectionManager) sendPunch(hostinfo *HostInfo) {
  380. if !n.punchy.GetPunch() {
  381. // Punching is disabled
  382. return
  383. }
  384. if n.punchy.GetTargetEverything() {
  385. hostinfo.remotes.ForEach(n.hostMap.preferredRanges, func(addr *udp.Addr, preferred bool) {
  386. n.metricsTxPunchy.Inc(1)
  387. n.intf.outside.WriteTo([]byte{1}, addr)
  388. })
  389. } else if hostinfo.remote != nil {
  390. n.metricsTxPunchy.Inc(1)
  391. n.intf.outside.WriteTo([]byte{1}, hostinfo.remote)
  392. }
  393. }
  394. func (n *connectionManager) tryRehandshake(hostinfo *HostInfo) {
  395. certState := n.intf.certState.Load()
  396. if bytes.Equal(hostinfo.ConnectionState.certState.certificate.Signature, certState.certificate.Signature) {
  397. return
  398. }
  399. n.l.WithField("vpnIp", hostinfo.vpnIp).
  400. WithField("reason", "local certificate is not current").
  401. Info("Re-handshaking with remote")
  402. //TODO: this is copied from getOrHandshake to keep the extra checks out of the hot path, figure it out
  403. newHostinfo := n.intf.handshakeManager.AddVpnIp(hostinfo.vpnIp, n.intf.initHostInfo)
  404. if !newHostinfo.HandshakeReady {
  405. ixHandshakeStage0(n.intf, newHostinfo.vpnIp, newHostinfo)
  406. }
  407. //If this is a static host, we don't need to wait for the HostQueryReply
  408. //We can trigger the handshake right now
  409. if _, ok := n.intf.lightHouse.GetStaticHostList()[hostinfo.vpnIp]; ok {
  410. select {
  411. case n.intf.handshakeManager.trigger <- hostinfo.vpnIp:
  412. default:
  413. }
  414. }
  415. }