control.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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 services), 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, 1)
  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. // ListHostmapHosts returns details about the actual or pending (handshaking) hostmap by vpn ip
  83. func (c *Control) ListHostmapHosts(pendingMap bool) []ControlHostInfo {
  84. if pendingMap {
  85. return listHostMapHosts(c.f.handshakeManager.pendingHostMap)
  86. } else {
  87. return listHostMapHosts(c.f.hostMap)
  88. }
  89. }
  90. // ListHostmapIndexes returns details about the actual or pending (handshaking) hostmap by local index id
  91. func (c *Control) ListHostmapIndexes(pendingMap bool) []ControlHostInfo {
  92. if pendingMap {
  93. return listHostMapIndexes(c.f.handshakeManager.pendingHostMap)
  94. } else {
  95. return listHostMapIndexes(c.f.hostMap)
  96. }
  97. }
  98. // GetHostInfoByVpnIp returns a single tunnels hostInfo, or nil if not found
  99. func (c *Control) GetHostInfoByVpnIp(vpnIp iputil.VpnIp, pending bool) *ControlHostInfo {
  100. var hm *HostMap
  101. if pending {
  102. hm = c.f.handshakeManager.pendingHostMap
  103. } else {
  104. hm = c.f.hostMap
  105. }
  106. h, err := hm.QueryVpnIp(vpnIp)
  107. if err != nil {
  108. return nil
  109. }
  110. ch := copyHostInfo(h, c.f.hostMap.preferredRanges)
  111. return &ch
  112. }
  113. // SetRemoteForTunnel forces a tunnel to use a specific remote
  114. func (c *Control) SetRemoteForTunnel(vpnIp iputil.VpnIp, addr udp.Addr) *ControlHostInfo {
  115. hostInfo, err := c.f.hostMap.QueryVpnIp(vpnIp)
  116. if err != nil {
  117. return nil
  118. }
  119. hostInfo.SetRemote(addr.Copy())
  120. ch := copyHostInfo(hostInfo, c.f.hostMap.preferredRanges)
  121. return &ch
  122. }
  123. // CloseTunnel closes a fully established tunnel. If localOnly is false it will notify the remote end as well.
  124. func (c *Control) CloseTunnel(vpnIp iputil.VpnIp, localOnly bool) bool {
  125. hostInfo, err := c.f.hostMap.QueryVpnIp(vpnIp)
  126. if err != nil {
  127. return false
  128. }
  129. if !localOnly {
  130. c.f.send(
  131. header.CloseTunnel,
  132. 0,
  133. hostInfo.ConnectionState,
  134. hostInfo,
  135. []byte{},
  136. make([]byte, 12, 12),
  137. make([]byte, mtu),
  138. )
  139. }
  140. c.f.closeTunnel(hostInfo)
  141. return true
  142. }
  143. // CloseAllTunnels is just like CloseTunnel except it goes through and shuts them all down, optionally you can avoid shutting down lighthouse tunnels
  144. // the int returned is a count of tunnels closed
  145. func (c *Control) CloseAllTunnels(excludeLighthouses bool) (closed int) {
  146. //TODO: this is probably better as a function in ConnectionManager or HostMap directly
  147. lighthouses := c.f.lightHouse.GetLighthouses()
  148. shutdown := func(h *HostInfo) {
  149. if excludeLighthouses {
  150. if _, ok := lighthouses[h.vpnIp]; ok {
  151. return
  152. }
  153. }
  154. c.f.send(header.CloseTunnel, 0, h.ConnectionState, h, []byte{}, make([]byte, 12, 12), make([]byte, mtu))
  155. c.f.closeTunnel(h)
  156. c.l.WithField("vpnIp", h.vpnIp).WithField("udpAddr", h.remote).
  157. Debug("Sending close tunnel message")
  158. closed++
  159. }
  160. // Learn which hosts are being used as relays, so we can shut them down last.
  161. relayingHosts := map[iputil.VpnIp]*HostInfo{}
  162. // Grab the hostMap lock to access the Relays map
  163. c.f.hostMap.Lock()
  164. for _, relayingHost := range c.f.hostMap.Relays {
  165. relayingHosts[relayingHost.vpnIp] = relayingHost
  166. }
  167. c.f.hostMap.Unlock()
  168. hostInfos := []*HostInfo{}
  169. // Grab the hostMap lock to access the Hosts map
  170. c.f.hostMap.Lock()
  171. for _, relayHost := range c.f.hostMap.Indexes {
  172. if _, ok := relayingHosts[relayHost.vpnIp]; !ok {
  173. hostInfos = append(hostInfos, relayHost)
  174. }
  175. }
  176. c.f.hostMap.Unlock()
  177. for _, h := range hostInfos {
  178. shutdown(h)
  179. }
  180. for _, h := range relayingHosts {
  181. shutdown(h)
  182. }
  183. return
  184. }
  185. func copyHostInfo(h *HostInfo, preferredRanges []*net.IPNet) ControlHostInfo {
  186. chi := ControlHostInfo{
  187. VpnIp: h.vpnIp.ToIP(),
  188. LocalIndex: h.localIndexId,
  189. RemoteIndex: h.remoteIndexId,
  190. RemoteAddrs: h.remotes.CopyAddrs(preferredRanges),
  191. CachedPackets: len(h.packetStore),
  192. CurrentRelaysToMe: h.relayState.CopyRelayIps(),
  193. CurrentRelaysThroughMe: h.relayState.CopyRelayForIps(),
  194. }
  195. if h.ConnectionState != nil {
  196. chi.MessageCounter = h.ConnectionState.messageCounter.Load()
  197. }
  198. if c := h.GetCert(); c != nil {
  199. chi.Cert = c.Copy()
  200. }
  201. if h.remote != nil {
  202. chi.CurrentRemote = h.remote.Copy()
  203. }
  204. return chi
  205. }
  206. func listHostMapHosts(hm *HostMap) []ControlHostInfo {
  207. hm.RLock()
  208. hosts := make([]ControlHostInfo, len(hm.Hosts))
  209. i := 0
  210. for _, v := range hm.Hosts {
  211. hosts[i] = copyHostInfo(v, hm.preferredRanges)
  212. i++
  213. }
  214. hm.RUnlock()
  215. return hosts
  216. }
  217. func listHostMapIndexes(hm *HostMap) []ControlHostInfo {
  218. hm.RLock()
  219. hosts := make([]ControlHostInfo, len(hm.Indexes))
  220. i := 0
  221. for _, v := range hm.Indexes {
  222. hosts[i] = copyHostInfo(v, hm.preferredRanges)
  223. i++
  224. }
  225. hm.RUnlock()
  226. return hosts
  227. }