control.go 10 KB

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