control.go 10 KB

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