control.go 12 KB

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