control.go 11 KB

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