handshake_manager.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. package nebula
  2. import (
  3. "crypto/rand"
  4. "encoding/binary"
  5. "fmt"
  6. "net"
  7. "time"
  8. "github.com/sirupsen/logrus"
  9. )
  10. const (
  11. // Total time to try a handshake = sequence of HandshakeTryInterval * HandshakeRetries
  12. // With 100ms interval and 20 retries is 23.5 seconds
  13. DefaultHandshakeTryInterval = time.Millisecond * 100
  14. DefaultHandshakeRetries = 20
  15. // DefaultHandshakeWaitRotation is the number of handshake attempts to do before starting to use other ips addresses
  16. DefaultHandshakeWaitRotation = 5
  17. DefaultHandshakeTriggerBuffer = 64
  18. )
  19. var (
  20. defaultHandshakeConfig = HandshakeConfig{
  21. tryInterval: DefaultHandshakeTryInterval,
  22. retries: DefaultHandshakeRetries,
  23. waitRotation: DefaultHandshakeWaitRotation,
  24. triggerBuffer: DefaultHandshakeTriggerBuffer,
  25. }
  26. )
  27. type HandshakeConfig struct {
  28. tryInterval time.Duration
  29. retries int
  30. waitRotation int
  31. triggerBuffer int
  32. messageMetrics *MessageMetrics
  33. }
  34. type HandshakeManager struct {
  35. pendingHostMap *HostMap
  36. mainHostMap *HostMap
  37. lightHouse *LightHouse
  38. outside *udpConn
  39. config HandshakeConfig
  40. // can be used to trigger outbound handshake for the given vpnIP
  41. trigger chan uint32
  42. OutboundHandshakeTimer *SystemTimerWheel
  43. InboundHandshakeTimer *SystemTimerWheel
  44. messageMetrics *MessageMetrics
  45. }
  46. func NewHandshakeManager(tunCidr *net.IPNet, preferredRanges []*net.IPNet, mainHostMap *HostMap, lightHouse *LightHouse, outside *udpConn, config HandshakeConfig) *HandshakeManager {
  47. return &HandshakeManager{
  48. pendingHostMap: NewHostMap("pending", tunCidr, preferredRanges),
  49. mainHostMap: mainHostMap,
  50. lightHouse: lightHouse,
  51. outside: outside,
  52. config: config,
  53. trigger: make(chan uint32, config.triggerBuffer),
  54. OutboundHandshakeTimer: NewSystemTimerWheel(config.tryInterval, config.tryInterval*time.Duration(config.retries)),
  55. InboundHandshakeTimer: NewSystemTimerWheel(config.tryInterval, config.tryInterval*time.Duration(config.retries)),
  56. messageMetrics: config.messageMetrics,
  57. }
  58. }
  59. func (c *HandshakeManager) Run(f EncWriter) {
  60. clockSource := time.Tick(c.config.tryInterval)
  61. for {
  62. select {
  63. case vpnIP := <-c.trigger:
  64. l.WithField("vpnIp", IntIp(vpnIP)).Debug("HandshakeManager: triggered")
  65. c.handleOutbound(vpnIP, f, true)
  66. case now := <-clockSource:
  67. c.NextOutboundHandshakeTimerTick(now, f)
  68. c.NextInboundHandshakeTimerTick(now)
  69. }
  70. }
  71. }
  72. func (c *HandshakeManager) NextOutboundHandshakeTimerTick(now time.Time, f EncWriter) {
  73. c.OutboundHandshakeTimer.advance(now)
  74. for {
  75. ep := c.OutboundHandshakeTimer.Purge()
  76. if ep == nil {
  77. break
  78. }
  79. vpnIP := ep.(uint32)
  80. c.handleOutbound(vpnIP, f, false)
  81. }
  82. }
  83. func (c *HandshakeManager) handleOutbound(vpnIP uint32, f EncWriter, lighthouseTriggered bool) {
  84. hostinfo, err := c.pendingHostMap.QueryVpnIP(vpnIP)
  85. if err != nil {
  86. return
  87. }
  88. hostinfo.Lock()
  89. defer hostinfo.Unlock()
  90. // If we haven't finished the handshake and we haven't hit max retries, query
  91. // lighthouse and then send the handshake packet again.
  92. if hostinfo.HandshakeCounter < c.config.retries && !hostinfo.HandshakeComplete {
  93. if hostinfo.remote == nil {
  94. // We continue to query the lighthouse because hosts may
  95. // come online during handshake retries. If the query
  96. // succeeds (no error), add the lighthouse info to hostinfo
  97. ips := c.lightHouse.QueryCache(vpnIP)
  98. // If we have no responses yet, or only one IP (the host hadn't
  99. // finished reporting its own IPs yet), then send another query to
  100. // the LH.
  101. if len(ips) <= 1 {
  102. ips, err = c.lightHouse.Query(vpnIP, f)
  103. }
  104. if err == nil {
  105. for _, ip := range ips {
  106. hostinfo.AddRemote(ip)
  107. }
  108. hostinfo.ForcePromoteBest(c.mainHostMap.preferredRanges)
  109. }
  110. } else if lighthouseTriggered {
  111. // We were triggered by a lighthouse HostQueryReply packet, but
  112. // we have already picked a remote for this host (this can happen
  113. // if we are configured with multiple lighthouses). So we can skip
  114. // this trigger and let the timerwheel handle the rest of the
  115. // process
  116. return
  117. }
  118. hostinfo.HandshakeCounter++
  119. // We want to use the "best" calculated ip for the first 5 attempts, after that we just blindly rotate through
  120. // all the others until we can stand up a connection.
  121. if hostinfo.HandshakeCounter > c.config.waitRotation {
  122. hostinfo.rotateRemote()
  123. }
  124. // Ensure the handshake is ready to avoid a race in timer tick and stage 0 handshake generation
  125. if hostinfo.HandshakeReady && hostinfo.remote != nil {
  126. c.messageMetrics.Tx(handshake, NebulaMessageSubType(hostinfo.HandshakePacket[0][1]), 1)
  127. err := c.outside.WriteTo(hostinfo.HandshakePacket[0], hostinfo.remote)
  128. if err != nil {
  129. hostinfo.logger().WithField("udpAddr", hostinfo.remote).
  130. WithField("initiatorIndex", hostinfo.localIndexId).
  131. WithField("remoteIndex", hostinfo.remoteIndexId).
  132. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  133. WithError(err).Error("Failed to send handshake message")
  134. } else {
  135. //TODO: this log line is assuming a lot of stuff around the cached stage 0 handshake packet, we should
  136. // keep the real packet struct around for logging purposes
  137. hostinfo.logger().WithField("udpAddr", hostinfo.remote).
  138. WithField("initiatorIndex", hostinfo.localIndexId).
  139. WithField("remoteIndex", hostinfo.remoteIndexId).
  140. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  141. Info("Handshake message sent")
  142. }
  143. }
  144. // Readd to the timer wheel so we continue trying wait HandshakeTryInterval * counter longer for next try
  145. if !lighthouseTriggered {
  146. //l.Infoln("Interval: ", HandshakeTryInterval*time.Duration(hostinfo.HandshakeCounter))
  147. c.OutboundHandshakeTimer.Add(vpnIP, c.config.tryInterval*time.Duration(hostinfo.HandshakeCounter))
  148. }
  149. } else {
  150. c.pendingHostMap.DeleteHostInfo(hostinfo)
  151. }
  152. }
  153. func (c *HandshakeManager) NextInboundHandshakeTimerTick(now time.Time) {
  154. c.InboundHandshakeTimer.advance(now)
  155. for {
  156. ep := c.InboundHandshakeTimer.Purge()
  157. if ep == nil {
  158. break
  159. }
  160. index := ep.(uint32)
  161. c.pendingHostMap.DeleteIndex(index)
  162. }
  163. }
  164. func (c *HandshakeManager) AddVpnIP(vpnIP uint32) *HostInfo {
  165. hostinfo := c.pendingHostMap.AddVpnIP(vpnIP)
  166. // We lock here and use an array to insert items to prevent locking the
  167. // main receive thread for very long by waiting to add items to the pending map
  168. c.OutboundHandshakeTimer.Add(vpnIP, c.config.tryInterval)
  169. return hostinfo
  170. }
  171. func (c *HandshakeManager) AddIndex(index uint32, ci *ConnectionState) (*HostInfo, error) {
  172. hostinfo, err := c.pendingHostMap.AddIndex(index, ci)
  173. if err != nil {
  174. return nil, fmt.Errorf("Issue adding index: %d", index)
  175. }
  176. //c.mainHostMap.AddIndexHostInfo(index, hostinfo)
  177. c.InboundHandshakeTimer.Add(index, time.Second*10)
  178. return hostinfo, nil
  179. }
  180. func (c *HandshakeManager) AddIndexHostInfo(index uint32, h *HostInfo) {
  181. c.pendingHostMap.AddIndexHostInfo(index, h)
  182. }
  183. func (c *HandshakeManager) addRemoteIndexHostInfo(index uint32, h *HostInfo) {
  184. c.pendingHostMap.addRemoteIndexHostInfo(index, h)
  185. }
  186. func (c *HandshakeManager) DeleteHostInfo(hostinfo *HostInfo) {
  187. //l.Debugln("Deleting pending hostinfo :", hostinfo)
  188. c.pendingHostMap.DeleteHostInfo(hostinfo)
  189. }
  190. func (c *HandshakeManager) QueryIndex(index uint32) (*HostInfo, error) {
  191. return c.pendingHostMap.QueryIndex(index)
  192. }
  193. func (c *HandshakeManager) EmitStats() {
  194. c.pendingHostMap.EmitStats("pending")
  195. c.mainHostMap.EmitStats("main")
  196. }
  197. // Utility functions below
  198. func generateIndex() (uint32, error) {
  199. b := make([]byte, 4)
  200. // Let zero mean we don't know the ID, so don't generate zero
  201. var index uint32
  202. for index == 0 {
  203. _, err := rand.Read(b)
  204. if err != nil {
  205. l.Errorln(err)
  206. return 0, err
  207. }
  208. index = binary.BigEndian.Uint32(b)
  209. }
  210. if l.Level >= logrus.DebugLevel {
  211. l.WithField("index", index).
  212. Debug("Generated index")
  213. }
  214. return index, nil
  215. }