handshake_manager.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. )
  13. const (
  14. DefaultHandshakeTryInterval = time.Millisecond * 100
  15. DefaultHandshakeRetries = 10
  16. DefaultHandshakeTriggerBuffer = 64
  17. )
  18. var (
  19. defaultHandshakeConfig = HandshakeConfig{
  20. tryInterval: DefaultHandshakeTryInterval,
  21. retries: DefaultHandshakeRetries,
  22. triggerBuffer: DefaultHandshakeTriggerBuffer,
  23. }
  24. )
  25. type HandshakeConfig struct {
  26. tryInterval time.Duration
  27. retries int
  28. triggerBuffer int
  29. messageMetrics *MessageMetrics
  30. }
  31. type HandshakeManager struct {
  32. pendingHostMap *HostMap
  33. mainHostMap *HostMap
  34. lightHouse *LightHouse
  35. outside *udpConn
  36. config HandshakeConfig
  37. OutboundHandshakeTimer *SystemTimerWheel
  38. messageMetrics *MessageMetrics
  39. metricInitiated metrics.Counter
  40. metricTimedOut metrics.Counter
  41. l *logrus.Logger
  42. // can be used to trigger outbound handshake for the given vpnIP
  43. trigger chan uint32
  44. }
  45. func NewHandshakeManager(l *logrus.Logger, tunCidr *net.IPNet, preferredRanges []*net.IPNet, mainHostMap *HostMap, lightHouse *LightHouse, outside *udpConn, config HandshakeConfig) *HandshakeManager {
  46. return &HandshakeManager{
  47. pendingHostMap: NewHostMap(l, "pending", tunCidr, preferredRanges),
  48. mainHostMap: mainHostMap,
  49. lightHouse: lightHouse,
  50. outside: outside,
  51. config: config,
  52. trigger: make(chan uint32, config.triggerBuffer),
  53. OutboundHandshakeTimer: NewSystemTimerWheel(config.tryInterval, hsTimeout(config.retries, config.tryInterval)),
  54. messageMetrics: config.messageMetrics,
  55. metricInitiated: metrics.GetOrRegisterCounter("handshake_manager.initiated", nil),
  56. metricTimedOut: metrics.GetOrRegisterCounter("handshake_manager.timed_out", nil),
  57. l: l,
  58. }
  59. }
  60. func (c *HandshakeManager) Run(ctx context.Context, f EncWriter) {
  61. clockSource := time.NewTicker(c.config.tryInterval)
  62. defer clockSource.Stop()
  63. for {
  64. select {
  65. case <-ctx.Done():
  66. return
  67. case vpnIP := <-c.trigger:
  68. c.l.WithField("vpnIp", IntIp(vpnIP)).Debug("HandshakeManager: triggered")
  69. c.handleOutbound(vpnIP, f, true)
  70. case now := <-clockSource.C:
  71. c.NextOutboundHandshakeTimerTick(now, f)
  72. }
  73. }
  74. }
  75. func (c *HandshakeManager) NextOutboundHandshakeTimerTick(now time.Time, f EncWriter) {
  76. c.OutboundHandshakeTimer.advance(now)
  77. for {
  78. ep := c.OutboundHandshakeTimer.Purge()
  79. if ep == nil {
  80. break
  81. }
  82. vpnIP := ep.(uint32)
  83. c.handleOutbound(vpnIP, f, false)
  84. }
  85. }
  86. func (c *HandshakeManager) handleOutbound(vpnIP uint32, f EncWriter, lighthouseTriggered bool) {
  87. hostinfo, err := c.pendingHostMap.QueryVpnIP(vpnIP)
  88. if err != nil {
  89. return
  90. }
  91. hostinfo.Lock()
  92. defer hostinfo.Unlock()
  93. // We may have raced to completion but now that we have a lock we should ensure we have not yet completed.
  94. if hostinfo.HandshakeComplete {
  95. // Ensure we don't exist in the pending hostmap anymore since we have completed
  96. c.pendingHostMap.DeleteHostInfo(hostinfo)
  97. return
  98. }
  99. // Check if we have a handshake packet to transmit yet
  100. if !hostinfo.HandshakeReady {
  101. // There is currently a slight race in getOrHandshake due to ConnectionState not being part of the HostInfo directly
  102. // Our hostinfo here was added to the pending map and the wheel may have ticked to us before we created ConnectionState
  103. c.OutboundHandshakeTimer.Add(vpnIP, c.config.tryInterval*time.Duration(hostinfo.HandshakeCounter))
  104. return
  105. }
  106. // If we are out of time, clean up
  107. if hostinfo.HandshakeCounter >= c.config.retries {
  108. hostinfo.logger(c.l).WithField("udpAddrs", hostinfo.remotes.CopyAddrs(c.pendingHostMap.preferredRanges)).
  109. WithField("initiatorIndex", hostinfo.localIndexId).
  110. WithField("remoteIndex", hostinfo.remoteIndexId).
  111. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  112. WithField("durationNs", time.Since(hostinfo.handshakeStart).Nanoseconds()).
  113. Info("Handshake timed out")
  114. c.metricTimedOut.Inc(1)
  115. c.pendingHostMap.DeleteHostInfo(hostinfo)
  116. return
  117. }
  118. // We only care about a lighthouse trigger before the first handshake transmit attempt. This is a very specific
  119. // optimization for a fast lighthouse reply
  120. //TODO: it would feel better to do this once, anytime, as our delay increases over time
  121. if lighthouseTriggered && hostinfo.HandshakeCounter > 0 {
  122. // If we didn't return here a lighthouse could cause us to aggressively send handshakes
  123. return
  124. }
  125. // Get a remotes object if we don't already have one.
  126. // This is mainly to protect us as this should never be the case
  127. if hostinfo.remotes == nil {
  128. hostinfo.remotes = c.lightHouse.QueryCache(vpnIP)
  129. }
  130. //TODO: this will generate a load of queries for hosts with only 1 ip (i'm not using a lighthouse, static mapped)
  131. if hostinfo.remotes.Len(c.pendingHostMap.preferredRanges) <= 1 {
  132. // If we only have 1 remote it is highly likely our query raced with the other host registered within the lighthouse
  133. // Our vpnIP here has a tunnel with a lighthouse but has yet to send a host update packet there so we only know about
  134. // the learned public ip for them. Query again to short circuit the promotion counter
  135. c.lightHouse.QueryServer(vpnIP, f)
  136. }
  137. // Send a the handshake to all known ips, stage 2 takes care of assigning the hostinfo.remote based on the first to reply
  138. var sentTo []*udpAddr
  139. hostinfo.remotes.ForEach(c.pendingHostMap.preferredRanges, func(addr *udpAddr, _ bool) {
  140. c.messageMetrics.Tx(handshake, NebulaMessageSubType(hostinfo.HandshakePacket[0][1]), 1)
  141. err = c.outside.WriteTo(hostinfo.HandshakePacket[0], addr)
  142. if err != nil {
  143. hostinfo.logger(c.l).WithField("udpAddr", addr).
  144. WithField("initiatorIndex", hostinfo.localIndexId).
  145. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  146. WithError(err).Error("Failed to send handshake message")
  147. } else {
  148. sentTo = append(sentTo, addr)
  149. }
  150. })
  151. // 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
  152. if len(sentTo) > 0 {
  153. hostinfo.logger(c.l).WithField("udpAddrs", sentTo).
  154. WithField("initiatorIndex", hostinfo.localIndexId).
  155. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  156. Info("Handshake message sent")
  157. }
  158. // Increment the counter to increase our delay, linear backoff
  159. hostinfo.HandshakeCounter++
  160. // If a lighthouse triggered this attempt then we are still in the timer wheel and do not need to re-add
  161. if !lighthouseTriggered {
  162. //TODO: feel like we dupe handshake real fast in a tight loop, why?
  163. c.OutboundHandshakeTimer.Add(vpnIP, c.config.tryInterval*time.Duration(hostinfo.HandshakeCounter))
  164. }
  165. }
  166. func (c *HandshakeManager) AddVpnIP(vpnIP uint32) *HostInfo {
  167. hostinfo := c.pendingHostMap.AddVpnIP(vpnIP)
  168. // We lock here and use an array to insert items to prevent locking the
  169. // main receive thread for very long by waiting to add items to the pending map
  170. //TODO: what lock?
  171. c.OutboundHandshakeTimer.Add(vpnIP, c.config.tryInterval)
  172. c.metricInitiated.Inc(1)
  173. return hostinfo
  174. }
  175. var (
  176. ErrExistingHostInfo = errors.New("existing hostinfo")
  177. ErrAlreadySeen = errors.New("already seen")
  178. ErrLocalIndexCollision = errors.New("local index collision")
  179. ErrExistingHandshake = errors.New("existing handshake")
  180. )
  181. // CheckAndComplete checks for any conflicts in the main and pending hostmap
  182. // before adding hostinfo to main. If err is nil, it was added. Otherwise err will be:
  183. // ErrAlreadySeen if we already have an entry in the hostmap that has seen the
  184. // exact same handshake packet
  185. //
  186. // ErrExistingHostInfo if we already have an entry in the hostmap for this
  187. // VpnIP and the new handshake was older than the one we currently have
  188. //
  189. // ErrLocalIndexCollision if we already have an entry in the main or pending
  190. // hostmap for the hostinfo.localIndexId.
  191. func (c *HandshakeManager) CheckAndComplete(hostinfo *HostInfo, handshakePacket uint8, overwrite bool, f *Interface) (*HostInfo, error) {
  192. c.pendingHostMap.Lock()
  193. defer c.pendingHostMap.Unlock()
  194. c.mainHostMap.Lock()
  195. defer c.mainHostMap.Unlock()
  196. // Check if we already have a tunnel with this vpn ip
  197. existingHostInfo, found := c.mainHostMap.Hosts[hostinfo.hostId]
  198. if found && existingHostInfo != nil {
  199. // Is it just a delayed handshake packet?
  200. if bytes.Equal(hostinfo.HandshakePacket[handshakePacket], existingHostInfo.HandshakePacket[handshakePacket]) {
  201. return existingHostInfo, ErrAlreadySeen
  202. }
  203. // Is this a newer handshake?
  204. if existingHostInfo.lastHandshakeTime >= hostinfo.lastHandshakeTime {
  205. return existingHostInfo, ErrExistingHostInfo
  206. }
  207. existingHostInfo.logger(c.l).Info("Taking new handshake")
  208. }
  209. existingIndex, found := c.mainHostMap.Indexes[hostinfo.localIndexId]
  210. if found {
  211. // We have a collision, but for a different hostinfo
  212. return existingIndex, ErrLocalIndexCollision
  213. }
  214. existingIndex, found = c.pendingHostMap.Indexes[hostinfo.localIndexId]
  215. if found && existingIndex != hostinfo {
  216. // We have a collision, but for a different hostinfo
  217. return existingIndex, ErrLocalIndexCollision
  218. }
  219. existingRemoteIndex, found := c.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  220. if found && existingRemoteIndex != nil && existingRemoteIndex.hostId != hostinfo.hostId {
  221. // We have a collision, but this can happen since we can't control
  222. // the remote ID. Just log about the situation as a note.
  223. hostinfo.logger(c.l).
  224. WithField("remoteIndex", hostinfo.remoteIndexId).WithField("collision", IntIp(existingRemoteIndex.hostId)).
  225. Info("New host shadows existing host remoteIndex")
  226. }
  227. // Check if we are also handshaking with this vpn ip
  228. pendingHostInfo, found := c.pendingHostMap.Hosts[hostinfo.hostId]
  229. if found && pendingHostInfo != nil {
  230. if !overwrite {
  231. // We won, let our pending handshake win
  232. return pendingHostInfo, ErrExistingHandshake
  233. }
  234. // We lost, take this handshake and move any cached packets over so they get sent
  235. pendingHostInfo.ConnectionState.queueLock.Lock()
  236. hostinfo.packetStore = append(hostinfo.packetStore, pendingHostInfo.packetStore...)
  237. c.pendingHostMap.unlockedDeleteHostInfo(pendingHostInfo)
  238. pendingHostInfo.ConnectionState.queueLock.Unlock()
  239. pendingHostInfo.logger(c.l).Info("Handshake race lost, replacing pending handshake with completed tunnel")
  240. }
  241. if existingHostInfo != nil {
  242. // We are going to overwrite this entry, so remove the old references
  243. delete(c.mainHostMap.Hosts, existingHostInfo.hostId)
  244. delete(c.mainHostMap.Indexes, existingHostInfo.localIndexId)
  245. delete(c.mainHostMap.RemoteIndexes, existingHostInfo.remoteIndexId)
  246. }
  247. c.mainHostMap.addHostInfo(hostinfo, f)
  248. return existingHostInfo, nil
  249. }
  250. // Complete is a simpler version of CheckAndComplete when we already know we
  251. // won't have a localIndexId collision because we already have an entry in the
  252. // pendingHostMap
  253. func (c *HandshakeManager) Complete(hostinfo *HostInfo, f *Interface) {
  254. c.pendingHostMap.Lock()
  255. defer c.pendingHostMap.Unlock()
  256. c.mainHostMap.Lock()
  257. defer c.mainHostMap.Unlock()
  258. existingHostInfo, found := c.mainHostMap.Hosts[hostinfo.hostId]
  259. if found && existingHostInfo != nil {
  260. // We are going to overwrite this entry, so remove the old references
  261. delete(c.mainHostMap.Hosts, existingHostInfo.hostId)
  262. delete(c.mainHostMap.Indexes, existingHostInfo.localIndexId)
  263. delete(c.mainHostMap.RemoteIndexes, existingHostInfo.remoteIndexId)
  264. }
  265. existingRemoteIndex, found := c.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  266. if found && existingRemoteIndex != nil {
  267. // We have a collision, but this can happen since we can't control
  268. // the remote ID. Just log about the situation as a note.
  269. hostinfo.logger(c.l).
  270. WithField("remoteIndex", hostinfo.remoteIndexId).WithField("collision", IntIp(existingRemoteIndex.hostId)).
  271. Info("New host shadows existing host remoteIndex")
  272. }
  273. c.mainHostMap.addHostInfo(hostinfo, f)
  274. c.pendingHostMap.unlockedDeleteHostInfo(hostinfo)
  275. }
  276. // AddIndexHostInfo generates a unique localIndexId for this HostInfo
  277. // and adds it to the pendingHostMap. Will error if we are unable to generate
  278. // a unique localIndexId
  279. func (c *HandshakeManager) AddIndexHostInfo(h *HostInfo) error {
  280. c.pendingHostMap.Lock()
  281. defer c.pendingHostMap.Unlock()
  282. c.mainHostMap.RLock()
  283. defer c.mainHostMap.RUnlock()
  284. for i := 0; i < 32; i++ {
  285. index, err := generateIndex(c.l)
  286. if err != nil {
  287. return err
  288. }
  289. _, inPending := c.pendingHostMap.Indexes[index]
  290. _, inMain := c.mainHostMap.Indexes[index]
  291. if !inMain && !inPending {
  292. h.localIndexId = index
  293. c.pendingHostMap.Indexes[index] = h
  294. return nil
  295. }
  296. }
  297. return errors.New("failed to generate unique localIndexId")
  298. }
  299. func (c *HandshakeManager) addRemoteIndexHostInfo(index uint32, h *HostInfo) {
  300. c.pendingHostMap.addRemoteIndexHostInfo(index, h)
  301. }
  302. func (c *HandshakeManager) DeleteHostInfo(hostinfo *HostInfo) {
  303. //l.Debugln("Deleting pending hostinfo :", hostinfo)
  304. c.pendingHostMap.DeleteHostInfo(hostinfo)
  305. }
  306. func (c *HandshakeManager) QueryIndex(index uint32) (*HostInfo, error) {
  307. return c.pendingHostMap.QueryIndex(index)
  308. }
  309. func (c *HandshakeManager) EmitStats() {
  310. c.pendingHostMap.EmitStats("pending")
  311. c.mainHostMap.EmitStats("main")
  312. }
  313. // Utility functions below
  314. func generateIndex(l *logrus.Logger) (uint32, error) {
  315. b := make([]byte, 4)
  316. // Let zero mean we don't know the ID, so don't generate zero
  317. var index uint32
  318. for index == 0 {
  319. _, err := rand.Read(b)
  320. if err != nil {
  321. l.Errorln(err)
  322. return 0, err
  323. }
  324. index = binary.BigEndian.Uint32(b)
  325. }
  326. if l.Level >= logrus.DebugLevel {
  327. l.WithField("index", index).
  328. Debug("Generated index")
  329. }
  330. return index, nil
  331. }
  332. func hsTimeout(tries int, interval time.Duration) time.Duration {
  333. return time.Duration(tries / 2 * ((2 * int(interval)) + (tries-1)*int(interval)))
  334. }