1
0

control.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. package nebula
  2. import (
  3. "context"
  4. "errors"
  5. "net/netip"
  6. "os"
  7. "os/signal"
  8. "sync"
  9. "syscall"
  10. "github.com/sirupsen/logrus"
  11. "github.com/slackhq/nebula/cert"
  12. "github.com/slackhq/nebula/header"
  13. "github.com/slackhq/nebula/overlay"
  14. )
  15. type RunState int
  16. const (
  17. Stopped RunState = 0 // The control has yet to be started
  18. Started RunState = 1 // The control has been started
  19. Stopping RunState = 2 // The control is stopping
  20. )
  21. var ErrAlreadyStarted = errors.New("nebula is already started")
  22. // Every interaction here needs to take extra care to copy memory and not return or use arguments "as is" when touching
  23. // core. This means copying IP objects, slices, de-referencing pointers and taking the actual value, etc
  24. type controlEach func(h *HostInfo)
  25. type controlHostLister interface {
  26. QueryVpnAddr(vpnAddr netip.Addr) *HostInfo
  27. ForEachIndex(each controlEach)
  28. ForEachVpnAddr(each controlEach)
  29. GetPreferredRanges() []netip.Prefix
  30. }
  31. type Control struct {
  32. stateLock sync.Mutex
  33. state RunState
  34. f *Interface
  35. l *logrus.Logger
  36. ctx context.Context
  37. cancel context.CancelFunc
  38. sshStart func()
  39. statsStart func()
  40. dnsStart func()
  41. lighthouseStart func()
  42. connectionManagerStart func(context.Context)
  43. }
  44. type ControlHostInfo struct {
  45. VpnAddrs []netip.Addr `json:"vpnAddrs"`
  46. LocalIndex uint32 `json:"localIndex"`
  47. RemoteIndex uint32 `json:"remoteIndex"`
  48. RemoteAddrs []netip.AddrPort `json:"remoteAddrs"`
  49. Cert cert.Certificate `json:"cert"`
  50. MessageCounter uint64 `json:"messageCounter"`
  51. CurrentRemote netip.AddrPort `json:"currentRemote"`
  52. CurrentRelaysToMe []netip.Addr `json:"currentRelaysToMe"`
  53. CurrentRelaysThroughMe []netip.Addr `json:"currentRelaysThroughMe"`
  54. }
  55. // Start actually runs nebula, this is a nonblocking call.
  56. // The returned function blocks until nebula has fully stopped and returns the
  57. // first fatal reader error (if any). A nil error means nebula shut down
  58. // gracefully; a non-nil error means a reader hit an unexpected failure that
  59. // triggered the shutdown.
  60. func (c *Control) Start() (func() error, error) {
  61. c.stateLock.Lock()
  62. if c.state != Stopped {
  63. c.stateLock.Unlock()
  64. return nil, ErrAlreadyStarted
  65. }
  66. // Activate the interface
  67. err := c.f.activate()
  68. if err != nil {
  69. c.stateLock.Unlock()
  70. return nil, err
  71. }
  72. // Call all the delayed funcs that waited patiently for the interface to be created.
  73. if c.sshStart != nil {
  74. go c.sshStart()
  75. }
  76. if c.statsStart != nil {
  77. go c.statsStart()
  78. }
  79. if c.dnsStart != nil {
  80. go c.dnsStart()
  81. }
  82. if c.connectionManagerStart != nil {
  83. go c.connectionManagerStart(c.ctx)
  84. }
  85. if c.lighthouseStart != nil {
  86. c.lighthouseStart()
  87. }
  88. c.f.triggerShutdown = c.Stop
  89. // Start reading packets.
  90. c.state = Started
  91. c.stateLock.Unlock()
  92. return c.f.run()
  93. }
  94. func (c *Control) State() RunState {
  95. c.stateLock.Lock()
  96. defer c.stateLock.Unlock()
  97. return c.state
  98. }
  99. func (c *Control) Context() context.Context {
  100. return c.ctx
  101. }
  102. // Stop is a non-blocking call that signals nebula to close all tunnels and shut down
  103. func (c *Control) Stop() {
  104. c.stateLock.Lock()
  105. if c.state != Started {
  106. c.stateLock.Unlock()
  107. // We are stopping or stopped already
  108. return
  109. }
  110. c.state = Stopping
  111. c.stateLock.Unlock()
  112. // Stop the handshakeManager (and other services), to prevent new tunnels from
  113. // being created while we're shutting them all down.
  114. c.cancel()
  115. c.CloseAllTunnels(false)
  116. if err := c.f.Close(); err != nil {
  117. c.l.WithError(err).Error("Close interface failed")
  118. }
  119. c.stateLock.Lock()
  120. c.state = Stopped
  121. c.stateLock.Unlock()
  122. }
  123. // ShutdownBlock will listen for and block on term and interrupt signals, calling Control.Stop() once signalled
  124. func (c *Control) ShutdownBlock() {
  125. sigChan := make(chan os.Signal, 1)
  126. signal.Notify(sigChan, syscall.SIGTERM)
  127. signal.Notify(sigChan, syscall.SIGINT)
  128. rawSig := <-sigChan
  129. sig := rawSig.String()
  130. c.l.WithField("signal", sig).Info("Caught signal, shutting down")
  131. c.Stop()
  132. }
  133. // RebindUDPServer asks the UDP listener to rebind it's listener. Mainly used on mobile clients when interfaces change
  134. func (c *Control) RebindUDPServer() {
  135. _ = c.f.outside.Rebind()
  136. // Trigger a lighthouse update, useful for mobile clients that should have an update interval of 0
  137. c.f.lightHouse.SendUpdate()
  138. // Let the main interface know that we rebound so that underlying tunnels know to trigger punches from their remotes
  139. c.f.rebindCount++
  140. }
  141. // ListHostmapHosts returns details about the actual or pending (handshaking) hostmap by vpn ip
  142. func (c *Control) ListHostmapHosts(pendingMap bool) []ControlHostInfo {
  143. if pendingMap {
  144. return listHostMapHosts(c.f.handshakeManager)
  145. } else {
  146. return listHostMapHosts(c.f.hostMap)
  147. }
  148. }
  149. // ListHostmapIndexes returns details about the actual or pending (handshaking) hostmap by local index id
  150. func (c *Control) ListHostmapIndexes(pendingMap bool) []ControlHostInfo {
  151. if pendingMap {
  152. return listHostMapIndexes(c.f.handshakeManager)
  153. } else {
  154. return listHostMapIndexes(c.f.hostMap)
  155. }
  156. }
  157. // GetCertByVpnIp returns the authenticated certificate of the given vpn IP, or nil if not found
  158. func (c *Control) GetCertByVpnIp(vpnIp netip.Addr) cert.Certificate {
  159. if c.f.myVpnAddrsTable.Contains(vpnIp) {
  160. // Only returning the default certificate since its impossible
  161. // for any other host but ourselves to have more than 1
  162. return c.f.pki.getCertState().GetDefaultCertificate().Copy()
  163. }
  164. hi := c.f.hostMap.QueryVpnAddr(vpnIp)
  165. if hi == nil {
  166. return nil
  167. }
  168. return hi.GetCert().Certificate.Copy()
  169. }
  170. // CreateTunnel creates a new tunnel to the given vpn ip.
  171. func (c *Control) CreateTunnel(vpnIp netip.Addr) {
  172. c.f.handshakeManager.StartHandshake(vpnIp, nil)
  173. }
  174. // PrintTunnel creates a new tunnel to the given vpn ip.
  175. func (c *Control) PrintTunnel(vpnIp netip.Addr) *ControlHostInfo {
  176. hi := c.f.hostMap.QueryVpnAddr(vpnIp)
  177. if hi == nil {
  178. return nil
  179. }
  180. chi := copyHostInfo(hi, c.f.hostMap.GetPreferredRanges())
  181. return &chi
  182. }
  183. // QueryLighthouse queries the lighthouse.
  184. func (c *Control) QueryLighthouse(vpnIp netip.Addr) *CacheMap {
  185. hi := c.f.lightHouse.Query(vpnIp)
  186. if hi == nil {
  187. return nil
  188. }
  189. return hi.CopyCache()
  190. }
  191. // GetHostInfoByVpnAddr returns a single tunnels hostInfo, or nil if not found
  192. // Caller should take care to Unmap() any 4in6 addresses prior to calling.
  193. func (c *Control) GetHostInfoByVpnAddr(vpnAddr netip.Addr, pending bool) *ControlHostInfo {
  194. var hl controlHostLister
  195. if pending {
  196. hl = c.f.handshakeManager
  197. } else {
  198. hl = c.f.hostMap
  199. }
  200. h := hl.QueryVpnAddr(vpnAddr)
  201. if h == nil {
  202. return nil
  203. }
  204. ch := copyHostInfo(h, c.f.hostMap.GetPreferredRanges())
  205. return &ch
  206. }
  207. // SetRemoteForTunnel forces a tunnel to use a specific remote
  208. // Caller should take care to Unmap() any 4in6 addresses prior to calling.
  209. func (c *Control) SetRemoteForTunnel(vpnIp netip.Addr, addr netip.AddrPort) *ControlHostInfo {
  210. hostInfo := c.f.hostMap.QueryVpnAddr(vpnIp)
  211. if hostInfo == nil {
  212. return nil
  213. }
  214. hostInfo.SetRemote(addr)
  215. ch := copyHostInfo(hostInfo, c.f.hostMap.GetPreferredRanges())
  216. return &ch
  217. }
  218. // CloseTunnel closes a fully established tunnel. If localOnly is false it will notify the remote end as well.
  219. // Caller should take care to Unmap() any 4in6 addresses prior to calling.
  220. func (c *Control) CloseTunnel(vpnIp netip.Addr, localOnly bool) bool {
  221. hostInfo := c.f.hostMap.QueryVpnAddr(vpnIp)
  222. if hostInfo == nil {
  223. return false
  224. }
  225. if !localOnly {
  226. c.f.send(
  227. header.CloseTunnel,
  228. 0,
  229. hostInfo.ConnectionState,
  230. hostInfo,
  231. []byte{},
  232. make([]byte, 12, 12),
  233. make([]byte, mtu),
  234. )
  235. }
  236. c.f.closeTunnel(hostInfo)
  237. return true
  238. }
  239. // CloseAllTunnels is just like CloseTunnel except it goes through and shuts them all down, optionally you can avoid shutting down lighthouse tunnels
  240. // the int returned is a count of tunnels closed
  241. func (c *Control) CloseAllTunnels(excludeLighthouses bool) (closed int) {
  242. shutdown := func(h *HostInfo) {
  243. if excludeLighthouses && c.f.lightHouse.IsAnyLighthouseAddr(h.vpnAddrs) {
  244. return
  245. }
  246. c.f.send(header.CloseTunnel, 0, h.ConnectionState, h, []byte{}, make([]byte, 12, 12), make([]byte, mtu))
  247. c.f.closeTunnel(h)
  248. c.l.WithField("vpnAddrs", h.vpnAddrs).WithField("udpAddr", h.remote).
  249. Debug("Sending close tunnel message")
  250. closed++
  251. }
  252. // Learn which hosts are being used as relays, so we can shut them down last.
  253. relayingHosts := map[netip.Addr]*HostInfo{}
  254. // Grab the hostMap lock to access the Relays map
  255. c.f.hostMap.Lock()
  256. for _, relayingHost := range c.f.hostMap.Relays {
  257. relayingHosts[relayingHost.vpnAddrs[0]] = relayingHost
  258. }
  259. c.f.hostMap.Unlock()
  260. hostInfos := []*HostInfo{}
  261. // Grab the hostMap lock to access the Hosts map
  262. c.f.hostMap.Lock()
  263. for _, relayHost := range c.f.hostMap.Indexes {
  264. if _, ok := relayingHosts[relayHost.vpnAddrs[0]]; !ok {
  265. hostInfos = append(hostInfos, relayHost)
  266. }
  267. }
  268. c.f.hostMap.Unlock()
  269. for _, h := range hostInfos {
  270. shutdown(h)
  271. }
  272. for _, h := range relayingHosts {
  273. shutdown(h)
  274. }
  275. return
  276. }
  277. func (c *Control) Device() overlay.Device {
  278. return c.f.inside
  279. }
  280. func copyHostInfo(h *HostInfo, preferredRanges []netip.Prefix) ControlHostInfo {
  281. chi := ControlHostInfo{
  282. VpnAddrs: make([]netip.Addr, len(h.vpnAddrs)),
  283. LocalIndex: h.localIndexId,
  284. RemoteIndex: h.remoteIndexId,
  285. RemoteAddrs: h.remotes.CopyAddrs(preferredRanges),
  286. CurrentRelaysToMe: h.relayState.CopyRelayIps(),
  287. CurrentRelaysThroughMe: h.relayState.CopyRelayForIps(),
  288. CurrentRemote: h.remote,
  289. }
  290. for i, a := range h.vpnAddrs {
  291. chi.VpnAddrs[i] = a
  292. }
  293. if h.ConnectionState != nil {
  294. chi.MessageCounter = h.ConnectionState.messageCounter.Load()
  295. }
  296. if c := h.GetCert(); c != nil {
  297. chi.Cert = c.Certificate.Copy()
  298. }
  299. return chi
  300. }
  301. func listHostMapHosts(hl controlHostLister) []ControlHostInfo {
  302. hosts := make([]ControlHostInfo, 0)
  303. pr := hl.GetPreferredRanges()
  304. hl.ForEachVpnAddr(func(hostinfo *HostInfo) {
  305. hosts = append(hosts, copyHostInfo(hostinfo, pr))
  306. })
  307. return hosts
  308. }
  309. func listHostMapIndexes(hl controlHostLister) []ControlHostInfo {
  310. hosts := make([]ControlHostInfo, 0)
  311. pr := hl.GetPreferredRanges()
  312. hl.ForEachIndex(func(hostinfo *HostInfo) {
  313. hosts = append(hosts, copyHostInfo(hostinfo, pr))
  314. })
  315. return hosts
  316. }