handshake_manager.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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 *SystemTimerWheel
  44. messageMetrics *MessageMetrics
  45. metricInitiated metrics.Counter
  46. metricTimedOut metrics.Counter
  47. l *logrus.Logger
  48. // can be used to trigger outbound handshake for the given vpnIp
  49. trigger chan iputil.VpnIp
  50. }
  51. func NewHandshakeManager(l *logrus.Logger, tunCidr *net.IPNet, preferredRanges []*net.IPNet, mainHostMap *HostMap, lightHouse *LightHouse, outside *udp.Conn, config HandshakeConfig) *HandshakeManager {
  52. return &HandshakeManager{
  53. pendingHostMap: NewHostMap(l, "pending", tunCidr, preferredRanges),
  54. mainHostMap: mainHostMap,
  55. lightHouse: lightHouse,
  56. outside: outside,
  57. config: config,
  58. trigger: make(chan iputil.VpnIp, config.triggerBuffer),
  59. OutboundHandshakeTimer: NewSystemTimerWheel(config.tryInterval, hsTimeout(config.retries, config.tryInterval)),
  60. messageMetrics: config.messageMetrics,
  61. metricInitiated: metrics.GetOrRegisterCounter("handshake_manager.initiated", nil),
  62. metricTimedOut: metrics.GetOrRegisterCounter("handshake_manager.timed_out", nil),
  63. l: l,
  64. }
  65. }
  66. func (c *HandshakeManager) Run(ctx context.Context, f udp.EncWriter) {
  67. clockSource := time.NewTicker(c.config.tryInterval)
  68. defer clockSource.Stop()
  69. for {
  70. select {
  71. case <-ctx.Done():
  72. return
  73. case vpnIP := <-c.trigger:
  74. c.handleOutbound(vpnIP, f, true)
  75. case now := <-clockSource.C:
  76. c.NextOutboundHandshakeTimerTick(now, f)
  77. }
  78. }
  79. }
  80. func (c *HandshakeManager) NextOutboundHandshakeTimerTick(now time.Time, f udp.EncWriter) {
  81. c.OutboundHandshakeTimer.advance(now)
  82. for {
  83. ep := c.OutboundHandshakeTimer.Purge()
  84. if ep == nil {
  85. break
  86. }
  87. vpnIp := ep.(iputil.VpnIp)
  88. c.handleOutbound(vpnIp, f, false)
  89. }
  90. }
  91. func (c *HandshakeManager) handleOutbound(vpnIp iputil.VpnIp, f udp.EncWriter, lighthouseTriggered bool) {
  92. hostinfo, err := c.pendingHostMap.QueryVpnIp(vpnIp)
  93. if err != nil {
  94. return
  95. }
  96. hostinfo.Lock()
  97. defer hostinfo.Unlock()
  98. // We may have raced to completion but now that we have a lock we should ensure we have not yet completed.
  99. if hostinfo.HandshakeComplete {
  100. // Ensure we don't exist in the pending hostmap anymore since we have completed
  101. c.pendingHostMap.DeleteHostInfo(hostinfo)
  102. return
  103. }
  104. // Check if we have a handshake packet to transmit yet
  105. if !hostinfo.HandshakeReady {
  106. // There is currently a slight race in getOrHandshake due to ConnectionState not being part of the HostInfo directly
  107. // Our hostinfo here was added to the pending map and the wheel may have ticked to us before we created ConnectionState
  108. c.OutboundHandshakeTimer.Add(vpnIp, c.config.tryInterval*time.Duration(hostinfo.HandshakeCounter))
  109. return
  110. }
  111. // If we are out of time, clean up
  112. if hostinfo.HandshakeCounter >= c.config.retries {
  113. hostinfo.logger(c.l).WithField("udpAddrs", hostinfo.remotes.CopyAddrs(c.pendingHostMap.preferredRanges)).
  114. WithField("initiatorIndex", hostinfo.localIndexId).
  115. WithField("remoteIndex", hostinfo.remoteIndexId).
  116. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  117. WithField("durationNs", time.Since(hostinfo.handshakeStart).Nanoseconds()).
  118. Info("Handshake timed out")
  119. c.metricTimedOut.Inc(1)
  120. c.pendingHostMap.DeleteHostInfo(hostinfo)
  121. return
  122. }
  123. // We only care about a lighthouse trigger before the first handshake transmit attempt. This is a very specific
  124. // optimization for a fast lighthouse reply
  125. //TODO: it would feel better to do this once, anytime, as our delay increases over time
  126. if lighthouseTriggered && hostinfo.HandshakeCounter > 0 {
  127. // If we didn't return here a lighthouse could cause us to aggressively send handshakes
  128. return
  129. }
  130. // Get a remotes object if we don't already have one.
  131. // This is mainly to protect us as this should never be the case
  132. // NB ^ This comment doesn't jive. It's how the thing gets intiailized.
  133. // It's the common path. Should it update every time, in case a future LH query/queries give us more info?
  134. if hostinfo.remotes == nil {
  135. hostinfo.remotes = c.lightHouse.QueryCache(vpnIp)
  136. }
  137. //TODO: this will generate a load of queries for hosts with only 1 ip (i'm not using a lighthouse, static mapped)
  138. if hostinfo.remotes.Len(c.pendingHostMap.preferredRanges) <= 1 {
  139. // If we only have 1 remote it is highly likely our query raced with the other host registered within the lighthouse
  140. // Our vpnIp here has a tunnel with a lighthouse but has yet to send a host update packet there so we only know about
  141. // the learned public ip for them. Query again to short circuit the promotion counter
  142. c.lightHouse.QueryServer(vpnIp, f)
  143. }
  144. // Send a the handshake to all known ips, stage 2 takes care of assigning the hostinfo.remote based on the first to reply
  145. var sentTo []*udp.Addr
  146. hostinfo.remotes.ForEach(c.pendingHostMap.preferredRanges, func(addr *udp.Addr, _ bool) {
  147. c.messageMetrics.Tx(header.Handshake, header.MessageSubType(hostinfo.HandshakePacket[0][1]), 1)
  148. err = c.outside.WriteTo(hostinfo.HandshakePacket[0], addr)
  149. if err != nil {
  150. hostinfo.logger(c.l).WithField("udpAddr", addr).
  151. WithField("initiatorIndex", hostinfo.localIndexId).
  152. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  153. WithError(err).Error("Failed to send handshake message")
  154. } else {
  155. sentTo = append(sentTo, addr)
  156. }
  157. })
  158. // 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
  159. if len(sentTo) > 0 {
  160. hostinfo.logger(c.l).WithField("udpAddrs", sentTo).
  161. WithField("initiatorIndex", hostinfo.localIndexId).
  162. WithField("handshake", m{"stage": 1, "style": "ix_psk0"}).
  163. Info("Handshake message sent")
  164. }
  165. if c.config.useRelays && len(hostinfo.remotes.relays) > 0 {
  166. hostinfo.logger(c.l).WithField("relayIps", hostinfo.remotes.relays).Info("Attempt to relay through hosts")
  167. // Send a RelayRequest to all known Relay IP's
  168. for _, relay := range hostinfo.remotes.relays {
  169. // Don't relay to myself, and don't relay through the host I'm trying to connect to
  170. if *relay == vpnIp || *relay == c.lightHouse.myVpnIp {
  171. continue
  172. }
  173. relayHostInfo, err := c.mainHostMap.QueryVpnIp(*relay)
  174. if err != nil || relayHostInfo.remote == nil {
  175. hostinfo.logger(c.l).WithError(err).WithField("relay", relay.String()).Info("Establish tunnel to relay target.")
  176. f.Handshake(*relay)
  177. continue
  178. }
  179. // Check the relay HostInfo to see if we already established a relay through it
  180. if existingRelay, ok := relayHostInfo.relayState.QueryRelayForByIp(vpnIp); ok {
  181. switch existingRelay.State {
  182. case Established:
  183. hostinfo.logger(c.l).WithField("relay", relay.String()).Info("Send handshake via relay")
  184. f.SendVia(relayHostInfo, existingRelay, hostinfo.HandshakePacket[0], make([]byte, 12), make([]byte, mtu), false)
  185. case Requested:
  186. hostinfo.logger(c.l).WithField("relay", relay.String()).Info("Re-send CreateRelay request")
  187. // Re-send the CreateRelay request, in case the previous one was lost.
  188. m := NebulaControl{
  189. Type: NebulaControl_CreateRelayRequest,
  190. InitiatorRelayIndex: existingRelay.LocalIndex,
  191. RelayFromIp: uint32(c.lightHouse.myVpnIp),
  192. RelayToIp: uint32(vpnIp),
  193. }
  194. msg, err := m.Marshal()
  195. if err != nil {
  196. hostinfo.logger(c.l).
  197. WithError(err).
  198. Error("Failed to marshal Control message to create relay")
  199. } else {
  200. f.SendMessageToVpnIp(header.Control, 0, *relay, msg, make([]byte, 12), make([]byte, mtu))
  201. }
  202. default:
  203. hostinfo.logger(c.l).
  204. WithField("vpnIp", vpnIp).
  205. WithField("state", existingRelay.State).
  206. WithField("relayVpnIp", relayHostInfo.vpnIp).
  207. Errorf("Relay unexpected state")
  208. }
  209. } else {
  210. // No relays exist or requested yet.
  211. if relayHostInfo.remote != nil {
  212. idx, err := AddRelay(c.l, relayHostInfo, c.mainHostMap, vpnIp, nil, TerminalType, Requested)
  213. if err != nil {
  214. hostinfo.logger(c.l).WithField("relay", relay.String()).WithError(err).Info("Failed to add relay to hostmap")
  215. }
  216. m := NebulaControl{
  217. Type: NebulaControl_CreateRelayRequest,
  218. InitiatorRelayIndex: idx,
  219. RelayFromIp: uint32(c.lightHouse.myVpnIp),
  220. RelayToIp: uint32(vpnIp),
  221. }
  222. msg, err := m.Marshal()
  223. if err != nil {
  224. hostinfo.logger(c.l).
  225. WithError(err).
  226. Error("Failed to marshal Control message to create relay")
  227. } else {
  228. f.SendMessageToVpnIp(header.Control, 0, *relay, msg, make([]byte, 12), make([]byte, mtu))
  229. }
  230. }
  231. }
  232. }
  233. }
  234. // Increment the counter to increase our delay, linear backoff
  235. hostinfo.HandshakeCounter++
  236. // If a lighthouse triggered this attempt then we are still in the timer wheel and do not need to re-add
  237. if !lighthouseTriggered {
  238. //TODO: feel like we dupe handshake real fast in a tight loop, why?
  239. c.OutboundHandshakeTimer.Add(vpnIp, c.config.tryInterval*time.Duration(hostinfo.HandshakeCounter))
  240. }
  241. }
  242. func (c *HandshakeManager) AddVpnIp(vpnIp iputil.VpnIp, init func(*HostInfo)) *HostInfo {
  243. hostinfo, created := c.pendingHostMap.AddVpnIp(vpnIp, init)
  244. if created {
  245. c.OutboundHandshakeTimer.Add(vpnIp, c.config.tryInterval)
  246. c.metricInitiated.Inc(1)
  247. }
  248. return hostinfo
  249. }
  250. var (
  251. ErrExistingHostInfo = errors.New("existing hostinfo")
  252. ErrAlreadySeen = errors.New("already seen")
  253. ErrLocalIndexCollision = errors.New("local index collision")
  254. ErrExistingHandshake = errors.New("existing handshake")
  255. )
  256. // CheckAndComplete checks for any conflicts in the main and pending hostmap
  257. // before adding hostinfo to main. If err is nil, it was added. Otherwise err will be:
  258. //
  259. // ErrAlreadySeen if we already have an entry in the hostmap that has seen the
  260. // exact same handshake packet
  261. //
  262. // ErrExistingHostInfo if we already have an entry in the hostmap for this
  263. // VpnIp and the new handshake was older than the one we currently have
  264. //
  265. // ErrLocalIndexCollision if we already have an entry in the main or pending
  266. // hostmap for the hostinfo.localIndexId.
  267. func (c *HandshakeManager) CheckAndComplete(hostinfo *HostInfo, handshakePacket uint8, overwrite bool, f *Interface) (*HostInfo, error) {
  268. c.pendingHostMap.Lock()
  269. defer c.pendingHostMap.Unlock()
  270. c.mainHostMap.Lock()
  271. defer c.mainHostMap.Unlock()
  272. // Check if we already have a tunnel with this vpn ip
  273. existingHostInfo, found := c.mainHostMap.Hosts[hostinfo.vpnIp]
  274. if found && existingHostInfo != nil {
  275. // Is it just a delayed handshake packet?
  276. if bytes.Equal(hostinfo.HandshakePacket[handshakePacket], existingHostInfo.HandshakePacket[handshakePacket]) {
  277. return existingHostInfo, ErrAlreadySeen
  278. }
  279. // Is this a newer handshake?
  280. if existingHostInfo.lastHandshakeTime >= hostinfo.lastHandshakeTime {
  281. return existingHostInfo, ErrExistingHostInfo
  282. }
  283. existingHostInfo.logger(c.l).Info("Taking new handshake")
  284. }
  285. existingIndex, found := c.mainHostMap.Indexes[hostinfo.localIndexId]
  286. if found {
  287. // We have a collision, but for a different hostinfo
  288. return existingIndex, ErrLocalIndexCollision
  289. }
  290. existingIndex, found = c.pendingHostMap.Indexes[hostinfo.localIndexId]
  291. if found && existingIndex != hostinfo {
  292. // We have a collision, but for a different hostinfo
  293. return existingIndex, ErrLocalIndexCollision
  294. }
  295. existingRemoteIndex, found := c.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  296. if found && existingRemoteIndex != nil && existingRemoteIndex.vpnIp != hostinfo.vpnIp {
  297. // We have a collision, but this can happen since we can't control
  298. // the remote ID. Just log about the situation as a note.
  299. hostinfo.logger(c.l).
  300. WithField("remoteIndex", hostinfo.remoteIndexId).WithField("collision", existingRemoteIndex.vpnIp).
  301. Info("New host shadows existing host remoteIndex")
  302. }
  303. // Check if we are also handshaking with this vpn ip
  304. pendingHostInfo, found := c.pendingHostMap.Hosts[hostinfo.vpnIp]
  305. if found && pendingHostInfo != nil {
  306. if !overwrite {
  307. // We won, let our pending handshake win
  308. return pendingHostInfo, ErrExistingHandshake
  309. }
  310. // We lost, take this handshake and move any cached packets over so they get sent
  311. pendingHostInfo.ConnectionState.queueLock.Lock()
  312. hostinfo.packetStore = append(hostinfo.packetStore, pendingHostInfo.packetStore...)
  313. c.pendingHostMap.unlockedDeleteHostInfo(pendingHostInfo)
  314. pendingHostInfo.ConnectionState.queueLock.Unlock()
  315. pendingHostInfo.logger(c.l).Info("Handshake race lost, replacing pending handshake with completed tunnel")
  316. }
  317. if existingHostInfo != nil {
  318. // We are going to overwrite this entry, so remove the old references
  319. delete(c.mainHostMap.Hosts, existingHostInfo.vpnIp)
  320. delete(c.mainHostMap.Indexes, existingHostInfo.localIndexId)
  321. delete(c.mainHostMap.RemoteIndexes, existingHostInfo.remoteIndexId)
  322. for _, relayIdx := range existingHostInfo.relayState.CopyRelayForIdxs() {
  323. delete(c.mainHostMap.Relays, relayIdx)
  324. }
  325. }
  326. c.mainHostMap.addHostInfo(hostinfo, f)
  327. return existingHostInfo, nil
  328. }
  329. // Complete is a simpler version of CheckAndComplete when we already know we
  330. // won't have a localIndexId collision because we already have an entry in the
  331. // pendingHostMap
  332. func (c *HandshakeManager) Complete(hostinfo *HostInfo, f *Interface) {
  333. c.pendingHostMap.Lock()
  334. defer c.pendingHostMap.Unlock()
  335. c.mainHostMap.Lock()
  336. defer c.mainHostMap.Unlock()
  337. existingHostInfo, found := c.mainHostMap.Hosts[hostinfo.vpnIp]
  338. if found && existingHostInfo != nil {
  339. // We are going to overwrite this entry, so remove the old references
  340. delete(c.mainHostMap.Hosts, existingHostInfo.vpnIp)
  341. delete(c.mainHostMap.Indexes, existingHostInfo.localIndexId)
  342. delete(c.mainHostMap.RemoteIndexes, existingHostInfo.remoteIndexId)
  343. for _, relayIdx := range existingHostInfo.relayState.CopyRelayForIdxs() {
  344. delete(c.mainHostMap.Relays, relayIdx)
  345. }
  346. }
  347. existingRemoteIndex, found := c.mainHostMap.RemoteIndexes[hostinfo.remoteIndexId]
  348. if found && existingRemoteIndex != nil {
  349. // We have a collision, but this can happen since we can't control
  350. // the remote ID. Just log about the situation as a note.
  351. hostinfo.logger(c.l).
  352. WithField("remoteIndex", hostinfo.remoteIndexId).WithField("collision", existingRemoteIndex.vpnIp).
  353. Info("New host shadows existing host remoteIndex")
  354. }
  355. c.mainHostMap.addHostInfo(hostinfo, f)
  356. c.pendingHostMap.unlockedDeleteHostInfo(hostinfo)
  357. }
  358. // AddIndexHostInfo generates a unique localIndexId for this HostInfo
  359. // and adds it to the pendingHostMap. Will error if we are unable to generate
  360. // a unique localIndexId
  361. func (c *HandshakeManager) AddIndexHostInfo(h *HostInfo) error {
  362. c.pendingHostMap.Lock()
  363. defer c.pendingHostMap.Unlock()
  364. c.mainHostMap.RLock()
  365. defer c.mainHostMap.RUnlock()
  366. for i := 0; i < 32; i++ {
  367. index, err := generateIndex(c.l)
  368. if err != nil {
  369. return err
  370. }
  371. _, inPending := c.pendingHostMap.Indexes[index]
  372. _, inMain := c.mainHostMap.Indexes[index]
  373. if !inMain && !inPending {
  374. h.localIndexId = index
  375. c.pendingHostMap.Indexes[index] = h
  376. return nil
  377. }
  378. }
  379. return errors.New("failed to generate unique localIndexId")
  380. }
  381. func (c *HandshakeManager) addRemoteIndexHostInfo(index uint32, h *HostInfo) {
  382. c.pendingHostMap.addRemoteIndexHostInfo(index, h)
  383. }
  384. func (c *HandshakeManager) DeleteHostInfo(hostinfo *HostInfo) {
  385. //l.Debugln("Deleting pending hostinfo :", hostinfo)
  386. c.pendingHostMap.DeleteHostInfo(hostinfo)
  387. }
  388. func (c *HandshakeManager) QueryIndex(index uint32) (*HostInfo, error) {
  389. return c.pendingHostMap.QueryIndex(index)
  390. }
  391. func (c *HandshakeManager) EmitStats() {
  392. c.pendingHostMap.EmitStats("pending")
  393. c.mainHostMap.EmitStats("main")
  394. }
  395. // Utility functions below
  396. func generateIndex(l *logrus.Logger) (uint32, error) {
  397. b := make([]byte, 4)
  398. // Let zero mean we don't know the ID, so don't generate zero
  399. var index uint32
  400. for index == 0 {
  401. _, err := rand.Read(b)
  402. if err != nil {
  403. l.Errorln(err)
  404. return 0, err
  405. }
  406. index = binary.BigEndian.Uint32(b)
  407. }
  408. if l.Level >= logrus.DebugLevel {
  409. l.WithField("index", index).
  410. Debug("Generated index")
  411. }
  412. return index, nil
  413. }
  414. func hsTimeout(tries int, interval time.Duration) time.Duration {
  415. return time.Duration(tries / 2 * ((2 * int(interval)) + (tries-1)*int(interval)))
  416. }