handshake_manager.go 13 KB

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