control.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. package nebula
  2. import (
  3. "context"
  4. "net"
  5. "os"
  6. "os/signal"
  7. "sync/atomic"
  8. "syscall"
  9. "github.com/sirupsen/logrus"
  10. "github.com/slackhq/nebula/cert"
  11. "github.com/slackhq/nebula/header"
  12. "github.com/slackhq/nebula/iputil"
  13. "github.com/slackhq/nebula/udp"
  14. )
  15. // Every interaction here needs to take extra care to copy memory and not return or use arguments "as is" when touching
  16. // core. This means copying IP objects, slices, de-referencing pointers and taking the actual value, etc
  17. type Control struct {
  18. f *Interface
  19. l *logrus.Logger
  20. cancel context.CancelFunc
  21. sshStart func()
  22. statsStart func()
  23. dnsStart func()
  24. }
  25. type ControlHostInfo struct {
  26. VpnIp net.IP `json:"vpnIp"`
  27. LocalIndex uint32 `json:"localIndex"`
  28. RemoteIndex uint32 `json:"remoteIndex"`
  29. RemoteAddrs []*udp.Addr `json:"remoteAddrs"`
  30. CachedPackets int `json:"cachedPackets"`
  31. Cert *cert.NebulaCertificate `json:"cert"`
  32. MessageCounter uint64 `json:"messageCounter"`
  33. CurrentRemote *udp.Addr `json:"currentRemote"`
  34. }
  35. // Start actually runs nebula, this is a nonblocking call. To block use Control.ShutdownBlock()
  36. func (c *Control) Start() {
  37. // Activate the interface
  38. c.f.activate()
  39. // Call all the delayed funcs that waited patiently for the interface to be created.
  40. if c.sshStart != nil {
  41. go c.sshStart()
  42. }
  43. if c.statsStart != nil {
  44. go c.statsStart()
  45. }
  46. if c.dnsStart != nil {
  47. go c.dnsStart()
  48. }
  49. // Start reading packets.
  50. c.f.run()
  51. }
  52. // Stop signals nebula to shutdown, returns after the shutdown is complete
  53. func (c *Control) Stop() {
  54. //TODO: stop tun and udp routines, the lock on hostMap effectively does that though
  55. c.CloseAllTunnels(false)
  56. c.cancel()
  57. c.l.Info("Goodbye")
  58. }
  59. // ShutdownBlock will listen for and block on term and interrupt signals, calling Control.Stop() once signalled
  60. func (c *Control) ShutdownBlock() {
  61. sigChan := make(chan os.Signal)
  62. signal.Notify(sigChan, syscall.SIGTERM)
  63. signal.Notify(sigChan, syscall.SIGINT)
  64. rawSig := <-sigChan
  65. sig := rawSig.String()
  66. c.l.WithField("signal", sig).Info("Caught signal, shutting down")
  67. c.Stop()
  68. }
  69. // RebindUDPServer asks the UDP listener to rebind it's listener. Mainly used on mobile clients when interfaces change
  70. func (c *Control) RebindUDPServer() {
  71. _ = c.f.outside.Rebind()
  72. // Trigger a lighthouse update, useful for mobile clients that should have an update interval of 0
  73. c.f.lightHouse.SendUpdate(c.f)
  74. // Let the main interface know that we rebound so that underlying tunnels know to trigger punches from their remotes
  75. c.f.rebindCount++
  76. }
  77. // ListHostmap returns details about the actual or pending (handshaking) hostmap
  78. func (c *Control) ListHostmap(pendingMap bool) []ControlHostInfo {
  79. if pendingMap {
  80. return listHostMap(c.f.handshakeManager.pendingHostMap)
  81. } else {
  82. return listHostMap(c.f.hostMap)
  83. }
  84. }
  85. // GetHostInfoByVpnIp returns a single tunnels hostInfo, or nil if not found
  86. func (c *Control) GetHostInfoByVpnIp(vpnIp iputil.VpnIp, pending bool) *ControlHostInfo {
  87. var hm *HostMap
  88. if pending {
  89. hm = c.f.handshakeManager.pendingHostMap
  90. } else {
  91. hm = c.f.hostMap
  92. }
  93. h, err := hm.QueryVpnIp(vpnIp)
  94. if err != nil {
  95. return nil
  96. }
  97. ch := copyHostInfo(h, c.f.hostMap.preferredRanges)
  98. return &ch
  99. }
  100. // SetRemoteForTunnel forces a tunnel to use a specific remote
  101. func (c *Control) SetRemoteForTunnel(vpnIp iputil.VpnIp, addr udp.Addr) *ControlHostInfo {
  102. hostInfo, err := c.f.hostMap.QueryVpnIp(vpnIp)
  103. if err != nil {
  104. return nil
  105. }
  106. hostInfo.SetRemote(addr.Copy())
  107. ch := copyHostInfo(hostInfo, c.f.hostMap.preferredRanges)
  108. return &ch
  109. }
  110. // CloseTunnel closes a fully established tunnel. If localOnly is false it will notify the remote end as well.
  111. func (c *Control) CloseTunnel(vpnIp iputil.VpnIp, localOnly bool) bool {
  112. hostInfo, err := c.f.hostMap.QueryVpnIp(vpnIp)
  113. if err != nil {
  114. return false
  115. }
  116. if !localOnly {
  117. c.f.send(
  118. header.CloseTunnel,
  119. 0,
  120. hostInfo.ConnectionState,
  121. hostInfo,
  122. hostInfo.remote,
  123. []byte{},
  124. make([]byte, 12, 12),
  125. make([]byte, mtu),
  126. )
  127. }
  128. c.f.closeTunnel(hostInfo, false)
  129. return true
  130. }
  131. // CloseAllTunnels is just like CloseTunnel except it goes through and shuts them all down, optionally you can avoid shutting down lighthouse tunnels
  132. // the int returned is a count of tunnels closed
  133. func (c *Control) CloseAllTunnels(excludeLighthouses bool) (closed int) {
  134. //TODO: this is probably better as a function in ConnectionManager or HostMap directly
  135. c.f.hostMap.Lock()
  136. for _, h := range c.f.hostMap.Hosts {
  137. if excludeLighthouses {
  138. if _, ok := c.f.lightHouse.lighthouses[h.vpnIp]; ok {
  139. continue
  140. }
  141. }
  142. if h.ConnectionState.ready {
  143. c.f.send(header.CloseTunnel, 0, h.ConnectionState, h, h.remote, []byte{}, make([]byte, 12, 12), make([]byte, mtu))
  144. c.f.closeTunnel(h, true)
  145. c.l.WithField("vpnIp", h.vpnIp).WithField("udpAddr", h.remote).
  146. Debug("Sending close tunnel message")
  147. closed++
  148. }
  149. }
  150. c.f.hostMap.Unlock()
  151. return
  152. }
  153. func copyHostInfo(h *HostInfo, preferredRanges []*net.IPNet) ControlHostInfo {
  154. chi := ControlHostInfo{
  155. VpnIp: h.vpnIp.ToIP(),
  156. LocalIndex: h.localIndexId,
  157. RemoteIndex: h.remoteIndexId,
  158. RemoteAddrs: h.remotes.CopyAddrs(preferredRanges),
  159. CachedPackets: len(h.packetStore),
  160. }
  161. if h.ConnectionState != nil {
  162. chi.MessageCounter = atomic.LoadUint64(&h.ConnectionState.atomicMessageCounter)
  163. }
  164. if c := h.GetCert(); c != nil {
  165. chi.Cert = c.Copy()
  166. }
  167. if h.remote != nil {
  168. chi.CurrentRemote = h.remote.Copy()
  169. }
  170. return chi
  171. }
  172. func listHostMap(hm *HostMap) []ControlHostInfo {
  173. hm.RLock()
  174. hosts := make([]ControlHostInfo, len(hm.Hosts))
  175. i := 0
  176. for _, v := range hm.Hosts {
  177. hosts[i] = copyHostInfo(v, hm.preferredRanges)
  178. i++
  179. }
  180. hm.RUnlock()
  181. return hosts
  182. }