control.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. package nebula
  2. import (
  3. "context"
  4. "errors"
  5. "net/netip"
  6. "os"
  7. "os/signal"
  8. "sync"
  9. "syscall"
  10. "github.com/sirupsen/logrus"
  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. Stopped RunState = 0 // The control has yet to be started
  18. Started RunState = 1 // The control has been started
  19. Stopping RunState = 2 // The control is stopping
  20. )
  21. var ErrAlreadyStarted = errors.New("nebula is already started")
  22. // Every interaction here needs to take extra care to copy memory and not return or use arguments "as is" when touching
  23. // core. This means copying IP objects, slices, de-referencing pointers and taking the actual value, etc
  24. type controlEach func(h *HostInfo)
  25. type controlHostLister interface {
  26. QueryVpnAddr(vpnAddr netip.Addr) *HostInfo
  27. ForEachIndex(each controlEach)
  28. ForEachVpnAddr(each controlEach)
  29. GetPreferredRanges() []netip.Prefix
  30. }
  31. type Control struct {
  32. stateLock sync.Mutex
  33. state RunState
  34. f *Interface
  35. l *logrus.Logger
  36. ctx context.Context
  37. cancel context.CancelFunc
  38. sshStart func()
  39. statsStart func()
  40. dnsStart func()
  41. lighthouseStart func()
  42. connectionManagerStart func(context.Context)
  43. }
  44. type ControlHostInfo struct {
  45. VpnAddrs []netip.Addr `json:"vpnAddrs"`
  46. LocalIndex uint32 `json:"localIndex"`
  47. RemoteIndex uint32 `json:"remoteIndex"`
  48. RemoteAddrs []netip.AddrPort `json:"remoteAddrs"`
  49. Cert cert.Certificate `json:"cert"`
  50. MessageCounter uint64 `json:"messageCounter"`
  51. CurrentRemote netip.AddrPort `json:"currentRemote"`
  52. CurrentRelaysToMe []netip.Addr `json:"currentRelaysToMe"`
  53. CurrentRelaysThroughMe []netip.Addr `json:"currentRelaysThroughMe"`
  54. }
  55. // Start actually runs nebula, this is a nonblocking call.
  56. // The returned function can be used to wait for nebula to fully stop.
  57. func (c *Control) Start() (func(), error) {
  58. c.stateLock.Lock()
  59. if c.state != Stopped {
  60. c.stateLock.Unlock()
  61. return nil, ErrAlreadyStarted
  62. }
  63. // Activate the interface
  64. err := c.f.activate()
  65. if err != nil {
  66. c.stateLock.Unlock()
  67. return nil, err
  68. }
  69. // Call all the delayed funcs that waited patiently for the interface to be created.
  70. if c.sshStart != nil {
  71. go c.sshStart()
  72. }
  73. if c.statsStart != nil {
  74. go c.statsStart()
  75. }
  76. if c.dnsStart != nil {
  77. go c.dnsStart()
  78. }
  79. if c.connectionManagerStart != nil {
  80. go c.connectionManagerStart(c.ctx)
  81. }
  82. if c.lighthouseStart != nil {
  83. c.lighthouseStart()
  84. }
  85. // Start reading packets.
  86. c.state = Started
  87. c.stateLock.Unlock()
  88. return c.f.run(c.ctx)
  89. }
  90. func (c *Control) State() RunState {
  91. c.stateLock.Lock()
  92. defer c.stateLock.Unlock()
  93. return c.state
  94. }
  95. func (c *Control) Context() context.Context {
  96. return c.ctx
  97. }
  98. // Stop is a non-blocking call that signals nebula to close all tunnels and shut down
  99. func (c *Control) Stop() {
  100. c.stateLock.Lock()
  101. if c.state != Started {
  102. c.stateLock.Unlock()
  103. // We are stopping or stopped already
  104. return
  105. }
  106. c.state = Stopping
  107. c.stateLock.Unlock()
  108. // Stop the handshakeManager (and other services), to prevent new tunnels from
  109. // being created while we're shutting them all down.
  110. c.cancel()
  111. c.CloseAllTunnels(false)
  112. if err := c.f.Close(); err != nil {
  113. c.l.WithError(err).Error("Close interface failed")
  114. }
  115. c.state = Stopped
  116. }
  117. // ShutdownBlock will listen for and block on term and interrupt signals, calling Control.Stop() once signalled
  118. func (c *Control) ShutdownBlock() {
  119. sigChan := make(chan os.Signal, 1)
  120. signal.Notify(sigChan, syscall.SIGTERM)
  121. signal.Notify(sigChan, syscall.SIGINT)
  122. rawSig := <-sigChan
  123. sig := rawSig.String()
  124. c.l.WithField("signal", sig).Info("Caught signal, shutting down")
  125. c.Stop()
  126. }
  127. // RebindUDPServer asks the UDP listener to rebind it's listener. Mainly used on mobile clients when interfaces change
  128. func (c *Control) RebindUDPServer() {
  129. _ = c.f.outside.Rebind()
  130. // Trigger a lighthouse update, useful for mobile clients that should have an update interval of 0
  131. c.f.lightHouse.SendUpdate()
  132. // Let the main interface know that we rebound so that underlying tunnels know to trigger punches from their remotes
  133. c.f.rebindCount++
  134. }
  135. // ListHostmapHosts returns details about the actual or pending (handshaking) hostmap by vpn ip
  136. func (c *Control) ListHostmapHosts(pendingMap bool) []ControlHostInfo {
  137. if pendingMap {
  138. return listHostMapHosts(c.f.handshakeManager)
  139. } else {
  140. return listHostMapHosts(c.f.hostMap)
  141. }
  142. }
  143. // ListHostmapIndexes returns details about the actual or pending (handshaking) hostmap by local index id
  144. func (c *Control) ListHostmapIndexes(pendingMap bool) []ControlHostInfo {
  145. if pendingMap {
  146. return listHostMapIndexes(c.f.handshakeManager)
  147. } else {
  148. return listHostMapIndexes(c.f.hostMap)
  149. }
  150. }
  151. // GetCertByVpnIp returns the authenticated certificate of the given vpn IP, or nil if not found
  152. func (c *Control) GetCertByVpnIp(vpnIp netip.Addr) cert.Certificate {
  153. if c.f.myVpnAddrsTable.Contains(vpnIp) {
  154. // Only returning the default certificate since its impossible
  155. // for any other host but ourselves to have more than 1
  156. return c.f.pki.getCertState().GetDefaultCertificate().Copy()
  157. }
  158. hi := c.f.hostMap.QueryVpnAddr(vpnIp)
  159. if hi == nil {
  160. return nil
  161. }
  162. return hi.GetCert().Certificate.Copy()
  163. }
  164. // CreateTunnel creates a new tunnel to the given vpn ip.
  165. func (c *Control) CreateTunnel(vpnIp netip.Addr) {
  166. c.f.handshakeManager.StartHandshake(vpnIp, nil)
  167. }
  168. // PrintTunnel creates a new tunnel to the given vpn ip.
  169. func (c *Control) PrintTunnel(vpnIp netip.Addr) *ControlHostInfo {
  170. hi := c.f.hostMap.QueryVpnAddr(vpnIp)
  171. if hi == nil {
  172. return nil
  173. }
  174. chi := copyHostInfo(hi, c.f.hostMap.GetPreferredRanges())
  175. return &chi
  176. }
  177. // QueryLighthouse queries the lighthouse.
  178. func (c *Control) QueryLighthouse(vpnIp netip.Addr) *CacheMap {
  179. hi := c.f.lightHouse.Query(vpnIp)
  180. if hi == nil {
  181. return nil
  182. }
  183. return hi.CopyCache()
  184. }
  185. // GetHostInfoByVpnAddr returns a single tunnels hostInfo, or nil if not found
  186. // Caller should take care to Unmap() any 4in6 addresses prior to calling.
  187. func (c *Control) GetHostInfoByVpnAddr(vpnAddr netip.Addr, pending bool) *ControlHostInfo {
  188. var hl controlHostLister
  189. if pending {
  190. hl = c.f.handshakeManager
  191. } else {
  192. hl = c.f.hostMap
  193. }
  194. h := hl.QueryVpnAddr(vpnAddr)
  195. if h == nil {
  196. return nil
  197. }
  198. ch := copyHostInfo(h, c.f.hostMap.GetPreferredRanges())
  199. return &ch
  200. }
  201. // SetRemoteForTunnel forces a tunnel to use a specific remote
  202. // Caller should take care to Unmap() any 4in6 addresses prior to calling.
  203. func (c *Control) SetRemoteForTunnel(vpnIp netip.Addr, addr netip.AddrPort) *ControlHostInfo {
  204. hostInfo := c.f.hostMap.QueryVpnAddr(vpnIp)
  205. if hostInfo == nil {
  206. return nil
  207. }
  208. hostInfo.SetRemote(addr)
  209. ch := copyHostInfo(hostInfo, c.f.hostMap.GetPreferredRanges())
  210. return &ch
  211. }
  212. // CloseTunnel closes a fully established tunnel. If localOnly is false it will notify the remote end as well.
  213. // Caller should take care to Unmap() any 4in6 addresses prior to calling.
  214. func (c *Control) CloseTunnel(vpnIp netip.Addr, localOnly bool) bool {
  215. hostInfo := c.f.hostMap.QueryVpnAddr(vpnIp)
  216. if hostInfo == nil {
  217. return false
  218. }
  219. if !localOnly {
  220. c.f.send(
  221. header.CloseTunnel,
  222. 0,
  223. hostInfo.ConnectionState,
  224. hostInfo,
  225. []byte{},
  226. make([]byte, 12, 12),
  227. make([]byte, mtu),
  228. )
  229. }
  230. c.f.closeTunnel(hostInfo)
  231. return true
  232. }
  233. // CloseAllTunnels is just like CloseTunnel except it goes through and shuts them all down, optionally you can avoid shutting down lighthouse tunnels
  234. // the int returned is a count of tunnels closed
  235. func (c *Control) CloseAllTunnels(excludeLighthouses bool) (closed int) {
  236. shutdown := func(h *HostInfo) {
  237. if excludeLighthouses && c.f.lightHouse.IsAnyLighthouseAddr(h.vpnAddrs) {
  238. return
  239. }
  240. c.f.send(header.CloseTunnel, 0, h.ConnectionState, h, []byte{}, make([]byte, 12, 12), make([]byte, mtu))
  241. c.f.closeTunnel(h)
  242. c.l.WithField("vpnAddrs", h.vpnAddrs).WithField("udpAddr", h.remote).
  243. Debug("Sending close tunnel message")
  244. closed++
  245. }
  246. // Learn which hosts are being used as relays, so we can shut them down last.
  247. relayingHosts := map[netip.Addr]*HostInfo{}
  248. // Grab the hostMap lock to access the Relays map
  249. c.f.hostMap.Lock()
  250. for _, relayingHost := range c.f.hostMap.Relays {
  251. relayingHosts[relayingHost.vpnAddrs[0]] = relayingHost
  252. }
  253. c.f.hostMap.Unlock()
  254. hostInfos := []*HostInfo{}
  255. // Grab the hostMap lock to access the Hosts map
  256. c.f.hostMap.Lock()
  257. for _, relayHost := range c.f.hostMap.Indexes {
  258. if _, ok := relayingHosts[relayHost.vpnAddrs[0]]; !ok {
  259. hostInfos = append(hostInfos, relayHost)
  260. }
  261. }
  262. c.f.hostMap.Unlock()
  263. for _, h := range hostInfos {
  264. shutdown(h)
  265. }
  266. for _, h := range relayingHosts {
  267. shutdown(h)
  268. }
  269. return
  270. }
  271. func (c *Control) Device() overlay.Device {
  272. return c.f.inside
  273. }
  274. func copyHostInfo(h *HostInfo, preferredRanges []netip.Prefix) ControlHostInfo {
  275. chi := ControlHostInfo{
  276. VpnAddrs: make([]netip.Addr, len(h.vpnAddrs)),
  277. LocalIndex: h.localIndexId,
  278. RemoteIndex: h.remoteIndexId,
  279. RemoteAddrs: h.remotes.CopyAddrs(preferredRanges),
  280. CurrentRelaysToMe: h.relayState.CopyRelayIps(),
  281. CurrentRelaysThroughMe: h.relayState.CopyRelayForIps(),
  282. CurrentRemote: h.remote,
  283. }
  284. for i, a := range h.vpnAddrs {
  285. chi.VpnAddrs[i] = a
  286. }
  287. if h.ConnectionState != nil {
  288. chi.MessageCounter = h.ConnectionState.messageCounter.Load()
  289. }
  290. if c := h.GetCert(); c != nil {
  291. chi.Cert = c.Certificate.Copy()
  292. }
  293. return chi
  294. }
  295. func listHostMapHosts(hl controlHostLister) []ControlHostInfo {
  296. hosts := make([]ControlHostInfo, 0)
  297. pr := hl.GetPreferredRanges()
  298. hl.ForEachVpnAddr(func(hostinfo *HostInfo) {
  299. hosts = append(hosts, copyHostInfo(hostinfo, pr))
  300. })
  301. return hosts
  302. }
  303. func listHostMapIndexes(hl controlHostLister) []ControlHostInfo {
  304. hosts := make([]ControlHostInfo, 0)
  305. pr := hl.GetPreferredRanges()
  306. hl.ForEachIndex(func(hostinfo *HostInfo) {
  307. hosts = append(hosts, copyHostInfo(hostinfo, pr))
  308. })
  309. return hosts
  310. }