control.go 6.8 KB

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