control.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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 reports the
  61. // fatal reader error (nil on a clean shutdown). Calling it is equivalent to
  62. // calling Wait.
  63. func (c *Control) Start() (func() error, error) {
  64. c.stateLock.Lock()
  65. defer c.stateLock.Unlock()
  66. switch c.state {
  67. case StateReady:
  68. //yay!
  69. case StateStopped, StateStopping:
  70. return nil, ErrAlreadyStopped
  71. case StateStarted:
  72. return nil, ErrAlreadyStarted
  73. default:
  74. return nil, ErrUnknownState
  75. }
  76. // Activate the interface
  77. err := c.f.activate()
  78. if err != nil {
  79. // Cancel before Close so a caller returning from Wait always observes a dead Context
  80. c.cancel()
  81. _ = c.f.Close()
  82. c.state = StateStopped
  83. return nil, err
  84. }
  85. // Call all the delayed funcs that waited patiently for the interface to be created.
  86. if c.sshStart != nil {
  87. go c.sshStart()
  88. }
  89. if c.statsStart != nil {
  90. go c.statsStart()
  91. }
  92. if c.dnsStart != nil {
  93. go c.dnsStart()
  94. }
  95. if c.connectionManagerStart != nil {
  96. go c.connectionManagerStart(c.ctx)
  97. }
  98. if c.lighthouseStart != nil {
  99. c.lighthouseStart()
  100. }
  101. c.f.triggerShutdown = c.Stop
  102. // Start reading packets.
  103. c.f.run()
  104. c.state = StateStarted
  105. return c.Wait, nil
  106. }
  107. func (c *Control) State() RunState {
  108. c.stateLock.Lock()
  109. defer c.stateLock.Unlock()
  110. return c.state
  111. }
  112. func (c *Control) Context() context.Context {
  113. return c.ctx
  114. }
  115. // Stop tears nebula down, closing all tunnels and releasing everything it holds.
  116. // Use Wait to block until the shutdown has completed.
  117. // A Control that has been stopped cannot be started again, Start will return ErrAlreadyStopped.
  118. func (c *Control) Stop() {
  119. c.stateLock.Lock()
  120. switch c.state {
  121. case StateStarted:
  122. // Fall through to the full teardown below
  123. case StateReady:
  124. // Never started
  125. c.cancel()
  126. c.state = StateStopped
  127. if err := c.f.Close(); err != nil {
  128. c.l.Error("Close interface failed", "error", err)
  129. }
  130. c.stateLock.Unlock()
  131. return
  132. default:
  133. c.stateLock.Unlock()
  134. // We are stopping or stopped already
  135. return
  136. }
  137. c.state = StateStopping
  138. c.stateLock.Unlock()
  139. // Closing tunnels can be slow with a large hostmap, don't hold the lock for it
  140. c.cancel()
  141. c.CloseAllTunnels(false)
  142. c.stateLock.Lock()
  143. c.state = StateStopped
  144. if err := c.f.Close(); err != nil {
  145. c.l.Error("Close interface failed", "error", err)
  146. }
  147. c.stateLock.Unlock()
  148. }
  149. // Wait blocks until nebula has fully stopped, either via Stop or an internal fatal error,
  150. // and returns the first fatal packet reader error if there was one.
  151. // It is safe to call from multiple goroutines and at any point in the lifecycle,
  152. // but a Wait on a Control that is never started and never stopped will block forever.
  153. func (c *Control) Wait() error {
  154. return c.f.wait()
  155. }
  156. // ShutdownBlock will listen for and block on term and interrupt signals, calling Control.Stop() once signalled
  157. func (c *Control) ShutdownBlock() {
  158. sigChan := make(chan os.Signal, 1)
  159. signal.Notify(sigChan, syscall.SIGTERM)
  160. signal.Notify(sigChan, syscall.SIGINT)
  161. rawSig := <-sigChan
  162. sig := rawSig.String()
  163. c.l.Info("Caught signal, shutting down", "signal", sig)
  164. c.Stop()
  165. }
  166. // RebindUDPServer asks the UDP listener to rebind it's listener. Mainly used on mobile clients when interfaces change.
  167. func (c *Control) RebindUDPServer() {
  168. c.stateLock.Lock()
  169. defer c.stateLock.Unlock()
  170. if c.state != StateStarted {
  171. return
  172. }
  173. _ = c.f.outside.Rebind()
  174. // Trigger a lighthouse update, useful for mobile clients that should have an update interval of 0
  175. c.f.lightHouse.SendUpdate()
  176. // Let the main interface know that we rebound so that underlying tunnels know to trigger punches from their remotes
  177. c.f.rebindCount++
  178. }
  179. // ListHostmapHosts returns details about the actual or pending (handshaking) hostmap by vpn ip
  180. func (c *Control) ListHostmapHosts(pendingMap bool) []ControlHostInfo {
  181. if pendingMap {
  182. return listHostMapHosts(c.f.handshakeManager)
  183. } else {
  184. return listHostMapHosts(c.f.hostMap)
  185. }
  186. }
  187. // ListHostmapIndexes returns details about the actual or pending (handshaking) hostmap by local index id
  188. func (c *Control) ListHostmapIndexes(pendingMap bool) []ControlHostInfo {
  189. if pendingMap {
  190. return listHostMapIndexes(c.f.handshakeManager)
  191. } else {
  192. return listHostMapIndexes(c.f.hostMap)
  193. }
  194. }
  195. // GetCertByVpnIp returns the authenticated certificate of the given vpn IP, or nil if not found
  196. func (c *Control) GetCertByVpnIp(vpnIp netip.Addr) cert.Certificate {
  197. if c.f.myVpnAddrsTable.Contains(vpnIp) {
  198. // Only returning the default certificate since its impossible
  199. // for any other host but ourselves to have more than 1
  200. return c.f.pki.getCertState().GetDefaultCertificate().Copy()
  201. }
  202. hi := c.f.hostMap.QueryVpnAddr(vpnIp)
  203. if hi == nil {
  204. return nil
  205. }
  206. return hi.GetCert().Certificate.Copy()
  207. }
  208. // CreateTunnel creates a new tunnel to the given vpn ip.
  209. func (c *Control) CreateTunnel(vpnIp netip.Addr) {
  210. c.f.handshakeManager.StartHandshake(vpnIp, nil)
  211. }
  212. // PrintTunnel creates a new tunnel to the given vpn ip.
  213. func (c *Control) PrintTunnel(vpnIp netip.Addr) *ControlHostInfo {
  214. hi := c.f.hostMap.QueryVpnAddr(vpnIp)
  215. if hi == nil {
  216. return nil
  217. }
  218. chi := copyHostInfo(hi, c.f.hostMap.GetPreferredRanges())
  219. return &chi
  220. }
  221. // QueryLighthouse queries the lighthouse.
  222. func (c *Control) QueryLighthouse(vpnIp netip.Addr) *CacheMap {
  223. hi := c.f.lightHouse.Query(vpnIp)
  224. if hi == nil {
  225. return nil
  226. }
  227. return hi.CopyCache()
  228. }
  229. // GetHostInfoByVpnAddr returns a single tunnels hostInfo, or nil if not found
  230. // Caller should take care to Unmap() any 4in6 addresses prior to calling.
  231. func (c *Control) GetHostInfoByVpnAddr(vpnAddr netip.Addr, pending bool) *ControlHostInfo {
  232. var hl controlHostLister
  233. if pending {
  234. hl = c.f.handshakeManager
  235. } else {
  236. hl = c.f.hostMap
  237. }
  238. h := hl.QueryVpnAddr(vpnAddr)
  239. if h == nil {
  240. return nil
  241. }
  242. ch := copyHostInfo(h, c.f.hostMap.GetPreferredRanges())
  243. return &ch
  244. }
  245. // SetRemoteForTunnel forces a tunnel to use a specific remote
  246. // Caller should take care to Unmap() any 4in6 addresses prior to calling.
  247. func (c *Control) SetRemoteForTunnel(vpnIp netip.Addr, addr netip.AddrPort) *ControlHostInfo {
  248. hostInfo := c.f.hostMap.QueryVpnAddr(vpnIp)
  249. if hostInfo == nil {
  250. return nil
  251. }
  252. hostInfo.SetRemote(addr)
  253. ch := copyHostInfo(hostInfo, c.f.hostMap.GetPreferredRanges())
  254. return &ch
  255. }
  256. // CloseTunnel closes a fully established tunnel. If localOnly is false it will notify the remote end as well.
  257. // Caller should take care to Unmap() any 4in6 addresses prior to calling.
  258. func (c *Control) CloseTunnel(vpnIp netip.Addr, localOnly bool) bool {
  259. hostInfo := c.f.hostMap.QueryVpnAddr(vpnIp)
  260. if hostInfo == nil {
  261. return false
  262. }
  263. if !localOnly {
  264. c.f.send(
  265. header.CloseTunnel,
  266. 0,
  267. hostInfo.ConnectionState,
  268. hostInfo,
  269. []byte{},
  270. make([]byte, 12, 12),
  271. make([]byte, mtu),
  272. )
  273. }
  274. c.f.closeTunnel(hostInfo)
  275. return true
  276. }
  277. // CloseAllTunnels is just like CloseTunnel except it goes through and shuts them all down, optionally you can avoid shutting down lighthouse tunnels
  278. // the int returned is a count of tunnels closed
  279. func (c *Control) CloseAllTunnels(excludeLighthouses bool) (closed int) {
  280. shutdown := func(h *HostInfo) {
  281. if excludeLighthouses && c.f.lightHouse.IsAnyLighthouseAddr(h.vpnAddrs) {
  282. return
  283. }
  284. c.f.send(header.CloseTunnel, 0, h.ConnectionState, h, []byte{}, make([]byte, 12, 12), make([]byte, mtu))
  285. c.f.closeTunnel(h)
  286. c.l.Debug("Sending close tunnel message",
  287. "vpnAddrs", h.vpnAddrs,
  288. "udpAddr", h.GetRemote(),
  289. )
  290. closed++
  291. }
  292. // Learn which hosts are being used as relays, so we can shut them down last.
  293. relayingHosts := map[netip.Addr]*HostInfo{}
  294. // Grab the hostMap lock to access the Relays map
  295. c.f.hostMap.Lock()
  296. for _, relayingHost := range c.f.hostMap.Relays {
  297. relayingHosts[relayingHost.vpnAddrs[0]] = relayingHost
  298. }
  299. c.f.hostMap.Unlock()
  300. hostInfos := []*HostInfo{}
  301. // Grab the hostMap lock to access the Hosts map
  302. c.f.hostMap.Lock()
  303. for _, relayHost := range c.f.hostMap.Indexes {
  304. if _, ok := relayingHosts[relayHost.vpnAddrs[0]]; !ok {
  305. hostInfos = append(hostInfos, relayHost)
  306. }
  307. }
  308. c.f.hostMap.Unlock()
  309. for _, h := range hostInfos {
  310. shutdown(h)
  311. }
  312. for _, h := range relayingHosts {
  313. shutdown(h)
  314. }
  315. return
  316. }
  317. func (c *Control) Device() overlay.Device {
  318. return c.f.inside
  319. }
  320. func copyHostInfo(h *HostInfo, preferredRanges []netip.Prefix) ControlHostInfo {
  321. chi := ControlHostInfo{
  322. VpnAddrs: make([]netip.Addr, len(h.vpnAddrs)),
  323. LocalIndex: h.localIndexId,
  324. RemoteIndex: h.remoteIndexId,
  325. RemoteAddrs: h.remotes.CopyAddrs(preferredRanges),
  326. CurrentRelaysToMe: h.relayState.CopyRelayIps(),
  327. CurrentRelaysThroughMe: h.relayState.CopyRelayForIps(),
  328. CurrentRemote: h.GetRemote(),
  329. }
  330. for i, a := range h.vpnAddrs {
  331. chi.VpnAddrs[i] = a
  332. }
  333. if h.ConnectionState != nil {
  334. chi.MessageCounter = h.ConnectionState.messageCounter.Load()
  335. }
  336. if c := h.GetCert(); c != nil {
  337. chi.Cert = c.Certificate.Copy()
  338. }
  339. return chi
  340. }
  341. func listHostMapHosts(hl controlHostLister) []ControlHostInfo {
  342. hosts := make([]ControlHostInfo, 0)
  343. pr := hl.GetPreferredRanges()
  344. hl.ForEachVpnAddr(func(hostinfo *HostInfo) {
  345. hosts = append(hosts, copyHostInfo(hostinfo, pr))
  346. })
  347. return hosts
  348. }
  349. func listHostMapIndexes(hl controlHostLister) []ControlHostInfo {
  350. hosts := make([]ControlHostInfo, 0)
  351. pr := hl.GetPreferredRanges()
  352. hl.ForEachIndex(func(hostinfo *HostInfo) {
  353. hosts = append(hosts, copyHostInfo(hostinfo, pr))
  354. })
  355. return hosts
  356. }