2
0

control.go 9.0 KB

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