connection_manager.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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.DeleteVpnIp(hostinfo.vpnIp)
  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.PeerIp)
  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 relayed connection exists in a Requested state; re-send the request
  203. index = existing.LocalIndex
  204. switch r.Type {
  205. case TerminalType:
  206. relayFrom = n.intf.myVpnNet.Addr()
  207. relayTo = existing.PeerIp
  208. case ForwardingType:
  209. relayFrom = existing.PeerIp
  210. relayTo = newhostinfo.vpnIp
  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.PeerIp, 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.myVpnNet.Addr()
  234. relayTo = r.PeerIp
  235. case ForwardingType:
  236. relayFrom = r.PeerIp
  237. relayTo = newhostinfo.vpnIp
  238. default:
  239. // should never happen
  240. panic(fmt.Sprintf("Migrating unknown relay type: %v", r.Type))
  241. }
  242. }
  243. //TODO: IPV6-WORK
  244. relayFromB := relayFrom.As4()
  245. relayToB := relayTo.As4()
  246. // Send a CreateRelayRequest to the peer.
  247. req := NebulaControl{
  248. Type: NebulaControl_CreateRelayRequest,
  249. InitiatorRelayIndex: index,
  250. RelayFromIp: binary.BigEndian.Uint32(relayFromB[:]),
  251. RelayToIp: binary.BigEndian.Uint32(relayToB[:]),
  252. }
  253. msg, err := req.Marshal()
  254. if err != nil {
  255. n.l.WithError(err).Error("failed to marshal Control message to migrate relay")
  256. } else {
  257. n.intf.SendMessageToHostInfo(header.Control, 0, newhostinfo, msg, make([]byte, 12), make([]byte, mtu))
  258. n.l.WithFields(logrus.Fields{
  259. "relayFrom": req.RelayFromIp,
  260. "relayTo": req.RelayToIp,
  261. "initiatorRelayIndex": req.InitiatorRelayIndex,
  262. "responderRelayIndex": req.ResponderRelayIndex,
  263. "vpnIp": newhostinfo.vpnIp}).
  264. Info("send CreateRelayRequest")
  265. }
  266. }
  267. }
  268. func (n *connectionManager) makeTrafficDecision(localIndex uint32, now time.Time) (trafficDecision, *HostInfo, *HostInfo) {
  269. n.hostMap.RLock()
  270. defer n.hostMap.RUnlock()
  271. hostinfo := n.hostMap.Indexes[localIndex]
  272. if hostinfo == nil {
  273. n.l.WithField("localIndex", localIndex).Debugf("Not found in hostmap")
  274. delete(n.pendingDeletion, localIndex)
  275. return doNothing, nil, nil
  276. }
  277. if n.isInvalidCertificate(now, hostinfo) {
  278. delete(n.pendingDeletion, hostinfo.localIndexId)
  279. return closeTunnel, hostinfo, nil
  280. }
  281. primary := n.hostMap.Hosts[hostinfo.vpnIp]
  282. mainHostInfo := true
  283. if primary != nil && primary != hostinfo {
  284. mainHostInfo = false
  285. }
  286. // Check for traffic on this hostinfo
  287. inTraffic, outTraffic := n.getAndResetTrafficCheck(localIndex)
  288. // A hostinfo is determined alive if there is incoming traffic
  289. if inTraffic {
  290. decision := doNothing
  291. if n.l.Level >= logrus.DebugLevel {
  292. hostinfo.logger(n.l).
  293. WithField("tunnelCheck", m{"state": "alive", "method": "passive"}).
  294. Debug("Tunnel status")
  295. }
  296. delete(n.pendingDeletion, hostinfo.localIndexId)
  297. if mainHostInfo {
  298. decision = tryRehandshake
  299. } else {
  300. if n.shouldSwapPrimary(hostinfo, primary) {
  301. decision = swapPrimary
  302. } else {
  303. // migrate the relays to the primary, if in use.
  304. decision = migrateRelays
  305. }
  306. }
  307. n.trafficTimer.Add(hostinfo.localIndexId, n.checkInterval)
  308. if !outTraffic {
  309. // Send a punch packet to keep the NAT state alive
  310. n.sendPunch(hostinfo)
  311. }
  312. return decision, hostinfo, primary
  313. }
  314. if _, ok := n.pendingDeletion[hostinfo.localIndexId]; ok {
  315. // We have already sent a test packet and nothing was returned, this hostinfo is dead
  316. hostinfo.logger(n.l).
  317. WithField("tunnelCheck", m{"state": "dead", "method": "active"}).
  318. Info("Tunnel status")
  319. delete(n.pendingDeletion, hostinfo.localIndexId)
  320. return deleteTunnel, hostinfo, nil
  321. }
  322. decision := doNothing
  323. if hostinfo != nil && hostinfo.ConnectionState != nil && mainHostInfo {
  324. if !outTraffic {
  325. // If we aren't sending or receiving traffic then its an unused tunnel and we don't to test the tunnel.
  326. // Just maintain NAT state if configured to do so.
  327. n.sendPunch(hostinfo)
  328. n.trafficTimer.Add(hostinfo.localIndexId, n.checkInterval)
  329. return doNothing, nil, nil
  330. }
  331. if n.punchy.GetTargetEverything() {
  332. // This is similar to the old punchy behavior with a slight optimization.
  333. // We aren't receiving traffic but we are sending it, punch on all known
  334. // ips in case we need to re-prime NAT state
  335. n.sendPunch(hostinfo)
  336. }
  337. if n.l.Level >= logrus.DebugLevel {
  338. hostinfo.logger(n.l).
  339. WithField("tunnelCheck", m{"state": "testing", "method": "active"}).
  340. Debug("Tunnel status")
  341. }
  342. // Send a test packet to trigger an authenticated tunnel test, this should suss out any lingering tunnel issues
  343. decision = sendTestPacket
  344. } else {
  345. if n.l.Level >= logrus.DebugLevel {
  346. hostinfo.logger(n.l).Debugf("Hostinfo sadness")
  347. }
  348. }
  349. n.pendingDeletion[hostinfo.localIndexId] = struct{}{}
  350. n.trafficTimer.Add(hostinfo.localIndexId, n.pendingDeletionInterval)
  351. return decision, hostinfo, nil
  352. }
  353. func (n *connectionManager) shouldSwapPrimary(current, primary *HostInfo) bool {
  354. // The primary tunnel is the most recent handshake to complete locally and should work entirely fine.
  355. // If we are here then we have multiple tunnels for a host pair and neither side believes the same tunnel is primary.
  356. // Let's sort this out.
  357. if current.vpnIp.Compare(n.intf.myVpnNet.Addr()) < 0 {
  358. // Only one side should flip primary because if both flip then we may never resolve to a single tunnel.
  359. // vpn ip is static across all tunnels for this host pair so lets use that to determine who is flipping.
  360. // The remotes vpn ip is lower than mine. I will not flip.
  361. return false
  362. }
  363. certState := n.intf.pki.GetCertState()
  364. return bytes.Equal(current.ConnectionState.myCert.Signature, certState.Certificate.Signature)
  365. }
  366. func (n *connectionManager) swapPrimary(current, primary *HostInfo) {
  367. n.hostMap.Lock()
  368. // Make sure the primary is still the same after the write lock. This avoids a race with a rehandshake.
  369. if n.hostMap.Hosts[current.vpnIp] == primary {
  370. n.hostMap.unlockedMakePrimary(current)
  371. }
  372. n.hostMap.Unlock()
  373. }
  374. // isInvalidCertificate will check if we should destroy a tunnel if pki.disconnect_invalid is true and
  375. // the certificate is no longer valid. Block listed certificates will skip the pki.disconnect_invalid
  376. // check and return true.
  377. func (n *connectionManager) isInvalidCertificate(now time.Time, hostinfo *HostInfo) bool {
  378. remoteCert := hostinfo.GetCert()
  379. if remoteCert == nil {
  380. return false
  381. }
  382. valid, err := remoteCert.VerifyWithCache(now, n.intf.pki.GetCAPool())
  383. if valid {
  384. return false
  385. }
  386. if !n.intf.disconnectInvalid.Load() && err != cert.ErrBlockListed {
  387. // Block listed certificates should always be disconnected
  388. return false
  389. }
  390. fingerprint, _ := remoteCert.Sha256Sum()
  391. hostinfo.logger(n.l).WithError(err).
  392. WithField("fingerprint", fingerprint).
  393. Info("Remote certificate is no longer valid, tearing down the tunnel")
  394. return true
  395. }
  396. func (n *connectionManager) sendPunch(hostinfo *HostInfo) {
  397. if !n.punchy.GetPunch() {
  398. // Punching is disabled
  399. return
  400. }
  401. if n.punchy.GetTargetEverything() {
  402. hostinfo.remotes.ForEach(n.hostMap.GetPreferredRanges(), func(addr netip.AddrPort, preferred bool) {
  403. n.metricsTxPunchy.Inc(1)
  404. n.intf.outside.WriteTo([]byte{1}, addr)
  405. })
  406. } else if hostinfo.remote.IsValid() {
  407. n.metricsTxPunchy.Inc(1)
  408. n.intf.outside.WriteTo([]byte{1}, hostinfo.remote)
  409. }
  410. }
  411. func (n *connectionManager) tryRehandshake(hostinfo *HostInfo) {
  412. certState := n.intf.pki.GetCertState()
  413. if bytes.Equal(hostinfo.ConnectionState.myCert.Signature, certState.Certificate.Signature) {
  414. return
  415. }
  416. n.l.WithField("vpnIp", hostinfo.vpnIp).
  417. WithField("reason", "local certificate is not current").
  418. Info("Re-handshaking with remote")
  419. n.intf.handshakeManager.StartHandshake(hostinfo.vpnIp, nil)
  420. }