handshake_manager.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. )
  18. var (
  19. defaultHandshakeConfig = HandshakeConfig{
  20. tryInterval: DefaultHandshakeTryInterval,
  21. retries: DefaultHandshakeRetries,
  22. waitRotation: DefaultHandshakeWaitRotation,
  23. }
  24. )
  25. type HandshakeConfig struct {
  26. tryInterval time.Duration
  27. retries int
  28. waitRotation 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. InboundHandshakeTimer *SystemTimerWheel
  39. messageMetrics *MessageMetrics
  40. }
  41. func NewHandshakeManager(tunCidr *net.IPNet, preferredRanges []*net.IPNet, mainHostMap *HostMap, lightHouse *LightHouse, outside *udpConn, config HandshakeConfig) *HandshakeManager {
  42. return &HandshakeManager{
  43. pendingHostMap: NewHostMap("pending", tunCidr, preferredRanges),
  44. mainHostMap: mainHostMap,
  45. lightHouse: lightHouse,
  46. outside: outside,
  47. config: config,
  48. OutboundHandshakeTimer: NewSystemTimerWheel(config.tryInterval, config.tryInterval*time.Duration(config.retries)),
  49. InboundHandshakeTimer: NewSystemTimerWheel(config.tryInterval, config.tryInterval*time.Duration(config.retries)),
  50. messageMetrics: config.messageMetrics,
  51. }
  52. }
  53. func (c *HandshakeManager) Run(f EncWriter) {
  54. clockSource := time.Tick(c.config.tryInterval)
  55. for now := range clockSource {
  56. c.NextOutboundHandshakeTimerTick(now, f)
  57. c.NextInboundHandshakeTimerTick(now)
  58. }
  59. }
  60. func (c *HandshakeManager) NextOutboundHandshakeTimerTick(now time.Time, f EncWriter) {
  61. c.OutboundHandshakeTimer.advance(now)
  62. for {
  63. ep := c.OutboundHandshakeTimer.Purge()
  64. if ep == nil {
  65. break
  66. }
  67. vpnIP := ep.(uint32)
  68. index, err := c.pendingHostMap.GetIndexByVpnIP(vpnIP)
  69. if err != nil {
  70. continue
  71. }
  72. hostinfo, err := c.pendingHostMap.QueryVpnIP(vpnIP)
  73. if err != nil {
  74. continue
  75. }
  76. // If we haven't finished the handshake and we haven't hit max retries, query
  77. // lighthouse and then send the handshake packet again.
  78. if hostinfo.HandshakeCounter < c.config.retries && !hostinfo.HandshakeComplete {
  79. if hostinfo.remote == nil {
  80. // We continue to query the lighthouse because hosts may
  81. // come online during handshake retries. If the query
  82. // succeeds (no error), add the lighthouse info to hostinfo
  83. ips, err := c.lightHouse.Query(vpnIP, f)
  84. if err == nil {
  85. for _, ip := range ips {
  86. hostinfo.AddRemote(ip)
  87. }
  88. hostinfo.ForcePromoteBest(c.mainHostMap.preferredRanges)
  89. }
  90. }
  91. hostinfo.HandshakeCounter++
  92. // We want to use the "best" calculated ip for the first 5 attempts, after that we just blindly rotate through
  93. // all the others until we can stand up a connection.
  94. if hostinfo.HandshakeCounter > c.config.waitRotation {
  95. hostinfo.rotateRemote()
  96. }
  97. // Ensure the handshake is ready to avoid a race in timer tick and stage 0 handshake generation
  98. if hostinfo.HandshakeReady && hostinfo.remote != nil {
  99. c.messageMetrics.Tx(handshake, NebulaMessageSubType(hostinfo.HandshakePacket[0][1]), 1)
  100. err := c.outside.WriteTo(hostinfo.HandshakePacket[0], hostinfo.remote)
  101. if err != nil {
  102. hostinfo.logger().WithField("udpAddr", hostinfo.remote).
  103. WithField("initiatorIndex", hostinfo.localIndexId).
  104. WithField("remoteIndex", hostinfo.remoteIndexId).
  105. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  106. WithError(err).Error("Failed to send handshake message")
  107. } else {
  108. //TODO: this log line is assuming a lot of stuff around the cached stage 0 handshake packet, we should
  109. // keep the real packet struct around for logging purposes
  110. hostinfo.logger().WithField("udpAddr", hostinfo.remote).
  111. WithField("initiatorIndex", hostinfo.localIndexId).
  112. WithField("remoteIndex", hostinfo.remoteIndexId).
  113. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  114. Info("Handshake message sent")
  115. }
  116. }
  117. // Readd to the timer wheel so we continue trying wait HandshakeTryInterval * counter longer for next try
  118. //l.Infoln("Interval: ", HandshakeTryInterval*time.Duration(hostinfo.HandshakeCounter))
  119. c.OutboundHandshakeTimer.Add(vpnIP, c.config.tryInterval*time.Duration(hostinfo.HandshakeCounter))
  120. } else {
  121. c.pendingHostMap.DeleteVpnIP(vpnIP)
  122. c.pendingHostMap.DeleteIndex(index)
  123. }
  124. }
  125. }
  126. func (c *HandshakeManager) NextInboundHandshakeTimerTick(now time.Time) {
  127. c.InboundHandshakeTimer.advance(now)
  128. for {
  129. ep := c.InboundHandshakeTimer.Purge()
  130. if ep == nil {
  131. break
  132. }
  133. index := ep.(uint32)
  134. vpnIP, err := c.pendingHostMap.GetVpnIPByIndex(index)
  135. if err != nil {
  136. continue
  137. }
  138. c.pendingHostMap.DeleteIndex(index)
  139. c.pendingHostMap.DeleteVpnIP(vpnIP)
  140. }
  141. }
  142. func (c *HandshakeManager) AddVpnIP(vpnIP uint32) *HostInfo {
  143. hostinfo := c.pendingHostMap.AddVpnIP(vpnIP)
  144. // We lock here and use an array to insert items to prevent locking the
  145. // main receive thread for very long by waiting to add items to the pending map
  146. c.OutboundHandshakeTimer.Add(vpnIP, c.config.tryInterval)
  147. return hostinfo
  148. }
  149. func (c *HandshakeManager) DeleteVpnIP(vpnIP uint32) {
  150. //l.Debugln("Deleting pending vpn ip :", IntIp(vpnIP))
  151. c.pendingHostMap.DeleteVpnIP(vpnIP)
  152. }
  153. func (c *HandshakeManager) AddIndex(index uint32, ci *ConnectionState) (*HostInfo, error) {
  154. hostinfo, err := c.pendingHostMap.AddIndex(index, ci)
  155. if err != nil {
  156. return nil, fmt.Errorf("Issue adding index: %d", index)
  157. }
  158. //c.mainHostMap.AddIndexHostInfo(index, hostinfo)
  159. c.InboundHandshakeTimer.Add(index, time.Second*10)
  160. return hostinfo, nil
  161. }
  162. func (c *HandshakeManager) AddIndexHostInfo(index uint32, h *HostInfo) {
  163. c.pendingHostMap.AddIndexHostInfo(index, h)
  164. }
  165. func (c *HandshakeManager) DeleteIndex(index uint32) {
  166. //l.Debugln("Deleting pending index :", index)
  167. c.pendingHostMap.DeleteIndex(index)
  168. }
  169. func (c *HandshakeManager) QueryIndex(index uint32) (*HostInfo, error) {
  170. return c.pendingHostMap.QueryIndex(index)
  171. }
  172. func (c *HandshakeManager) EmitStats() {
  173. c.pendingHostMap.EmitStats("pending")
  174. c.mainHostMap.EmitStats("main")
  175. }
  176. // Utility functions below
  177. func generateIndex() (uint32, error) {
  178. b := make([]byte, 4)
  179. _, err := rand.Read(b)
  180. if err != nil {
  181. l.Errorln(err)
  182. return 0, err
  183. }
  184. index := binary.BigEndian.Uint32(b)
  185. if l.Level >= logrus.DebugLevel {
  186. l.WithField("index", index).
  187. Debug("Generated index")
  188. }
  189. return index, nil
  190. }