control.go 11 KB

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