control.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. package nebula
  2. import (
  3. "context"
  4. "net"
  5. "os"
  6. "os/signal"
  7. "sync/atomic"
  8. "syscall"
  9. "github.com/sirupsen/logrus"
  10. "github.com/slackhq/nebula/cert"
  11. "github.com/slackhq/nebula/header"
  12. "github.com/slackhq/nebula/iputil"
  13. "github.com/slackhq/nebula/udp"
  14. )
  15. // Every interaction here needs to take extra care to copy memory and not return or use arguments "as is" when touching
  16. // core. This means copying IP objects, slices, de-referencing pointers and taking the actual value, etc
  17. type Control struct {
  18. f *Interface
  19. l *logrus.Logger
  20. cancel context.CancelFunc
  21. sshStart func()
  22. statsStart func()
  23. dnsStart func()
  24. }
  25. type ControlHostInfo struct {
  26. VpnIp net.IP `json:"vpnIp"`
  27. LocalIndex uint32 `json:"localIndex"`
  28. RemoteIndex uint32 `json:"remoteIndex"`
  29. RemoteAddrs []*udp.Addr `json:"remoteAddrs"`
  30. CachedPackets int `json:"cachedPackets"`
  31. Cert *cert.NebulaCertificate `json:"cert"`
  32. MessageCounter uint64 `json:"messageCounter"`
  33. CurrentRemote *udp.Addr `json:"currentRemote"`
  34. }
  35. // Start actually runs nebula, this is a nonblocking call. To block use Control.ShutdownBlock()
  36. func (c *Control) Start() {
  37. // Activate the interface
  38. c.f.activate()
  39. // Call all the delayed funcs that waited patiently for the interface to be created.
  40. if c.sshStart != nil {
  41. go c.sshStart()
  42. }
  43. if c.statsStart != nil {
  44. go c.statsStart()
  45. }
  46. if c.dnsStart != nil {
  47. go c.dnsStart()
  48. }
  49. // Start reading packets.
  50. c.f.run()
  51. }
  52. // Stop signals nebula to shutdown, returns after the shutdown is complete
  53. func (c *Control) Stop() {
  54. //TODO: stop tun and udp routines, the lock on hostMap effectively does that though
  55. c.CloseAllTunnels(false)
  56. if err := c.f.Close(); err != nil {
  57. c.l.WithError(err).Error("Close interface failed")
  58. }
  59. c.cancel()
  60. c.l.Info("Goodbye")
  61. }
  62. // ShutdownBlock will listen for and block on term and interrupt signals, calling Control.Stop() once signalled
  63. func (c *Control) ShutdownBlock() {
  64. sigChan := make(chan os.Signal)
  65. signal.Notify(sigChan, syscall.SIGTERM)
  66. signal.Notify(sigChan, syscall.SIGINT)
  67. rawSig := <-sigChan
  68. sig := rawSig.String()
  69. c.l.WithField("signal", sig).Info("Caught signal, shutting down")
  70. c.Stop()
  71. }
  72. // RebindUDPServer asks the UDP listener to rebind it's listener. Mainly used on mobile clients when interfaces change
  73. func (c *Control) RebindUDPServer() {
  74. _ = c.f.outside.Rebind()
  75. // Trigger a lighthouse update, useful for mobile clients that should have an update interval of 0
  76. c.f.lightHouse.SendUpdate(c.f)
  77. // Let the main interface know that we rebound so that underlying tunnels know to trigger punches from their remotes
  78. c.f.rebindCount++
  79. }
  80. // ListHostmap returns details about the actual or pending (handshaking) hostmap
  81. func (c *Control) ListHostmap(pendingMap bool) []ControlHostInfo {
  82. if pendingMap {
  83. return listHostMap(c.f.handshakeManager.pendingHostMap)
  84. } else {
  85. return listHostMap(c.f.hostMap)
  86. }
  87. }
  88. // GetHostInfoByVpnIp returns a single tunnels hostInfo, or nil if not found
  89. func (c *Control) GetHostInfoByVpnIp(vpnIp iputil.VpnIp, pending bool) *ControlHostInfo {
  90. var hm *HostMap
  91. if pending {
  92. hm = c.f.handshakeManager.pendingHostMap
  93. } else {
  94. hm = c.f.hostMap
  95. }
  96. h, err := hm.QueryVpnIp(vpnIp)
  97. if err != nil {
  98. return nil
  99. }
  100. ch := copyHostInfo(h, c.f.hostMap.preferredRanges)
  101. return &ch
  102. }
  103. // SetRemoteForTunnel forces a tunnel to use a specific remote
  104. func (c *Control) SetRemoteForTunnel(vpnIp iputil.VpnIp, addr udp.Addr) *ControlHostInfo {
  105. hostInfo, err := c.f.hostMap.QueryVpnIp(vpnIp)
  106. if err != nil {
  107. return nil
  108. }
  109. hostInfo.SetRemote(addr.Copy())
  110. ch := copyHostInfo(hostInfo, c.f.hostMap.preferredRanges)
  111. return &ch
  112. }
  113. // CloseTunnel closes a fully established tunnel. If localOnly is false it will notify the remote end as well.
  114. func (c *Control) CloseTunnel(vpnIp iputil.VpnIp, localOnly bool) bool {
  115. hostInfo, err := c.f.hostMap.QueryVpnIp(vpnIp)
  116. if err != nil {
  117. return false
  118. }
  119. if !localOnly {
  120. c.f.send(
  121. header.CloseTunnel,
  122. 0,
  123. hostInfo.ConnectionState,
  124. hostInfo,
  125. hostInfo.remote,
  126. []byte{},
  127. make([]byte, 12, 12),
  128. make([]byte, mtu),
  129. )
  130. }
  131. c.f.closeTunnel(hostInfo, false)
  132. return true
  133. }
  134. // CloseAllTunnels is just like CloseTunnel except it goes through and shuts them all down, optionally you can avoid shutting down lighthouse tunnels
  135. // the int returned is a count of tunnels closed
  136. func (c *Control) CloseAllTunnels(excludeLighthouses bool) (closed int) {
  137. //TODO: this is probably better as a function in ConnectionManager or HostMap directly
  138. c.f.hostMap.Lock()
  139. for _, h := range c.f.hostMap.Hosts {
  140. if excludeLighthouses {
  141. if _, ok := c.f.lightHouse.lighthouses[h.vpnIp]; ok {
  142. continue
  143. }
  144. }
  145. if h.ConnectionState.ready {
  146. c.f.send(header.CloseTunnel, 0, h.ConnectionState, h, h.remote, []byte{}, make([]byte, 12, 12), make([]byte, mtu))
  147. c.f.closeTunnel(h, true)
  148. c.l.WithField("vpnIp", h.vpnIp).WithField("udpAddr", h.remote).
  149. Debug("Sending close tunnel message")
  150. closed++
  151. }
  152. }
  153. c.f.hostMap.Unlock()
  154. return
  155. }
  156. func copyHostInfo(h *HostInfo, preferredRanges []*net.IPNet) ControlHostInfo {
  157. chi := ControlHostInfo{
  158. VpnIp: h.vpnIp.ToIP(),
  159. LocalIndex: h.localIndexId,
  160. RemoteIndex: h.remoteIndexId,
  161. RemoteAddrs: h.remotes.CopyAddrs(preferredRanges),
  162. CachedPackets: len(h.packetStore),
  163. }
  164. if h.ConnectionState != nil {
  165. chi.MessageCounter = atomic.LoadUint64(&h.ConnectionState.atomicMessageCounter)
  166. }
  167. if c := h.GetCert(); c != nil {
  168. chi.Cert = c.Copy()
  169. }
  170. if h.remote != nil {
  171. chi.CurrentRemote = h.remote.Copy()
  172. }
  173. return chi
  174. }
  175. func listHostMap(hm *HostMap) []ControlHostInfo {
  176. hm.RLock()
  177. hosts := make([]ControlHostInfo, len(hm.Hosts))
  178. i := 0
  179. for _, v := range hm.Hosts {
  180. hosts[i] = copyHostInfo(v, hm.preferredRanges)
  181. i++
  182. }
  183. hm.RUnlock()
  184. return hosts
  185. }