control.go 9.8 KB

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