1
0

control.go 10 KB

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