control.go 6.8 KB

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