main.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. package nebula
  2. import (
  3. "context"
  4. "fmt"
  5. "log/slog"
  6. "net"
  7. "net/netip"
  8. "runtime/debug"
  9. "strings"
  10. "time"
  11. "github.com/slackhq/nebula/config"
  12. "github.com/slackhq/nebula/overlay"
  13. "github.com/slackhq/nebula/sshd"
  14. "github.com/slackhq/nebula/udp"
  15. "github.com/slackhq/nebula/util"
  16. "go.yaml.in/yaml/v3"
  17. )
  18. type m = map[string]any
  19. func Main(c *config.C, configTest bool, buildVersion string, l *slog.Logger, deviceFactory overlay.DeviceFactory) (retcon *Control, reterr error) {
  20. ctx, cancel := context.WithCancel(context.Background())
  21. // Automatically cancel the context if Main returns an error, to signal all created goroutines to quit.
  22. defer func() {
  23. if reterr != nil {
  24. cancel()
  25. }
  26. }()
  27. if buildVersion == "" {
  28. buildVersion = moduleVersion()
  29. }
  30. // Print the config if in test, the exit comes later
  31. if configTest {
  32. b, err := yaml.Marshal(c.Settings)
  33. if err != nil {
  34. return nil, err
  35. }
  36. // Print the final config
  37. l.Info(string(b))
  38. }
  39. pki, err := NewPKIFromConfig(l, c)
  40. if err != nil {
  41. return nil, util.ContextualizeIfNeeded("Failed to load PKI from config", err)
  42. }
  43. fw, err := NewFirewallFromConfig(l, pki.getCertState(), c)
  44. if err != nil {
  45. return nil, util.ContextualizeIfNeeded("Error while loading firewall rules", err)
  46. }
  47. l.Info("Firewall started", "firewallHashes", fw.GetRuleHashes())
  48. ssh, err := sshd.NewSSHServer(ctx, l.With("subsystem", "sshd"))
  49. if err != nil {
  50. return nil, util.ContextualizeIfNeeded("Error while creating SSH server", err)
  51. }
  52. wireSSHReload(l, ssh, c)
  53. var sshStart func()
  54. if c.GetBool("sshd.enabled", false) {
  55. sshStart, err = configSSH(l, ssh, c)
  56. if err != nil {
  57. l.Warn("Failed to configure sshd, ssh debugging will not be available", "error", err)
  58. sshStart = nil
  59. }
  60. }
  61. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  62. // All non system modifying configuration consumption should live above this line
  63. // tun config, listeners, anything modifying the computer should be below
  64. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  65. var routines int
  66. // If `routines` is set, use that and ignore the specific values
  67. if routines = c.GetInt("routines", 0); routines != 0 {
  68. if routines < 1 {
  69. routines = 1
  70. }
  71. if routines > 1 {
  72. l.Info("Using multiple routines", "routines", routines)
  73. }
  74. } else {
  75. // deprecated and undocumented
  76. tunQueues := c.GetInt("tun.routines", 1)
  77. udpQueues := c.GetInt("listen.routines", 1)
  78. routines = max(tunQueues, udpQueues)
  79. if routines != 1 {
  80. l.Warn("Setting tun.routines and listen.routines is deprecated. Use `routines` instead", "routines", routines)
  81. }
  82. }
  83. // EXPERIMENTAL
  84. // Intentionally not documented yet while we do more testing and determine
  85. // a good default value.
  86. conntrackCacheTimeout := c.GetDuration("firewall.conntrack.routine_cache_timeout", 0)
  87. if routines > 1 && !c.IsSet("firewall.conntrack.routine_cache_timeout") {
  88. // Use a different default if we are running with multiple routines
  89. conntrackCacheTimeout = 1 * time.Second
  90. }
  91. if conntrackCacheTimeout > 0 {
  92. l.Info("Using routine-local conntrack cache", "duration", conntrackCacheTimeout)
  93. }
  94. var tun overlay.Device
  95. if !configTest {
  96. c.CatchHUP(ctx)
  97. if deviceFactory == nil {
  98. deviceFactory = overlay.NewDeviceFromConfig
  99. }
  100. tun, err = deviceFactory(c, l, pki.getCertState().myVpnNetworks, routines)
  101. if err != nil {
  102. return nil, util.ContextualizeIfNeeded("Failed to get a tun/tap device", err)
  103. }
  104. defer func() {
  105. if reterr != nil {
  106. tun.Close()
  107. }
  108. }()
  109. }
  110. // set up our UDP listener
  111. udpConns := make([]udp.Conn, routines)
  112. port := c.GetInt("listen.port", 0)
  113. if !configTest {
  114. rawListenHost := c.GetString("listen.host", "0.0.0.0")
  115. var listenHost netip.Addr
  116. if rawListenHost == "[::]" {
  117. // Old guidance was to provide the literal `[::]` in `listen.host` but that won't resolve.
  118. listenHost = netip.IPv6Unspecified()
  119. } else {
  120. ips, err := net.DefaultResolver.LookupNetIP(context.Background(), "ip", rawListenHost)
  121. if err != nil {
  122. return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
  123. }
  124. if len(ips) == 0 {
  125. return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
  126. }
  127. listenHost = ips[0].Unmap()
  128. }
  129. for i := 0; i < routines; i++ {
  130. l.Info("listening", "addr", netip.AddrPortFrom(listenHost, uint16(port)))
  131. udpServer, err := udp.NewListener(l, listenHost, port, routines > 1, c.GetInt("listen.batch", 64))
  132. if err != nil {
  133. return nil, util.NewContextualError("Failed to open udp listener", m{"queue": i}, err)
  134. }
  135. udpServer.ReloadConfig(c)
  136. udpConns[i] = udpServer
  137. // If port is dynamic, discover it before the next pass through the for loop
  138. // This way all routines will use the same port correctly
  139. if port == 0 {
  140. uPort, err := udpServer.LocalAddr()
  141. if err != nil {
  142. return nil, util.NewContextualError("Failed to get listening port", nil, err)
  143. }
  144. port = int(uPort.Port())
  145. }
  146. }
  147. }
  148. hostMap := NewHostMapFromConfig(l, c)
  149. punchy := NewPunchyFromConfig(l, c, udpConns[0])
  150. connManager := newConnectionManagerFromConfig(l, c, hostMap, punchy)
  151. lightHouse, err := NewLightHouseFromConfig(ctx, l, c, pki.getCertState(), udpConns[0], punchy)
  152. if err != nil {
  153. return nil, util.ContextualizeIfNeeded("Failed to initialize lighthouse handler", err)
  154. }
  155. var messageMetrics *MessageMetrics
  156. if c.GetBool("stats.message_metrics", false) {
  157. messageMetrics = newMessageMetrics()
  158. } else {
  159. messageMetrics = newMessageMetricsOnlyRecvError()
  160. }
  161. handshakeConfig := HandshakeConfig{
  162. tryInterval: c.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
  163. retries: int64(c.GetInt("handshakes.retries", DefaultHandshakeRetries)),
  164. triggerBuffer: c.GetInt("handshakes.trigger_buffer", DefaultHandshakeTriggerBuffer),
  165. messageMetrics: messageMetrics,
  166. }
  167. handshakeManager := NewHandshakeManager(l, hostMap, lightHouse, udpConns[0], handshakeConfig)
  168. lightHouse.handshakeTrigger = handshakeManager.trigger
  169. ds, err := newDnsServerFromConfig(ctx, l, pki, hostMap, c)
  170. if err != nil {
  171. l.Warn("Failed to start DNS responder", "error", err)
  172. }
  173. ifConfig := &InterfaceConfig{
  174. HostMap: hostMap,
  175. Inside: tun,
  176. Outside: udpConns[0],
  177. pki: pki,
  178. Firewall: fw,
  179. DnsServer: ds,
  180. HandshakeManager: handshakeManager,
  181. connectionManager: connManager,
  182. lightHouse: lightHouse,
  183. tryPromoteEvery: c.GetUint32("counters.try_promote", defaultPromoteEvery),
  184. reQueryEvery: c.GetUint32("counters.requery_every_packets", defaultReQueryEvery),
  185. reQueryWait: c.GetDuration("timers.requery_wait_duration", defaultReQueryWait),
  186. DropLocalBroadcast: c.GetBool("tun.drop_local_broadcast", false),
  187. DropMulticast: c.GetBool("tun.drop_multicast", false),
  188. routines: routines,
  189. MessageMetrics: messageMetrics,
  190. version: buildVersion,
  191. relayManager: NewRelayManager(ctx, l, hostMap, c),
  192. punchy: punchy,
  193. ConntrackCacheTimeout: conntrackCacheTimeout,
  194. l: l,
  195. }
  196. var ifce *Interface
  197. if !configTest {
  198. ifce, err = NewInterface(ctx, ifConfig)
  199. if err != nil {
  200. return nil, fmt.Errorf("failed to initialize interface: %s", err)
  201. }
  202. ifce.writers = udpConns
  203. lightHouse.ifce = ifce
  204. ifce.RegisterConfigChangeCallbacks(c)
  205. ifce.reloadDisconnectInvalid(c)
  206. ifce.reloadSendRecvError(c)
  207. ifce.reloadAcceptRecvError(c)
  208. handshakeManager.f = ifce
  209. go handshakeManager.Run(ctx)
  210. punchy.Start(ctx, ifce, hostMap, lightHouse)
  211. }
  212. stats, err := newStatsServerFromConfig(ctx, l, c, buildVersion, configTest)
  213. if err != nil {
  214. return nil, util.ContextualizeIfNeeded("Failed to start stats emitter", err)
  215. }
  216. if configTest {
  217. return nil, nil
  218. }
  219. go ifce.emitStats(ctx, c.GetDuration("stats.interval", time.Second*10))
  220. attachCommands(l, c, ssh, ifce)
  221. return &Control{
  222. state: StateReady,
  223. f: ifce,
  224. l: l,
  225. ctx: ctx,
  226. cancel: cancel,
  227. sshStart: sshStart,
  228. statsStart: stats.Start,
  229. dnsStart: ds.Start,
  230. lighthouseStart: lightHouse.StartUpdateWorker,
  231. connectionManagerStart: connManager.Start,
  232. }, nil
  233. }
  234. func moduleVersion() string {
  235. info, ok := debug.ReadBuildInfo()
  236. if !ok {
  237. return ""
  238. }
  239. for _, dep := range info.Deps {
  240. if dep.Path == "github.com/slackhq/nebula" {
  241. return strings.TrimPrefix(dep.Version, "v")
  242. }
  243. }
  244. return ""
  245. }