connection_manager.go 15 KB

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