control.go 9.1 KB

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