control.go 12 KB

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