handshake_manager.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. // We only care about a lighthouse trigger before the first handshake transmit attempt. This is a very specific
  128. // optimization for a fast lighthouse reply
  129. //TODO: it would feel better to do this once, anytime, as our delay increases over time
  130. if lighthouseTriggered && hostinfo.HandshakeCounter > 0 {
  131. // If we didn't return here a lighthouse could cause us to aggressively send handshakes
  132. return
  133. }
  134. // Get a remotes object if we don't already have one.
  135. // This is mainly to protect us as this should never be the case
  136. // NB ^ This comment doesn't jive. It's how the thing gets initialized.
  137. // It's the common path. Should it update every time, in case a future LH query/queries give us more info?
  138. if hostinfo.remotes == nil {
  139. hostinfo.remotes = c.lightHouse.QueryCache(vpnIp)
  140. }
  141. //TODO: this will generate a load of queries for hosts with only 1 ip (i'm not using a lighthouse, static mapped)
  142. if hostinfo.remotes.Len(c.pendingHostMap.preferredRanges) <= 1 {
  143. // If we only have 1 remote it is highly likely our query raced with the other host registered within the lighthouse
  144. // Our vpnIp here has a tunnel with a lighthouse but has yet to send a host update packet there so we only know about
  145. // the learned public ip for them. Query again to short circuit the promotion counter
  146. c.lightHouse.QueryServer(vpnIp, f)
  147. }
  148. // Send the handshake to all known ips, stage 2 takes care of assigning the hostinfo.remote based on the first to reply
  149. var sentTo []*udp.Addr
  150. hostinfo.remotes.ForEach(c.pendingHostMap.preferredRanges, func(addr *udp.Addr, _ bool) {
  151. c.messageMetrics.Tx(header.Handshake, header.MessageSubType(hostinfo.HandshakePacket[0][1]), 1)
  152. err = c.outside.WriteTo(hostinfo.HandshakePacket[0], addr)
  153. if err != nil {
  154. hostinfo.logger(c.l).WithField("udpAddr", addr).
  155. WithField("initiatorIndex", hostinfo.localIndexId).
  156. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  157. WithError(err).Error("Failed to send handshake message")
  158. } else {
  159. sentTo = append(sentTo, addr)
  160. }
  161. })
  162. // 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
  163. if len(sentTo) > 0 {
  164. hostinfo.logger(c.l).WithField("udpAddrs", sentTo).
  165. WithField("initiatorIndex", hostinfo.localIndexId).
  166. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  167. Info("Handshake message sent")
  168. }
  169. if c.config.useRelays && len(hostinfo.remotes.relays) > 0 {
  170. hostinfo.logger(c.l).WithField("relayIps", hostinfo.remotes.relays).Info("Attempt to relay through hosts")
  171. // Send a RelayRequest to all known Relay IP's
  172. for _, relay := range hostinfo.remotes.relays {
  173. // Don't relay to myself, and don't relay through the host I'm trying to connect to
  174. if *relay == vpnIp || *relay == c.lightHouse.myVpnIp {
  175. continue
  176. }
  177. relayHostInfo, err := c.mainHostMap.QueryVpnIp(*relay)
  178. if err != nil || relayHostInfo.remote == nil {
  179. hostinfo.logger(c.l).WithError(err).WithField("relay", relay.String()).Info("Establish tunnel to relay target.")
  180. f.Handshake(*relay)
  181. continue
  182. }
  183. // Check the relay HostInfo to see if we already established a relay through it
  184. if existingRelay, ok := relayHostInfo.relayState.QueryRelayForByIp(vpnIp); ok {
  185. switch existingRelay.State {
  186. case Established:
  187. hostinfo.logger(c.l).WithField("relay", relay.String()).Info("Send handshake via relay")
  188. f.SendVia(relayHostInfo, existingRelay, hostinfo.HandshakePacket[0], make([]byte, 12), make([]byte, mtu), false)
  189. case Requested:
  190. hostinfo.logger(c.l).WithField("relay", relay.String()).Info("Re-send CreateRelay request")
  191. // Re-send the CreateRelay request, in case the previous one was lost.
  192. m := NebulaControl{
  193. Type: NebulaControl_CreateRelayRequest,
  194. InitiatorRelayIndex: existingRelay.LocalIndex,
  195. RelayFromIp: uint32(c.lightHouse.myVpnIp),
  196. RelayToIp: uint32(vpnIp),
  197. }
  198. msg, err := m.Marshal()
  199. if err != nil {
  200. hostinfo.logger(c.l).
  201. WithError(err).
  202. Error("Failed to marshal Control message to create relay")
  203. } else {
  204. f.SendMessageToVpnIp(header.Control, 0, *relay, msg, make([]byte, 12), make([]byte, mtu))
  205. }
  206. default:
  207. hostinfo.logger(c.l).
  208. WithField("vpnIp", vpnIp).
  209. WithField("state", existingRelay.State).
  210. WithField("relayVpnIp", relayHostInfo.vpnIp).
  211. Errorf("Relay unexpected state")
  212. }
  213. } else {
  214. // No relays exist or requested yet.
  215. if relayHostInfo.remote != nil {
  216. idx, err := AddRelay(c.l, relayHostInfo, c.mainHostMap, vpnIp, nil, TerminalType, Requested)
  217. if err != nil {
  218. hostinfo.logger(c.l).WithField("relay", relay.String()).WithError(err).Info("Failed to add relay to hostmap")
  219. }
  220. m := NebulaControl{
  221. Type: NebulaControl_CreateRelayRequest,
  222. InitiatorRelayIndex: idx,
  223. RelayFromIp: uint32(c.lightHouse.myVpnIp),
  224. RelayToIp: uint32(vpnIp),
  225. }
  226. msg, err := m.Marshal()
  227. if err != nil {
  228. hostinfo.logger(c.l).
  229. WithError(err).
  230. Error("Failed to marshal Control message to create relay")
  231. } else {
  232. f.SendMessageToVpnIp(header.Control, 0, *relay, msg, make([]byte, 12), make([]byte, mtu))
  233. }
  234. }
  235. }
  236. }
  237. }
  238. // Increment the counter to increase our delay, linear backoff
  239. hostinfo.HandshakeCounter++
  240. // If a lighthouse triggered this attempt then we are still in the timer wheel and do not need to re-add
  241. if !lighthouseTriggered {
  242. c.OutboundHandshakeTimer.Add(vpnIp, c.config.tryInterval*time.Duration(hostinfo.HandshakeCounter))
  243. }
  244. }
  245. func (c *HandshakeManager) AddVpnIp(vpnIp iputil.VpnIp, init func(*HostInfo)) *HostInfo {
  246. hostinfo, created := c.pendingHostMap.AddVpnIp(vpnIp, init)
  247. if created {
  248. if _, ok := c.vpnIps[vpnIp]; !ok {
  249. c.OutboundHandshakeTimer.Add(vpnIp, c.config.tryInterval)
  250. }
  251. c.vpnIps[vpnIp] = struct{}{}
  252. c.metricInitiated.Inc(1)
  253. }
  254. return hostinfo
  255. }
  256. var (
  257. ErrExistingHostInfo = errors.New("existing hostinfo")
  258. ErrAlreadySeen = errors.New("already seen")
  259. ErrLocalIndexCollision = errors.New("local index collision")
  260. )
  261. // CheckAndComplete checks for any conflicts in the main and pending hostmap
  262. // before adding hostinfo to main. If err is nil, it was added. Otherwise err will be:
  263. //
  264. // ErrAlreadySeen if we already have an entry in the hostmap that has seen the
  265. // exact same handshake packet
  266. //
  267. // ErrExistingHostInfo if we already have an entry in the hostmap for this
  268. // VpnIp and the new handshake was older than the one we currently have
  269. //
  270. // ErrLocalIndexCollision if we already have an entry in the main or pending
  271. // hostmap for the hostinfo.localIndexId.
  272. func (c *HandshakeManager) CheckAndComplete(hostinfo *HostInfo, handshakePacket uint8, f *Interface) (*HostInfo, error) {
  273. c.pendingHostMap.Lock()
  274. defer c.pendingHostMap.Unlock()
  275. c.mainHostMap.Lock()
  276. defer c.mainHostMap.Unlock()
  277. // Check if we already have a tunnel with this vpn ip
  278. existingHostInfo, found := c.mainHostMap.Hosts[hostinfo.vpnIp]
  279. if found && existingHostInfo != nil {
  280. testHostInfo := existingHostInfo
  281. for testHostInfo != nil {
  282. // Is it just a delayed handshake packet?
  283. if bytes.Equal(hostinfo.HandshakePacket[handshakePacket], existingHostInfo.HandshakePacket[handshakePacket]) {
  284. return existingHostInfo, ErrAlreadySeen
  285. }
  286. testHostInfo = testHostInfo.next
  287. }
  288. // Is this a newer handshake?
  289. if existingHostInfo.lastHandshakeTime >= hostinfo.lastHandshakeTime {
  290. return existingHostInfo, ErrExistingHostInfo
  291. }
  292. existingHostInfo.logger(c.l).Info("Taking new handshake")
  293. }
  294. existingIndex, found := c.mainHostMap.Indexes[hostinfo.localIndexId]
  295. if found {
  296. // We have a collision, but for a different hostinfo
  297. return existingIndex, ErrLocalIndexCollision
  298. }
  299. existingIndex, found = c.pendingHostMap.Indexes[hostinfo.localIndexId]
  300. if found && existingIndex != hostinfo {
  301. // We have a collision, but for a different hostinfo
  302. return existingIndex, ErrLocalIndexCollision
  303. }
  304. existingRemoteIndex, found := c.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  305. if found && existingRemoteIndex != nil && existingRemoteIndex.vpnIp != hostinfo.vpnIp {
  306. // We have a collision, but this can happen since we can't control
  307. // the remote ID. Just log about the situation as a note.
  308. hostinfo.logger(c.l).
  309. WithField("remoteIndex", hostinfo.remoteIndexId).WithField("collision", existingRemoteIndex.vpnIp).
  310. Info("New host shadows existing host remoteIndex")
  311. }
  312. c.mainHostMap.unlockedAddHostInfo(hostinfo, f)
  313. return existingHostInfo, nil
  314. }
  315. // Complete is a simpler version of CheckAndComplete when we already know we
  316. // won't have a localIndexId collision because we already have an entry in the
  317. // pendingHostMap. An existing hostinfo is returned if there was one.
  318. func (c *HandshakeManager) Complete(hostinfo *HostInfo, f *Interface) *HostInfo {
  319. c.pendingHostMap.Lock()
  320. defer c.pendingHostMap.Unlock()
  321. c.mainHostMap.Lock()
  322. defer c.mainHostMap.Unlock()
  323. existingRemoteIndex, found := c.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  324. if found && existingRemoteIndex != nil {
  325. // We have a collision, but this can happen since we can't control
  326. // the remote ID. Just log about the situation as a note.
  327. hostinfo.logger(c.l).
  328. WithField("remoteIndex", hostinfo.remoteIndexId).WithField("collision", existingRemoteIndex.vpnIp).
  329. Info("New host shadows existing host remoteIndex")
  330. }
  331. existingHostInfo := c.mainHostMap.Hosts[hostinfo.vpnIp]
  332. c.mainHostMap.unlockedAddHostInfo(hostinfo, f)
  333. c.pendingHostMap.unlockedDeleteHostInfo(hostinfo)
  334. return existingHostInfo
  335. }
  336. // AddIndexHostInfo generates a unique localIndexId for this HostInfo
  337. // and adds it to the pendingHostMap. Will error if we are unable to generate
  338. // a unique localIndexId
  339. func (c *HandshakeManager) AddIndexHostInfo(h *HostInfo) error {
  340. c.pendingHostMap.Lock()
  341. defer c.pendingHostMap.Unlock()
  342. c.mainHostMap.RLock()
  343. defer c.mainHostMap.RUnlock()
  344. for i := 0; i < 32; i++ {
  345. index, err := generateIndex(c.l)
  346. if err != nil {
  347. return err
  348. }
  349. _, inPending := c.pendingHostMap.Indexes[index]
  350. _, inMain := c.mainHostMap.Indexes[index]
  351. if !inMain && !inPending {
  352. h.localIndexId = index
  353. c.pendingHostMap.Indexes[index] = h
  354. return nil
  355. }
  356. }
  357. return errors.New("failed to generate unique localIndexId")
  358. }
  359. func (c *HandshakeManager) addRemoteIndexHostInfo(index uint32, h *HostInfo) {
  360. c.pendingHostMap.addRemoteIndexHostInfo(index, h)
  361. }
  362. func (c *HandshakeManager) DeleteHostInfo(hostinfo *HostInfo) {
  363. //l.Debugln("Deleting pending hostinfo :", hostinfo)
  364. c.pendingHostMap.DeleteHostInfo(hostinfo)
  365. }
  366. func (c *HandshakeManager) QueryIndex(index uint32) (*HostInfo, error) {
  367. return c.pendingHostMap.QueryIndex(index)
  368. }
  369. func (c *HandshakeManager) EmitStats() {
  370. c.pendingHostMap.EmitStats("pending")
  371. c.mainHostMap.EmitStats("main")
  372. }
  373. // Utility functions below
  374. func generateIndex(l *logrus.Logger) (uint32, error) {
  375. b := make([]byte, 4)
  376. // Let zero mean we don't know the ID, so don't generate zero
  377. var index uint32
  378. for index == 0 {
  379. _, err := rand.Read(b)
  380. if err != nil {
  381. l.Errorln(err)
  382. return 0, err
  383. }
  384. index = binary.BigEndian.Uint32(b)
  385. }
  386. if l.Level >= logrus.DebugLevel {
  387. l.WithField("index", index).
  388. Debug("Generated index")
  389. }
  390. return index, nil
  391. }
  392. func hsTimeout(tries int, interval time.Duration) time.Duration {
  393. return time.Duration(tries / 2 * ((2 * int(interval)) + (tries-1)*int(interval)))
  394. }