handshake_manager.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. package nebula
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/rand"
  6. "encoding/binary"
  7. "errors"
  8. "net"
  9. "time"
  10. "github.com/rcrowley/go-metrics"
  11. "github.com/sirupsen/logrus"
  12. "github.com/slackhq/nebula/header"
  13. "github.com/slackhq/nebula/iputil"
  14. "github.com/slackhq/nebula/udp"
  15. )
  16. const (
  17. DefaultHandshakeTryInterval = time.Millisecond * 100
  18. DefaultHandshakeRetries = 10
  19. DefaultHandshakeTriggerBuffer = 64
  20. DefaultUseRelays = true
  21. )
  22. var (
  23. defaultHandshakeConfig = HandshakeConfig{
  24. tryInterval: DefaultHandshakeTryInterval,
  25. retries: DefaultHandshakeRetries,
  26. triggerBuffer: DefaultHandshakeTriggerBuffer,
  27. useRelays: DefaultUseRelays,
  28. }
  29. )
  30. type HandshakeConfig struct {
  31. tryInterval time.Duration
  32. retries int
  33. triggerBuffer int
  34. useRelays bool
  35. messageMetrics *MessageMetrics
  36. }
  37. type HandshakeManager struct {
  38. pendingHostMap *HostMap
  39. mainHostMap *HostMap
  40. lightHouse *LightHouse
  41. outside *udp.Conn
  42. config HandshakeConfig
  43. OutboundHandshakeTimer *LockingTimerWheel[iputil.VpnIp]
  44. messageMetrics *MessageMetrics
  45. metricInitiated metrics.Counter
  46. metricTimedOut metrics.Counter
  47. l *logrus.Logger
  48. // vpnIps is another map similar to the pending hostmap but tracks entries in the wheel instead
  49. // this is to avoid situations where the same vpn ip enters the wheel and causes rapid fire handshaking
  50. vpnIps map[iputil.VpnIp]struct{}
  51. // can be used to trigger outbound handshake for the given vpnIp
  52. trigger chan iputil.VpnIp
  53. }
  54. func NewHandshakeManager(l *logrus.Logger, tunCidr *net.IPNet, preferredRanges []*net.IPNet, mainHostMap *HostMap, lightHouse *LightHouse, outside *udp.Conn, config HandshakeConfig) *HandshakeManager {
  55. return &HandshakeManager{
  56. pendingHostMap: NewHostMap(l, "pending", tunCidr, preferredRanges),
  57. mainHostMap: mainHostMap,
  58. lightHouse: lightHouse,
  59. outside: outside,
  60. config: config,
  61. trigger: make(chan iputil.VpnIp, config.triggerBuffer),
  62. OutboundHandshakeTimer: NewLockingTimerWheel[iputil.VpnIp](config.tryInterval, hsTimeout(config.retries, config.tryInterval)),
  63. vpnIps: map[iputil.VpnIp]struct{}{},
  64. messageMetrics: config.messageMetrics,
  65. metricInitiated: metrics.GetOrRegisterCounter("handshake_manager.initiated", nil),
  66. metricTimedOut: metrics.GetOrRegisterCounter("handshake_manager.timed_out", nil),
  67. l: l,
  68. }
  69. }
  70. func (c *HandshakeManager) Run(ctx context.Context, f udp.EncWriter) {
  71. clockSource := time.NewTicker(c.config.tryInterval)
  72. defer clockSource.Stop()
  73. for {
  74. select {
  75. case <-ctx.Done():
  76. return
  77. case vpnIP := <-c.trigger:
  78. c.handleOutbound(vpnIP, f, true)
  79. case now := <-clockSource.C:
  80. c.NextOutboundHandshakeTimerTick(now, f)
  81. }
  82. }
  83. }
  84. func (c *HandshakeManager) NextOutboundHandshakeTimerTick(now time.Time, f udp.EncWriter) {
  85. c.OutboundHandshakeTimer.Advance(now)
  86. for {
  87. vpnIp, has := c.OutboundHandshakeTimer.Purge()
  88. if !has {
  89. break
  90. }
  91. c.handleOutbound(vpnIp, f, false)
  92. }
  93. }
  94. func (c *HandshakeManager) handleOutbound(vpnIp iputil.VpnIp, f udp.EncWriter, lighthouseTriggered bool) {
  95. hostinfo, err := c.pendingHostMap.QueryVpnIp(vpnIp)
  96. if err != nil {
  97. delete(c.vpnIps, vpnIp)
  98. return
  99. }
  100. hostinfo.Lock()
  101. defer hostinfo.Unlock()
  102. // We may have raced to completion but now that we have a lock we should ensure we have not yet completed.
  103. if hostinfo.HandshakeComplete {
  104. // Ensure we don't exist in the pending hostmap anymore since we have completed
  105. c.pendingHostMap.DeleteHostInfo(hostinfo)
  106. return
  107. }
  108. // Check if we have a handshake packet to transmit yet
  109. if !hostinfo.HandshakeReady {
  110. // There is currently a slight race in getOrHandshake due to ConnectionState not being part of the HostInfo directly
  111. // Our hostinfo here was added to the pending map and the wheel may have ticked to us before we created ConnectionState
  112. c.OutboundHandshakeTimer.Add(vpnIp, c.config.tryInterval*time.Duration(hostinfo.HandshakeCounter))
  113. return
  114. }
  115. // If we are out of time, clean up
  116. if hostinfo.HandshakeCounter >= c.config.retries {
  117. hostinfo.logger(c.l).WithField("udpAddrs", hostinfo.remotes.CopyAddrs(c.pendingHostMap.preferredRanges)).
  118. WithField("initiatorIndex", hostinfo.localIndexId).
  119. WithField("remoteIndex", hostinfo.remoteIndexId).
  120. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  121. WithField("durationNs", time.Since(hostinfo.handshakeStart).Nanoseconds()).
  122. Info("Handshake timed out")
  123. c.metricTimedOut.Inc(1)
  124. c.pendingHostMap.DeleteHostInfo(hostinfo)
  125. return
  126. }
  127. // Get a remotes object if we don't already have one.
  128. // This is mainly to protect us as this should never be the case
  129. // NB ^ This comment doesn't jive. It's how the thing gets initialized.
  130. // It's the common path. Should it update every time, in case a future LH query/queries give us more info?
  131. if hostinfo.remotes == nil {
  132. hostinfo.remotes = c.lightHouse.QueryCache(vpnIp)
  133. }
  134. remotes := hostinfo.remotes.CopyAddrs(c.pendingHostMap.preferredRanges)
  135. remotesHaveChanged := !udp.AddrSlice(remotes).Equal(hostinfo.HandshakeLastRemotes)
  136. // We only care about a lighthouse trigger if we have new remotes to send to.
  137. // This is a very specific optimization for a fast lighthouse reply.
  138. if lighthouseTriggered && !remotesHaveChanged {
  139. // If we didn't return here a lighthouse could cause us to aggressively send handshakes
  140. return
  141. }
  142. hostinfo.HandshakeLastRemotes = remotes
  143. // TODO: this will generate a load of queries for hosts with only 1 ip
  144. // (such as ones registered to the lighthouse with only a private IP)
  145. // So we only do it one time after attempting 5 handshakes already.
  146. if len(remotes) <= 1 && hostinfo.HandshakeCounter == 5 {
  147. // If we only have 1 remote it is highly likely our query raced with the other host registered within the lighthouse
  148. // Our vpnIp here has a tunnel with a lighthouse but has yet to send a host update packet there so we only know about
  149. // the learned public ip for them. Query again to short circuit the promotion counter
  150. c.lightHouse.QueryServer(vpnIp, f)
  151. }
  152. // Send the handshake to all known ips, stage 2 takes care of assigning the hostinfo.remote based on the first to reply
  153. var sentTo []*udp.Addr
  154. hostinfo.remotes.ForEach(c.pendingHostMap.preferredRanges, func(addr *udp.Addr, _ bool) {
  155. c.messageMetrics.Tx(header.Handshake, header.MessageSubType(hostinfo.HandshakePacket[0][1]), 1)
  156. err = c.outside.WriteTo(hostinfo.HandshakePacket[0], addr)
  157. if err != nil {
  158. hostinfo.logger(c.l).WithField("udpAddr", addr).
  159. WithField("initiatorIndex", hostinfo.localIndexId).
  160. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  161. WithError(err).Error("Failed to send handshake message")
  162. } else {
  163. sentTo = append(sentTo, addr)
  164. }
  165. })
  166. // Don't be too noisy or confusing if we fail to send a handshake - if we don't get through we'll eventually log a timeout,
  167. // so only log when the list of remotes has changed
  168. if remotesHaveChanged {
  169. hostinfo.logger(c.l).WithField("udpAddrs", sentTo).
  170. WithField("initiatorIndex", hostinfo.localIndexId).
  171. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  172. Info("Handshake message sent")
  173. } else if c.l.IsLevelEnabled(logrus.DebugLevel) {
  174. hostinfo.logger(c.l).WithField("udpAddrs", sentTo).
  175. WithField("initiatorIndex", hostinfo.localIndexId).
  176. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  177. Debug("Handshake message sent")
  178. }
  179. if c.config.useRelays && len(hostinfo.remotes.relays) > 0 {
  180. hostinfo.logger(c.l).WithField("relays", hostinfo.remotes.relays).Info("Attempt to relay through hosts")
  181. // Send a RelayRequest to all known Relay IP's
  182. for _, relay := range hostinfo.remotes.relays {
  183. // Don't relay to myself, and don't relay through the host I'm trying to connect to
  184. if *relay == vpnIp || *relay == c.lightHouse.myVpnIp {
  185. continue
  186. }
  187. relayHostInfo, err := c.mainHostMap.QueryVpnIp(*relay)
  188. if err != nil || relayHostInfo.remote == nil {
  189. hostinfo.logger(c.l).WithError(err).WithField("relay", relay.String()).Info("Establish tunnel to relay target")
  190. f.Handshake(*relay)
  191. continue
  192. }
  193. // Check the relay HostInfo to see if we already established a relay through it
  194. if existingRelay, ok := relayHostInfo.relayState.QueryRelayForByIp(vpnIp); ok {
  195. switch existingRelay.State {
  196. case Established:
  197. hostinfo.logger(c.l).WithField("relay", relay.String()).Info("Send handshake via relay")
  198. f.SendVia(relayHostInfo, existingRelay, hostinfo.HandshakePacket[0], make([]byte, 12), make([]byte, mtu), false)
  199. case Requested:
  200. hostinfo.logger(c.l).WithField("relay", relay.String()).Info("Re-send CreateRelay request")
  201. // Re-send the CreateRelay request, in case the previous one was lost.
  202. m := NebulaControl{
  203. Type: NebulaControl_CreateRelayRequest,
  204. InitiatorRelayIndex: existingRelay.LocalIndex,
  205. RelayFromIp: uint32(c.lightHouse.myVpnIp),
  206. RelayToIp: uint32(vpnIp),
  207. }
  208. msg, err := m.Marshal()
  209. if err != nil {
  210. hostinfo.logger(c.l).
  211. WithError(err).
  212. Error("Failed to marshal Control message to create relay")
  213. } else {
  214. f.SendMessageToVpnIp(header.Control, 0, *relay, msg, make([]byte, 12), make([]byte, mtu))
  215. c.l.WithFields(logrus.Fields{
  216. "relayFrom": c.lightHouse.myVpnIp,
  217. "relayTo": vpnIp,
  218. "initiatorRelayIndex": existingRelay.LocalIndex,
  219. "relay": *relay}).
  220. Info("send CreateRelayRequest")
  221. }
  222. default:
  223. hostinfo.logger(c.l).
  224. WithField("vpnIp", vpnIp).
  225. WithField("state", existingRelay.State).
  226. WithField("relay", relayHostInfo.vpnIp).
  227. Errorf("Relay unexpected state")
  228. }
  229. } else {
  230. // No relays exist or requested yet.
  231. if relayHostInfo.remote != nil {
  232. idx, err := AddRelay(c.l, relayHostInfo, c.mainHostMap, vpnIp, nil, TerminalType, Requested)
  233. if err != nil {
  234. hostinfo.logger(c.l).WithField("relay", relay.String()).WithError(err).Info("Failed to add relay to hostmap")
  235. }
  236. m := NebulaControl{
  237. Type: NebulaControl_CreateRelayRequest,
  238. InitiatorRelayIndex: idx,
  239. RelayFromIp: uint32(c.lightHouse.myVpnIp),
  240. RelayToIp: uint32(vpnIp),
  241. }
  242. msg, err := m.Marshal()
  243. if err != nil {
  244. hostinfo.logger(c.l).
  245. WithError(err).
  246. Error("Failed to marshal Control message to create relay")
  247. } else {
  248. f.SendMessageToVpnIp(header.Control, 0, *relay, msg, make([]byte, 12), make([]byte, mtu))
  249. c.l.WithFields(logrus.Fields{
  250. "relayFrom": c.lightHouse.myVpnIp,
  251. "relayTo": vpnIp,
  252. "initiatorRelayIndex": idx,
  253. "relay": *relay}).
  254. Info("send CreateRelayRequest")
  255. }
  256. }
  257. }
  258. }
  259. }
  260. // Increment the counter to increase our delay, linear backoff
  261. hostinfo.HandshakeCounter++
  262. // If a lighthouse triggered this attempt then we are still in the timer wheel and do not need to re-add
  263. if !lighthouseTriggered {
  264. c.OutboundHandshakeTimer.Add(vpnIp, c.config.tryInterval*time.Duration(hostinfo.HandshakeCounter))
  265. }
  266. }
  267. func (c *HandshakeManager) AddVpnIp(vpnIp iputil.VpnIp, init func(*HostInfo)) *HostInfo {
  268. hostinfo, created := c.pendingHostMap.AddVpnIp(vpnIp, init)
  269. if created {
  270. if _, ok := c.vpnIps[vpnIp]; !ok {
  271. c.OutboundHandshakeTimer.Add(vpnIp, c.config.tryInterval)
  272. }
  273. c.vpnIps[vpnIp] = struct{}{}
  274. c.metricInitiated.Inc(1)
  275. }
  276. return hostinfo
  277. }
  278. var (
  279. ErrExistingHostInfo = errors.New("existing hostinfo")
  280. ErrAlreadySeen = errors.New("already seen")
  281. ErrLocalIndexCollision = errors.New("local index collision")
  282. )
  283. // CheckAndComplete checks for any conflicts in the main and pending hostmap
  284. // before adding hostinfo to main. If err is nil, it was added. Otherwise err will be:
  285. //
  286. // ErrAlreadySeen if we already have an entry in the hostmap that has seen the
  287. // exact same handshake packet
  288. //
  289. // ErrExistingHostInfo if we already have an entry in the hostmap for this
  290. // VpnIp and the new handshake was older than the one we currently have
  291. //
  292. // ErrLocalIndexCollision if we already have an entry in the main or pending
  293. // hostmap for the hostinfo.localIndexId.
  294. func (c *HandshakeManager) CheckAndComplete(hostinfo *HostInfo, handshakePacket uint8, f *Interface) (*HostInfo, error) {
  295. c.pendingHostMap.Lock()
  296. defer c.pendingHostMap.Unlock()
  297. c.mainHostMap.Lock()
  298. defer c.mainHostMap.Unlock()
  299. // Check if we already have a tunnel with this vpn ip
  300. existingHostInfo, found := c.mainHostMap.Hosts[hostinfo.vpnIp]
  301. if found && existingHostInfo != nil {
  302. testHostInfo := existingHostInfo
  303. for testHostInfo != nil {
  304. // Is it just a delayed handshake packet?
  305. if bytes.Equal(hostinfo.HandshakePacket[handshakePacket], existingHostInfo.HandshakePacket[handshakePacket]) {
  306. return existingHostInfo, ErrAlreadySeen
  307. }
  308. testHostInfo = testHostInfo.next
  309. }
  310. // Is this a newer handshake?
  311. if existingHostInfo.lastHandshakeTime >= hostinfo.lastHandshakeTime && !existingHostInfo.ConnectionState.initiator {
  312. return existingHostInfo, ErrExistingHostInfo
  313. }
  314. existingHostInfo.logger(c.l).Info("Taking new handshake")
  315. }
  316. existingIndex, found := c.mainHostMap.Indexes[hostinfo.localIndexId]
  317. if found {
  318. // We have a collision, but for a different hostinfo
  319. return existingIndex, ErrLocalIndexCollision
  320. }
  321. existingIndex, found = c.pendingHostMap.Indexes[hostinfo.localIndexId]
  322. if found && existingIndex != hostinfo {
  323. // We have a collision, but for a different hostinfo
  324. return existingIndex, ErrLocalIndexCollision
  325. }
  326. existingRemoteIndex, found := c.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  327. if found && existingRemoteIndex != nil && existingRemoteIndex.vpnIp != hostinfo.vpnIp {
  328. // We have a collision, but this can happen since we can't control
  329. // the remote ID. Just log about the situation as a note.
  330. hostinfo.logger(c.l).
  331. WithField("remoteIndex", hostinfo.remoteIndexId).WithField("collision", existingRemoteIndex.vpnIp).
  332. Info("New host shadows existing host remoteIndex")
  333. }
  334. c.mainHostMap.unlockedAddHostInfo(hostinfo, f)
  335. return existingHostInfo, nil
  336. }
  337. // Complete is a simpler version of CheckAndComplete when we already know we
  338. // won't have a localIndexId collision because we already have an entry in the
  339. // pendingHostMap. An existing hostinfo is returned if there was one.
  340. func (c *HandshakeManager) Complete(hostinfo *HostInfo, f *Interface) *HostInfo {
  341. c.pendingHostMap.Lock()
  342. defer c.pendingHostMap.Unlock()
  343. c.mainHostMap.Lock()
  344. defer c.mainHostMap.Unlock()
  345. existingRemoteIndex, found := c.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  346. if found && existingRemoteIndex != nil {
  347. // We have a collision, but this can happen since we can't control
  348. // the remote ID. Just log about the situation as a note.
  349. hostinfo.logger(c.l).
  350. WithField("remoteIndex", hostinfo.remoteIndexId).WithField("collision", existingRemoteIndex.vpnIp).
  351. Info("New host shadows existing host remoteIndex")
  352. }
  353. existingHostInfo := c.mainHostMap.Hosts[hostinfo.vpnIp]
  354. // We need to remove from the pending hostmap first to avoid undoing work when after to the main hostmap.
  355. c.pendingHostMap.unlockedDeleteHostInfo(hostinfo)
  356. c.mainHostMap.unlockedAddHostInfo(hostinfo, f)
  357. return existingHostInfo
  358. }
  359. // AddIndexHostInfo generates a unique localIndexId for this HostInfo
  360. // and adds it to the pendingHostMap. Will error if we are unable to generate
  361. // a unique localIndexId
  362. func (c *HandshakeManager) AddIndexHostInfo(h *HostInfo) error {
  363. c.pendingHostMap.Lock()
  364. defer c.pendingHostMap.Unlock()
  365. c.mainHostMap.RLock()
  366. defer c.mainHostMap.RUnlock()
  367. for i := 0; i < 32; i++ {
  368. index, err := generateIndex(c.l)
  369. if err != nil {
  370. return err
  371. }
  372. _, inPending := c.pendingHostMap.Indexes[index]
  373. _, inMain := c.mainHostMap.Indexes[index]
  374. if !inMain && !inPending {
  375. h.localIndexId = index
  376. c.pendingHostMap.Indexes[index] = h
  377. return nil
  378. }
  379. }
  380. return errors.New("failed to generate unique localIndexId")
  381. }
  382. func (c *HandshakeManager) addRemoteIndexHostInfo(index uint32, h *HostInfo) {
  383. c.pendingHostMap.addRemoteIndexHostInfo(index, h)
  384. }
  385. func (c *HandshakeManager) DeleteHostInfo(hostinfo *HostInfo) {
  386. //l.Debugln("Deleting pending hostinfo :", hostinfo)
  387. c.pendingHostMap.DeleteHostInfo(hostinfo)
  388. }
  389. func (c *HandshakeManager) QueryIndex(index uint32) (*HostInfo, error) {
  390. return c.pendingHostMap.QueryIndex(index)
  391. }
  392. func (c *HandshakeManager) EmitStats() {
  393. c.pendingHostMap.EmitStats("pending")
  394. c.mainHostMap.EmitStats("main")
  395. }
  396. // Utility functions below
  397. func generateIndex(l *logrus.Logger) (uint32, error) {
  398. b := make([]byte, 4)
  399. // Let zero mean we don't know the ID, so don't generate zero
  400. var index uint32
  401. for index == 0 {
  402. _, err := rand.Read(b)
  403. if err != nil {
  404. l.Errorln(err)
  405. return 0, err
  406. }
  407. index = binary.BigEndian.Uint32(b)
  408. }
  409. if l.Level >= logrus.DebugLevel {
  410. l.WithField("index", index).
  411. Debug("Generated index")
  412. }
  413. return index, nil
  414. }
  415. func hsTimeout(tries int, interval time.Duration) time.Duration {
  416. return time.Duration(tries / 2 * ((2 * int(interval)) + (tries-1)*int(interval)))
  417. }