control.go 13 KB

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