control.go 9.0 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. QueryVpnIp(vpnIp netip.Addr) *HostInfo
  18. ForEachIndex(each controlEach)
  19. ForEachVpnIp(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. VpnIp netip.Addr `json:"vpnIp"`
  35. LocalIndex uint32 `json:"localIndex"`
  36. RemoteIndex uint32 `json:"remoteIndex"`
  37. RemoteAddrs []netip.AddrPort `json:"remoteAddrs"`
  38. Cert *cert.NebulaCertificate `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.NebulaCertificate {
  117. if c.f.myVpnNet.Addr() == vpnIp {
  118. return c.f.pki.GetCertState().Certificate
  119. }
  120. hi := c.f.hostMap.QueryVpnIp(vpnIp)
  121. if hi == nil {
  122. return nil
  123. }
  124. return hi.GetCert()
  125. }
  126. // CreateTunnel creates a new tunnel to the given vpn ip.
  127. func (c *Control) CreateTunnel(vpnIp netip.Addr) {
  128. c.f.handshakeManager.StartHandshake(vpnIp, nil)
  129. }
  130. // PrintTunnel creates a new tunnel to the given vpn ip.
  131. func (c *Control) PrintTunnel(vpnIp netip.Addr) *ControlHostInfo {
  132. hi := c.f.hostMap.QueryVpnIp(vpnIp)
  133. if hi == nil {
  134. return nil
  135. }
  136. chi := copyHostInfo(hi, c.f.hostMap.GetPreferredRanges())
  137. return &chi
  138. }
  139. // QueryLighthouse queries the lighthouse.
  140. func (c *Control) QueryLighthouse(vpnIp netip.Addr) *CacheMap {
  141. hi := c.f.lightHouse.Query(vpnIp)
  142. if hi == nil {
  143. return nil
  144. }
  145. return hi.CopyCache()
  146. }
  147. // GetHostInfoByVpnIp returns a single tunnels hostInfo, or nil if not found
  148. // Caller should take care to Unmap() any 4in6 addresses prior to calling.
  149. func (c *Control) GetHostInfoByVpnIp(vpnIp netip.Addr, pending bool) *ControlHostInfo {
  150. var hl controlHostLister
  151. if pending {
  152. hl = c.f.handshakeManager
  153. } else {
  154. hl = c.f.hostMap
  155. }
  156. h := hl.QueryVpnIp(vpnIp)
  157. if h == nil {
  158. return nil
  159. }
  160. ch := copyHostInfo(h, c.f.hostMap.GetPreferredRanges())
  161. return &ch
  162. }
  163. // SetRemoteForTunnel forces a tunnel to use a specific remote
  164. // Caller should take care to Unmap() any 4in6 addresses prior to calling.
  165. func (c *Control) SetRemoteForTunnel(vpnIp netip.Addr, addr netip.AddrPort) *ControlHostInfo {
  166. hostInfo := c.f.hostMap.QueryVpnIp(vpnIp)
  167. if hostInfo == nil {
  168. return nil
  169. }
  170. hostInfo.SetRemote(addr)
  171. ch := copyHostInfo(hostInfo, c.f.hostMap.GetPreferredRanges())
  172. return &ch
  173. }
  174. // CloseTunnel closes a fully established tunnel. If localOnly is false it will notify the remote end as well.
  175. // Caller should take care to Unmap() any 4in6 addresses prior to calling.
  176. func (c *Control) CloseTunnel(vpnIp netip.Addr, localOnly bool) bool {
  177. hostInfo := c.f.hostMap.QueryVpnIp(vpnIp)
  178. if hostInfo == nil {
  179. return false
  180. }
  181. if !localOnly {
  182. c.f.send(
  183. header.CloseTunnel,
  184. 0,
  185. hostInfo.ConnectionState,
  186. hostInfo,
  187. []byte{},
  188. make([]byte, 12, 12),
  189. make([]byte, mtu),
  190. )
  191. }
  192. c.f.closeTunnel(hostInfo)
  193. return true
  194. }
  195. // CloseAllTunnels is just like CloseTunnel except it goes through and shuts them all down, optionally you can avoid shutting down lighthouse tunnels
  196. // the int returned is a count of tunnels closed
  197. func (c *Control) CloseAllTunnels(excludeLighthouses bool) (closed int) {
  198. //TODO: this is probably better as a function in ConnectionManager or HostMap directly
  199. lighthouses := c.f.lightHouse.GetLighthouses()
  200. shutdown := func(h *HostInfo) {
  201. if excludeLighthouses {
  202. if _, ok := lighthouses[h.vpnIp]; ok {
  203. return
  204. }
  205. }
  206. c.f.send(header.CloseTunnel, 0, h.ConnectionState, h, []byte{}, make([]byte, 12, 12), make([]byte, mtu))
  207. c.f.closeTunnel(h)
  208. c.l.WithField("vpnIp", h.vpnIp).WithField("udpAddr", h.remote).
  209. Debug("Sending close tunnel message")
  210. closed++
  211. }
  212. // Learn which hosts are being used as relays, so we can shut them down last.
  213. relayingHosts := map[netip.Addr]*HostInfo{}
  214. // Grab the hostMap lock to access the Relays map
  215. c.f.hostMap.Lock()
  216. for _, relayingHost := range c.f.hostMap.Relays {
  217. relayingHosts[relayingHost.vpnIp] = relayingHost
  218. }
  219. c.f.hostMap.Unlock()
  220. hostInfos := []*HostInfo{}
  221. // Grab the hostMap lock to access the Hosts map
  222. c.f.hostMap.Lock()
  223. for _, relayHost := range c.f.hostMap.Indexes {
  224. if _, ok := relayingHosts[relayHost.vpnIp]; !ok {
  225. hostInfos = append(hostInfos, relayHost)
  226. }
  227. }
  228. c.f.hostMap.Unlock()
  229. for _, h := range hostInfos {
  230. shutdown(h)
  231. }
  232. for _, h := range relayingHosts {
  233. shutdown(h)
  234. }
  235. return
  236. }
  237. func (c *Control) Device() overlay.Device {
  238. return c.f.inside
  239. }
  240. func copyHostInfo(h *HostInfo, preferredRanges []netip.Prefix) ControlHostInfo {
  241. chi := ControlHostInfo{
  242. VpnIp: h.vpnIp,
  243. LocalIndex: h.localIndexId,
  244. RemoteIndex: h.remoteIndexId,
  245. RemoteAddrs: h.remotes.CopyAddrs(preferredRanges),
  246. CurrentRelaysToMe: h.relayState.CopyRelayIps(),
  247. CurrentRelaysThroughMe: h.relayState.CopyRelayForIps(),
  248. CurrentRemote: h.remote,
  249. }
  250. if h.ConnectionState != nil {
  251. chi.MessageCounter = h.ConnectionState.messageCounter.Load()
  252. }
  253. if c := h.GetCert(); c != nil {
  254. chi.Cert = c.Copy()
  255. }
  256. return chi
  257. }
  258. func listHostMapHosts(hl controlHostLister) []ControlHostInfo {
  259. hosts := make([]ControlHostInfo, 0)
  260. pr := hl.GetPreferredRanges()
  261. hl.ForEachVpnIp(func(hostinfo *HostInfo) {
  262. hosts = append(hosts, copyHostInfo(hostinfo, pr))
  263. })
  264. return hosts
  265. }
  266. func listHostMapIndexes(hl controlHostLister) []ControlHostInfo {
  267. hosts := make([]ControlHostInfo, 0)
  268. pr := hl.GetPreferredRanges()
  269. hl.ForEachIndex(func(hostinfo *HostInfo) {
  270. hosts = append(hosts, copyHostInfo(hostinfo, pr))
  271. })
  272. return hosts
  273. }