control.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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/firewall/events"
  13. "github.com/slackhq/nebula/header"
  14. "github.com/slackhq/nebula/overlay"
  15. )
  16. type RunState int
  17. const (
  18. StateUnknown RunState = iota
  19. StateReady
  20. StateStarted
  21. StateStopping
  22. StateStopped
  23. )
  24. var ErrAlreadyStarted = errors.New("nebula is already started")
  25. var ErrAlreadyStopped = errors.New("nebula cannot be restarted")
  26. var ErrUnknownState = errors.New("nebula state is invalid")
  27. // Every interaction here needs to take extra care to copy memory and not return or use arguments "as is" when touching
  28. // core. This means copying IP objects, slices, de-referencing pointers and taking the actual value, etc
  29. type controlEach func(h *HostInfo)
  30. type controlHostLister interface {
  31. QueryVpnAddr(vpnAddr netip.Addr) *HostInfo
  32. ForEachIndex(each controlEach)
  33. ForEachVpnAddr(each controlEach)
  34. GetPreferredRanges() []netip.Prefix
  35. }
  36. type Control struct {
  37. stateLock sync.Mutex
  38. state RunState
  39. f *Interface
  40. l *logrus.Logger
  41. ctx context.Context
  42. cancel context.CancelFunc
  43. sshStart func()
  44. statsStart func()
  45. dnsStart func()
  46. lighthouseStart func()
  47. connectionManagerStart func(context.Context)
  48. }
  49. type ControlHostInfo struct {
  50. VpnAddrs []netip.Addr `json:"vpnAddrs"`
  51. LocalIndex uint32 `json:"localIndex"`
  52. RemoteIndex uint32 `json:"remoteIndex"`
  53. RemoteAddrs []netip.AddrPort `json:"remoteAddrs"`
  54. Cert cert.Certificate `json:"cert"`
  55. MessageCounter uint64 `json:"messageCounter"`
  56. CurrentRemote netip.AddrPort `json:"currentRemote"`
  57. CurrentRelaysToMe []netip.Addr `json:"currentRelaysToMe"`
  58. CurrentRelaysThroughMe []netip.Addr `json:"currentRelaysThroughMe"`
  59. }
  60. // Start actually runs nebula, this is a nonblocking call.
  61. // The returned function blocks until nebula has fully stopped and returns the
  62. // first fatal reader error (if any). A nil error means nebula shut down
  63. // gracefully; a non-nil error means a reader hit an unexpected failure that
  64. // triggered the shutdown.
  65. func (c *Control) Start() (func() error, error) {
  66. c.stateLock.Lock()
  67. defer c.stateLock.Unlock()
  68. switch c.state {
  69. case StateReady:
  70. //yay!
  71. case StateStopped, StateStopping:
  72. return nil, ErrAlreadyStopped
  73. case StateStarted:
  74. return nil, ErrAlreadyStarted
  75. default:
  76. return nil, ErrUnknownState
  77. }
  78. // Activate the interface
  79. err := c.f.activate()
  80. if err != nil {
  81. c.state = StateStopped
  82. return nil, err
  83. }
  84. // Call all the delayed funcs that waited patiently for the interface to be created.
  85. if c.sshStart != nil {
  86. go c.sshStart()
  87. }
  88. if c.statsStart != nil {
  89. go c.statsStart()
  90. }
  91. if c.dnsStart != nil {
  92. go c.dnsStart()
  93. }
  94. if c.connectionManagerStart != nil {
  95. go c.connectionManagerStart(c.ctx)
  96. }
  97. if c.lighthouseStart != nil {
  98. c.lighthouseStart()
  99. }
  100. c.f.triggerShutdown = c.Stop
  101. // Start reading packets.
  102. out, err := c.f.run()
  103. if err != nil {
  104. c.state = StateStopped
  105. return nil, err
  106. }
  107. c.state = StateStarted
  108. return out, nil
  109. }
  110. func (c *Control) State() RunState {
  111. c.stateLock.Lock()
  112. defer c.stateLock.Unlock()
  113. return c.state
  114. }
  115. func (c *Control) Context() context.Context {
  116. return c.ctx
  117. }
  118. // Stop is a non-blocking call that signals nebula to close all tunnels and shut down
  119. func (c *Control) Stop() {
  120. c.stateLock.Lock()
  121. if c.state != StateStarted {
  122. c.stateLock.Unlock()
  123. // We are stopping or stopped already
  124. return
  125. }
  126. c.state = StateStopping
  127. c.stateLock.Unlock()
  128. // Stop the handshakeManager (and other services), to prevent new tunnels from
  129. // being created while we're shutting them all down.
  130. c.cancel()
  131. c.CloseAllTunnels(false)
  132. if err := c.f.Close(); err != nil {
  133. c.l.WithError(err).Error("Close interface failed")
  134. }
  135. c.stateLock.Lock()
  136. c.state = StateStopped
  137. c.stateLock.Unlock()
  138. }
  139. // ShutdownBlock will listen for and block on term and interrupt signals, calling Control.Stop() once signalled
  140. func (c *Control) ShutdownBlock() {
  141. sigChan := make(chan os.Signal, 1)
  142. signal.Notify(sigChan, syscall.SIGTERM)
  143. signal.Notify(sigChan, syscall.SIGINT)
  144. rawSig := <-sigChan
  145. sig := rawSig.String()
  146. c.l.WithField("signal", sig).Info("Caught signal, shutting down")
  147. c.Stop()
  148. }
  149. // RebindUDPServer asks the UDP listener to rebind it's listener. Mainly used on mobile clients when interfaces change
  150. func (c *Control) RebindUDPServer() {
  151. _ = c.f.outside.Rebind()
  152. // Trigger a lighthouse update, useful for mobile clients that should have an update interval of 0
  153. c.f.lightHouse.SendUpdate()
  154. // Let the main interface know that we rebound so that underlying tunnels know to trigger punches from their remotes
  155. c.f.rebindCount++
  156. }
  157. // ListHostmapHosts returns details about the actual or pending (handshaking) hostmap by vpn ip
  158. func (c *Control) ListHostmapHosts(pendingMap bool) []ControlHostInfo {
  159. if pendingMap {
  160. return listHostMapHosts(c.f.handshakeManager)
  161. } else {
  162. return listHostMapHosts(c.f.hostMap)
  163. }
  164. }
  165. // ListHostmapIndexes returns details about the actual or pending (handshaking) hostmap by local index id
  166. func (c *Control) ListHostmapIndexes(pendingMap bool) []ControlHostInfo {
  167. if pendingMap {
  168. return listHostMapIndexes(c.f.handshakeManager)
  169. } else {
  170. return listHostMapIndexes(c.f.hostMap)
  171. }
  172. }
  173. // GetCertByVpnIp returns the authenticated certificate of the given vpn IP, or nil if not found
  174. func (c *Control) GetCertByVpnIp(vpnIp netip.Addr) cert.Certificate {
  175. if c.f.myVpnAddrsTable.Contains(vpnIp) {
  176. // Only returning the default certificate since its impossible
  177. // for any other host but ourselves to have more than 1
  178. return c.f.pki.getCertState().GetDefaultCertificate().Copy()
  179. }
  180. hi := c.f.hostMap.QueryVpnAddr(vpnIp)
  181. if hi == nil {
  182. return nil
  183. }
  184. return hi.GetCert().Certificate.Copy()
  185. }
  186. // CreateTunnel creates a new tunnel to the given vpn ip.
  187. func (c *Control) CreateTunnel(vpnIp netip.Addr) {
  188. c.f.handshakeManager.StartHandshake(vpnIp, nil)
  189. }
  190. // PrintTunnel creates a new tunnel to the given vpn ip.
  191. func (c *Control) PrintTunnel(vpnIp netip.Addr) *ControlHostInfo {
  192. hi := c.f.hostMap.QueryVpnAddr(vpnIp)
  193. if hi == nil {
  194. return nil
  195. }
  196. chi := copyHostInfo(hi, c.f.hostMap.GetPreferredRanges())
  197. return &chi
  198. }
  199. // QueryLighthouse queries the lighthouse.
  200. func (c *Control) QueryLighthouse(vpnIp netip.Addr) *CacheMap {
  201. hi := c.f.lightHouse.Query(vpnIp)
  202. if hi == nil {
  203. return nil
  204. }
  205. return hi.CopyCache()
  206. }
  207. // GetHostInfoByVpnAddr returns a single tunnels hostInfo, or nil if not found
  208. // Caller should take care to Unmap() any 4in6 addresses prior to calling.
  209. func (c *Control) GetHostInfoByVpnAddr(vpnAddr netip.Addr, pending bool) *ControlHostInfo {
  210. var hl controlHostLister
  211. if pending {
  212. hl = c.f.handshakeManager
  213. } else {
  214. hl = c.f.hostMap
  215. }
  216. h := hl.QueryVpnAddr(vpnAddr)
  217. if h == nil {
  218. return nil
  219. }
  220. ch := copyHostInfo(h, c.f.hostMap.GetPreferredRanges())
  221. return &ch
  222. }
  223. // SetRemoteForTunnel forces a tunnel to use a specific remote
  224. // Caller should take care to Unmap() any 4in6 addresses prior to calling.
  225. func (c *Control) SetRemoteForTunnel(vpnIp netip.Addr, addr netip.AddrPort) *ControlHostInfo {
  226. hostInfo := c.f.hostMap.QueryVpnAddr(vpnIp)
  227. if hostInfo == nil {
  228. return nil
  229. }
  230. hostInfo.SetRemote(addr)
  231. ch := copyHostInfo(hostInfo, c.f.hostMap.GetPreferredRanges())
  232. return &ch
  233. }
  234. // CloseTunnel closes a fully established tunnel. If localOnly is false it will notify the remote end as well.
  235. // Caller should take care to Unmap() any 4in6 addresses prior to calling.
  236. func (c *Control) CloseTunnel(vpnIp netip.Addr, localOnly bool) bool {
  237. hostInfo := c.f.hostMap.QueryVpnAddr(vpnIp)
  238. if hostInfo == nil {
  239. return false
  240. }
  241. if !localOnly {
  242. c.f.send(
  243. header.CloseTunnel,
  244. 0,
  245. hostInfo.ConnectionState,
  246. hostInfo,
  247. []byte{},
  248. make([]byte, 12, 12),
  249. make([]byte, mtu),
  250. )
  251. }
  252. c.f.closeTunnel(hostInfo)
  253. return true
  254. }
  255. // CloseAllTunnels is just like CloseTunnel except it goes through and shuts them all down, optionally you can avoid shutting down lighthouse tunnels
  256. // the int returned is a count of tunnels closed
  257. func (c *Control) CloseAllTunnels(excludeLighthouses bool) (closed int) {
  258. shutdown := func(h *HostInfo) {
  259. if excludeLighthouses && c.f.lightHouse.IsAnyLighthouseAddr(h.vpnAddrs) {
  260. return
  261. }
  262. c.f.send(header.CloseTunnel, 0, h.ConnectionState, h, []byte{}, make([]byte, 12, 12), make([]byte, mtu))
  263. c.f.closeTunnel(h)
  264. c.l.WithField("vpnAddrs", h.vpnAddrs).WithField("udpAddr", h.remote).
  265. Debug("Sending close tunnel message")
  266. closed++
  267. }
  268. // Learn which hosts are being used as relays, so we can shut them down last.
  269. relayingHosts := map[netip.Addr]*HostInfo{}
  270. // Grab the hostMap lock to access the Relays map
  271. c.f.hostMap.Lock()
  272. for _, relayingHost := range c.f.hostMap.Relays {
  273. relayingHosts[relayingHost.vpnAddrs[0]] = relayingHost
  274. }
  275. c.f.hostMap.Unlock()
  276. hostInfos := []*HostInfo{}
  277. // Grab the hostMap lock to access the Hosts map
  278. c.f.hostMap.Lock()
  279. for _, relayHost := range c.f.hostMap.Indexes {
  280. if _, ok := relayingHosts[relayHost.vpnAddrs[0]]; !ok {
  281. hostInfos = append(hostInfos, relayHost)
  282. }
  283. }
  284. c.f.hostMap.Unlock()
  285. for _, h := range hostInfos {
  286. shutdown(h)
  287. }
  288. for _, h := range relayingHosts {
  289. shutdown(h)
  290. }
  291. return
  292. }
  293. func (c *Control) Device() overlay.Device {
  294. return c.f.inside
  295. }
  296. // SetFirewallEventReporter installs an event reporter on the current firewall.
  297. // Passing nil clears any installed reporter. The reporter is carried across
  298. // firewall rule reloads. Report* methods are invoked while nebula holds
  299. // internal locks and must be non-blocking; in particular they must not call
  300. // back into *Control methods that touch the firewall, or deadlock will
  301. // result.
  302. //
  303. // Installation is performed by shallow-copying the current *Firewall,
  304. // setting the reporter field on the copy, and swapping the pointer under
  305. // the conntrack lock. Every Firewall the data path sees therefore has an
  306. // immutable reporter slot, and emit sites can read it without any
  307. // synchronization of their own.
  308. func (c *Control) SetFirewallEventReporter(r events.Reporter) {
  309. old := c.f.firewall
  310. if old == nil {
  311. return
  312. }
  313. old.Conntrack.Lock()
  314. defer old.Conntrack.Unlock()
  315. // Re-read under the lock in case a concurrent reload swapped in a new
  316. // Firewall between the unlocked load above and here. Both Firewalls share
  317. // the same Conntrack pointer in the normal (non-overflow) reload path,
  318. // so the lock we hold is the right one for whichever we see now.
  319. current := c.f.firewall
  320. fw := *current
  321. fw.reporter = r
  322. c.f.firewall = &fw
  323. }
  324. func copyHostInfo(h *HostInfo, preferredRanges []netip.Prefix) ControlHostInfo {
  325. chi := ControlHostInfo{
  326. VpnAddrs: make([]netip.Addr, len(h.vpnAddrs)),
  327. LocalIndex: h.localIndexId,
  328. RemoteIndex: h.remoteIndexId,
  329. RemoteAddrs: h.remotes.CopyAddrs(preferredRanges),
  330. CurrentRelaysToMe: h.relayState.CopyRelayIps(),
  331. CurrentRelaysThroughMe: h.relayState.CopyRelayForIps(),
  332. CurrentRemote: h.remote,
  333. }
  334. for i, a := range h.vpnAddrs {
  335. chi.VpnAddrs[i] = a
  336. }
  337. if h.ConnectionState != nil {
  338. chi.MessageCounter = h.ConnectionState.messageCounter.Load()
  339. }
  340. if c := h.GetCert(); c != nil {
  341. chi.Cert = c.Certificate.Copy()
  342. }
  343. return chi
  344. }
  345. func listHostMapHosts(hl controlHostLister) []ControlHostInfo {
  346. hosts := make([]ControlHostInfo, 0)
  347. pr := hl.GetPreferredRanges()
  348. hl.ForEachVpnAddr(func(hostinfo *HostInfo) {
  349. hosts = append(hosts, copyHostInfo(hostinfo, pr))
  350. })
  351. return hosts
  352. }
  353. func listHostMapIndexes(hl controlHostLister) []ControlHostInfo {
  354. hosts := make([]ControlHostInfo, 0)
  355. pr := hl.GetPreferredRanges()
  356. hl.ForEachIndex(func(hostinfo *HostInfo) {
  357. hosts = append(hosts, copyHostInfo(hostinfo, pr))
  358. })
  359. return hosts
  360. }