3
0

control.go 7.8 KB

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