main.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. package nebula
  2. import (
  3. "context"
  4. "fmt"
  5. "log/slog"
  6. "net"
  7. "net/netip"
  8. "runtime/debug"
  9. "slices"
  10. "strings"
  11. "time"
  12. "github.com/slackhq/nebula/config"
  13. "github.com/slackhq/nebula/overlay"
  14. "github.com/slackhq/nebula/sshd"
  15. "github.com/slackhq/nebula/udp"
  16. "github.com/slackhq/nebula/util"
  17. "go.yaml.in/yaml/v3"
  18. )
  19. type m = map[string]any
  20. func Main(c *config.C, configTest bool, buildVersion string, l *slog.Logger, deviceFactory overlay.DeviceFactory) (retcon *Control, reterr error) {
  21. ctx, cancel := context.WithCancel(context.Background())
  22. // Automatically cancel the context if Main returns an error, to signal all created goroutines to quit.
  23. defer func() {
  24. if reterr != nil {
  25. cancel()
  26. }
  27. }()
  28. if buildVersion == "" {
  29. buildVersion = moduleVersion()
  30. }
  31. // Print the config if in test, the exit comes later
  32. if configTest {
  33. b, err := yaml.Marshal(c.Settings)
  34. if err != nil {
  35. return nil, err
  36. }
  37. // Print the final config
  38. l.Info(string(b))
  39. }
  40. pki, err := NewPKIFromConfig(l, c)
  41. if err != nil {
  42. return nil, util.ContextualizeIfNeeded("Failed to load PKI from config", err)
  43. }
  44. fw, err := NewFirewallFromConfig(l, pki.getCertState(), c)
  45. if err != nil {
  46. return nil, util.ContextualizeIfNeeded("Error while loading firewall rules", err)
  47. }
  48. l.Info("Firewall started", "firewallHashes", fw.GetRuleHashes())
  49. ssh, err := sshd.NewSSHServer(ctx, l.With("subsystem", "sshd"))
  50. if err != nil {
  51. return nil, util.ContextualizeIfNeeded("Error while creating SSH server", err)
  52. }
  53. wireSSHReload(l, ssh, c)
  54. var sshStart func()
  55. if c.GetBool("sshd.enabled", false) {
  56. sshStart, err = configSSH(l, ssh, c)
  57. if err != nil {
  58. l.Warn("Failed to configure sshd, ssh debugging will not be available", "error", err)
  59. sshStart = nil
  60. }
  61. }
  62. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  63. // All non system modifying configuration consumption should live above this line
  64. // tun config, listeners, anything modifying the computer should be below
  65. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  66. var routines int
  67. // If `routines` is set, use that and ignore the specific values
  68. if routines = c.GetInt("routines", 0); routines != 0 {
  69. if routines < 1 {
  70. routines = 1
  71. }
  72. if routines > 1 {
  73. l.Info("Using multiple routines", "routines", routines)
  74. }
  75. } else {
  76. // deprecated and undocumented
  77. tunQueues := c.GetInt("tun.routines", 1)
  78. udpQueues := c.GetInt("listen.routines", 1)
  79. routines = max(tunQueues, udpQueues)
  80. if routines != 1 {
  81. l.Warn("Setting tun.routines and listen.routines is deprecated. Use `routines` instead", "routines", routines)
  82. }
  83. }
  84. // EXPERIMENTAL
  85. // Intentionally not documented yet while we do more testing and determine
  86. // a good default value.
  87. conntrackCacheTimeout := c.GetDuration("firewall.conntrack.routine_cache_timeout", 0)
  88. if routines > 1 && !c.IsSet("firewall.conntrack.routine_cache_timeout") {
  89. // Use a different default if we are running with multiple routines
  90. conntrackCacheTimeout = 1 * time.Second
  91. }
  92. if conntrackCacheTimeout > 0 {
  93. l.Info("Using routine-local conntrack cache", "duration", conntrackCacheTimeout)
  94. }
  95. var tun overlay.Device
  96. if !configTest {
  97. c.CatchHUP(ctx)
  98. if deviceFactory == nil {
  99. deviceFactory = overlay.NewDeviceFromConfig
  100. }
  101. tun, err = deviceFactory(c, l, pki.getCertState().myVpnNetworks, routines)
  102. if err != nil {
  103. return nil, util.ContextualizeIfNeeded("Failed to get a tun/tap device", err)
  104. }
  105. defer func() {
  106. if reterr != nil {
  107. tun.Close()
  108. }
  109. }()
  110. }
  111. // set up our UDP listener
  112. udpConns := make([]udp.Conn, routines)
  113. port := c.GetInt("listen.port", 0)
  114. // Callers get no handle to these until the Control is returned, release them on any error.
  115. defer func() {
  116. if reterr != nil {
  117. for _, u := range udpConns {
  118. if u != nil {
  119. _ = u.Close()
  120. }
  121. }
  122. }
  123. }()
  124. if !configTest {
  125. rawListenHost := c.GetString("listen.host", "0.0.0.0")
  126. var listenHost netip.Addr
  127. if rawListenHost == "[::]" {
  128. // Old guidance was to provide the literal `[::]` in `listen.host` but that won't resolve.
  129. listenHost = netip.IPv6Unspecified()
  130. } else {
  131. ips, err := net.DefaultResolver.LookupNetIP(context.Background(), "ip", rawListenHost)
  132. if err != nil {
  133. return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
  134. }
  135. if len(ips) == 0 {
  136. return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
  137. }
  138. listenHost = ips[0].Unmap()
  139. }
  140. for i := 0; i < routines; i++ {
  141. l.Info("listening", "addr", netip.AddrPortFrom(listenHost, uint16(port)))
  142. udpServer, err := udp.NewListener(l, listenHost, port, routines > 1, c.GetInt("listen.batch", 64))
  143. if err != nil {
  144. return nil, util.NewContextualError("Failed to open udp listener", m{"queue": i}, err)
  145. }
  146. udpServer.ReloadConfig(c)
  147. udpConns[i] = udpServer
  148. // If port is dynamic, discover it before the next pass through the for loop
  149. // This way all routines will use the same port correctly
  150. if port == 0 {
  151. uPort, err := udpServer.LocalAddr()
  152. if err != nil {
  153. return nil, util.NewContextualError("Failed to get listening port", nil, err)
  154. }
  155. port = int(uPort.Port())
  156. }
  157. }
  158. }
  159. hostMap := NewHostMapFromConfig(l, c)
  160. punchy := NewPunchyFromConfig(l, c, udpConns[0])
  161. connManager := newConnectionManagerFromConfig(l, c, hostMap, punchy)
  162. lightHouse, err := NewLightHouseFromConfig(ctx, l, c, pki.getCertState(), udpConns[0], punchy)
  163. if err != nil {
  164. return nil, util.ContextualizeIfNeeded("Failed to initialize lighthouse handler", err)
  165. }
  166. var messageMetrics *MessageMetrics
  167. if c.GetBool("stats.message_metrics", false) {
  168. messageMetrics = newMessageMetrics()
  169. } else {
  170. messageMetrics = newMessageMetricsOnlyRecvError()
  171. }
  172. handshakeConfig := HandshakeConfig{
  173. tryInterval: c.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
  174. retries: int64(c.GetInt("handshakes.retries", DefaultHandshakeRetries)),
  175. triggerBuffer: c.GetInt("handshakes.trigger_buffer", DefaultHandshakeTriggerBuffer),
  176. messageMetrics: messageMetrics,
  177. }
  178. handshakeManager := NewHandshakeManager(l, hostMap, lightHouse, udpConns[0], handshakeConfig)
  179. lightHouse.handshakeTrigger = handshakeManager.trigger
  180. ds, err := newDnsServerFromConfig(ctx, l, pki, hostMap, c)
  181. if err != nil {
  182. l.Warn("Failed to start DNS responder", "error", err)
  183. }
  184. ifConfig := &InterfaceConfig{
  185. HostMap: hostMap,
  186. Inside: tun,
  187. Outside: udpConns[0],
  188. pki: pki,
  189. Firewall: fw,
  190. DnsServer: ds,
  191. HandshakeManager: handshakeManager,
  192. connectionManager: connManager,
  193. lightHouse: lightHouse,
  194. tryPromoteEvery: c.GetUint32("counters.try_promote", defaultPromoteEvery),
  195. reQueryEvery: c.GetUint32("counters.requery_every_packets", defaultReQueryEvery),
  196. reQueryWait: c.GetDuration("timers.requery_wait_duration", defaultReQueryWait),
  197. DropLocalBroadcast: c.GetBool("tun.drop_local_broadcast", false),
  198. DropMulticast: c.GetBool("tun.drop_multicast", false),
  199. routines: routines,
  200. MessageMetrics: messageMetrics,
  201. version: buildVersion,
  202. relayManager: NewRelayManager(ctx, l, hostMap, c),
  203. punchy: punchy,
  204. ConntrackCacheTimeout: conntrackCacheTimeout,
  205. CpuAffinity: parseCpuAffinity(c, l, routines),
  206. PinThreads: c.GetBool("tun.pin_threads", true),
  207. l: l,
  208. }
  209. var ifce *Interface
  210. if !configTest {
  211. ifce, err = NewInterface(ctx, ifConfig)
  212. if err != nil {
  213. return nil, fmt.Errorf("failed to initialize interface: %s", err)
  214. }
  215. ifce.writers = udpConns
  216. lightHouse.ifce = ifce
  217. ifce.RegisterConfigChangeCallbacks(c)
  218. ifce.reloadDisconnectInvalid(c)
  219. ifce.reloadSendRecvError(c)
  220. ifce.reloadAcceptRecvError(c)
  221. handshakeManager.f = ifce
  222. go handshakeManager.Run(ctx)
  223. punchy.Start(ctx, ifce, hostMap, lightHouse)
  224. }
  225. stats, err := newStatsServerFromConfig(ctx, l, c, buildVersion, configTest)
  226. if err != nil {
  227. return nil, util.ContextualizeIfNeeded("Failed to start stats emitter", err)
  228. }
  229. if configTest {
  230. return nil, nil
  231. }
  232. go ifce.emitStats(ctx, c.GetDuration("stats.interval", time.Second*10))
  233. attachCommands(l, c, ssh, ifce)
  234. return &Control{
  235. state: StateReady,
  236. f: ifce,
  237. l: l,
  238. ctx: ctx,
  239. cancel: cancel,
  240. sshStart: sshStart,
  241. statsStart: stats.Start,
  242. dnsStart: ds.Start,
  243. lighthouseStart: lightHouse.StartUpdateWorker,
  244. connectionManagerStart: connManager.Start,
  245. }, nil
  246. }
  247. // parseCpuAffinity reads `tun.cpu_affinity` from the config — a list of
  248. // integer CPU IDs, one per TUN reader goroutine. Empty / unset returns nil
  249. // (listenIn falls back to spreading queues across the allowed CPU set).
  250. // Length mismatch with `routines` is a warning, not an error: shorter lists
  251. // are modulo-cycled across queues, longer lists' tail is ignored. Invalid
  252. // entries (non-integer, or a CPU ID we're not allowed to run on) are also a
  253. // warning and disable the override entirely so we don't silently pin to the
  254. // wrong CPU. Entries are validated against the process's current affinity
  255. // mask (util.AllowedCPUs) rather than 0..NumCPU-1: under a cgroup cpuset or
  256. // taskset the runnable IDs are frequently not that contiguous range, and
  257. // pinning to an unrunnable ID always fails. If the allowed set can't be
  258. // determined we fall back to a plain non-negative check.
  259. func parseCpuAffinity(c *config.C, l *slog.Logger, routines int) []int {
  260. raw := c.Get("tun.cpu_affinity")
  261. if raw == nil {
  262. return nil
  263. }
  264. rv, ok := raw.([]any)
  265. if !ok {
  266. l.Warn("tun.cpu_affinity must be a list of integers; ignoring", "value", raw)
  267. return nil
  268. }
  269. // allowed is the set of CPU IDs we're actually permitted to run on. A nil
  270. // slice (unsupported platform or lookup error) means "can't tell", so we
  271. // only apply the weaker non-negative check in that case.
  272. allowed, err := util.AllowedCPUs()
  273. if err != nil {
  274. l.Warn("could not determine allowed CPUs; validating tun.cpu_affinity against non-negative only", "error", err)
  275. allowed = nil
  276. }
  277. cpus := make([]int, 0, len(rv))
  278. for i, e := range rv {
  279. var cpu int
  280. switch v := e.(type) {
  281. case int:
  282. cpu = v
  283. case int64:
  284. cpu = int(v)
  285. case float64:
  286. cpu = int(v)
  287. default:
  288. l.Warn("tun.cpu_affinity entry not an integer; ignoring affinity",
  289. "index", i, "value", e)
  290. return nil
  291. }
  292. if cpu < 0 {
  293. l.Warn("tun.cpu_affinity entry out of range; ignoring affinity",
  294. "index", i, "cpu", cpu)
  295. return nil
  296. }
  297. if len(allowed) > 0 && !slices.Contains(allowed, cpu) {
  298. l.Warn("tun.cpu_affinity entry not in allowed CPU set; ignoring affinity",
  299. "index", i, "cpu", cpu, "allowed", allowed)
  300. return nil
  301. }
  302. cpus = append(cpus, cpu)
  303. }
  304. if len(cpus) != routines {
  305. l.Warn("tun.cpu_affinity length doesn't match routines; queues will modulo-cycle through the list",
  306. "affinity_len", len(cpus), "routines", routines)
  307. }
  308. return cpus
  309. }
  310. func moduleVersion() string {
  311. info, ok := debug.ReadBuildInfo()
  312. if !ok {
  313. return ""
  314. }
  315. for _, dep := range info.Deps {
  316. if dep.Path == "github.com/slackhq/nebula" {
  317. return strings.TrimPrefix(dep.Version, "v")
  318. }
  319. }
  320. return ""
  321. }