control.go 12 KB

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