control.go 12 KB

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