main.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. package nebula
  2. import (
  3. "context"
  4. "fmt"
  5. "log/slog"
  6. "net"
  7. "net/netip"
  8. "os"
  9. "runtime/debug"
  10. "slices"
  11. "strings"
  12. "time"
  13. "github.com/slackhq/nebula/config"
  14. "github.com/slackhq/nebula/cpupick"
  15. "github.com/slackhq/nebula/noiseutil"
  16. "github.com/slackhq/nebula/overlay"
  17. "github.com/slackhq/nebula/sshd"
  18. "github.com/slackhq/nebula/udp"
  19. "github.com/slackhq/nebula/util"
  20. "go.yaml.in/yaml/v3"
  21. )
  22. type m = map[string]any
  23. // maxRoutines caps routines below the RejectHeadroom nonce gap so concurrent senders can't race the counter past wrap.
  24. const maxRoutines = 1 << 16
  25. // The reject headroom must exceed every sender that can be mid-reservation at once, about two per routine.
  26. const _ = noiseutil.RejectHeadroom - 4*maxRoutines
  27. func Main(c *config.C, configTest bool, buildVersion string, l *slog.Logger, deviceFactory overlay.DeviceFactory) (retcon *Control, reterr error) {
  28. ctx, cancel := context.WithCancel(context.Background())
  29. // The goroutines started below stop only when this context does, and only a caller holding the
  30. // Control can arrange that. Cancel whenever we are not handing one back, which covers an error
  31. // and a config test alike: a config test used to leave the lighthouse query worker, and a
  32. // hostname resolver per dns named static host, running for the life of the process.
  33. defer func() {
  34. if retcon == nil {
  35. cancel()
  36. }
  37. }()
  38. if buildVersion == "" {
  39. buildVersion = moduleVersion()
  40. }
  41. // Debug builds (-tags debug) serve pprof on :6060; a no-op otherwise.
  42. startPprofServer(ctx, l)
  43. // Print the config if in test, the exit comes later
  44. if configTest {
  45. b, err := yaml.Marshal(c.Settings)
  46. if err != nil {
  47. return nil, err
  48. }
  49. // Print the final config
  50. l.Info(string(b))
  51. }
  52. pki, err := NewPKIFromConfig(l, c)
  53. if err != nil {
  54. return nil, util.ContextualizeIfNeeded("Failed to load PKI from config", err)
  55. }
  56. fw, err := NewFirewallFromConfig(l, pki.getCertState(), c)
  57. if err != nil {
  58. return nil, util.ContextualizeIfNeeded("Error while loading firewall rules", err)
  59. }
  60. l.Info("Firewall started", "firewallHashes", fw.GetRuleHashes())
  61. ssh, err := sshd.NewSSHServer(ctx, l.With("subsystem", "sshd"))
  62. if err != nil {
  63. return nil, util.ContextualizeIfNeeded("Error while creating SSH server", err)
  64. }
  65. wireSSHReload(l, ssh, c)
  66. var sshStart func()
  67. if c.GetBool("sshd.enabled", false) {
  68. sshStart, err = configSSH(l, ssh, c, nil)
  69. if err != nil {
  70. l.Warn("Failed to configure sshd, ssh debugging will not be available", "error", err)
  71. sshStart = nil
  72. }
  73. }
  74. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  75. // All non system modifying configuration consumption should live above this line
  76. // tun config, listeners, anything modifying the computer should be below
  77. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  78. var routines int
  79. // If `routines` is set, use that and ignore the specific values
  80. if routines = c.GetInt("routines", 0); routines != 0 {
  81. if routines < 1 {
  82. routines = 1
  83. }
  84. } else {
  85. // deprecated and undocumented
  86. tunQueues := c.GetInt("tun.routines", 1)
  87. udpQueues := c.GetInt("listen.routines", 1)
  88. routines = max(tunQueues, udpQueues)
  89. if routines != 1 {
  90. l.Warn("Setting tun.routines and listen.routines is deprecated. Use `routines` instead", "routines", routines)
  91. }
  92. }
  93. if routines > maxRoutines {
  94. l.Warn("Using multiple routines", "routines", maxRoutines, "clamped", true, "requestedRoutines", routines)
  95. routines = maxRoutines
  96. } else if routines > 1 {
  97. l.Info("Using multiple routines", "routines", routines)
  98. }
  99. // EXPERIMENTAL
  100. // Intentionally not documented yet while we do more testing and determine
  101. // a good default value.
  102. conntrackCacheTimeout := c.GetDuration("firewall.conntrack.routine_cache_timeout", 0)
  103. if routines > 1 && !c.IsSet("firewall.conntrack.routine_cache_timeout") {
  104. // Use a different default if we are running with multiple routines
  105. conntrackCacheTimeout = 1 * time.Second
  106. }
  107. if conntrackCacheTimeout > 0 {
  108. l.Info("Using routine-local conntrack cache", "duration", conntrackCacheTimeout)
  109. }
  110. var tun overlay.Device
  111. if !configTest {
  112. c.CatchHUP(ctx)
  113. if deviceFactory == nil {
  114. deviceFactory = overlay.NewDeviceFromConfig
  115. }
  116. tun, err = deviceFactory(c, l, pki.getCertState().myVpnNetworks, routines)
  117. if err != nil {
  118. return nil, util.ContextualizeIfNeeded("Failed to get a tun/tap device", err)
  119. }
  120. defer func() {
  121. if reterr != nil {
  122. tun.Close()
  123. }
  124. }()
  125. }
  126. // set up our UDP listener
  127. udpConns := make([]udp.Conn, routines)
  128. port := c.GetInt("listen.port", 0)
  129. // Callers get no handle to these until the Control is returned, release them on any error.
  130. defer func() {
  131. if reterr != nil {
  132. for _, u := range udpConns {
  133. if u != nil {
  134. _ = u.Close()
  135. }
  136. }
  137. }
  138. }()
  139. if !configTest {
  140. rawListenHost := c.GetString("listen.host", "0.0.0.0")
  141. var listenHost netip.Addr
  142. if rawListenHost == "[::]" {
  143. // Old guidance was to provide the literal `[::]` in `listen.host` but that won't resolve.
  144. listenHost = netip.IPv6Unspecified()
  145. } else {
  146. ips, err := net.DefaultResolver.LookupNetIP(context.Background(), "ip", rawListenHost)
  147. if err != nil {
  148. return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
  149. }
  150. if len(ips) == 0 {
  151. return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
  152. }
  153. listenHost = ips[0].Unmap()
  154. }
  155. for i := 0; i < routines; i++ {
  156. listen := netip.AddrPortFrom(listenHost, uint16(port))
  157. l.Info("listening", "addr", listen)
  158. batchSize := c.GetInt("listen.batch", 64)
  159. if batchSize < 1 {
  160. oldBatch := batchSize
  161. batchSize = 1
  162. l.Warn("listen.batch size is invalid", "provided", oldBatch, "overridden to", batchSize)
  163. }
  164. udpSettings := udp.Settings{
  165. Listen: listen,
  166. Multi: routines > 1,
  167. Batch: batchSize,
  168. Offloads: c.GetBool("listen.udp_offloads", false),
  169. }
  170. udpServer, err := udp.NewListener(l, udpSettings)
  171. if err != nil {
  172. return nil, util.NewContextualError("Failed to open udp listener", m{"queue": i}, err)
  173. }
  174. udpServer.ReloadConfig(c, nil)
  175. udpConns[i] = udpServer
  176. // If port is dynamic, discover it before the next pass through the for loop
  177. // This way all routines will use the same port correctly
  178. if port == 0 {
  179. uPort, err := udpServer.LocalAddr()
  180. if err != nil {
  181. return nil, util.NewContextualError("Failed to get listening port", nil, err)
  182. }
  183. port = int(uPort.Port())
  184. }
  185. }
  186. }
  187. hostMap := NewHostMapFromConfig(l, c)
  188. punchy := NewPunchyFromConfig(l, c, udpConns[0])
  189. connManager := newConnectionManagerFromConfig(l, c, hostMap, punchy)
  190. lightHouse, err := NewLightHouseFromConfig(ctx, l, c, pki.getCertState(), udpConns[0], punchy)
  191. if err != nil {
  192. return nil, util.ContextualizeIfNeeded("Failed to initialize lighthouse handler", err)
  193. }
  194. var messageMetrics *MessageMetrics
  195. if c.GetBool("stats.message_metrics", false) {
  196. messageMetrics = newMessageMetrics()
  197. } else {
  198. messageMetrics = newMessageMetricsOnlyRecvError()
  199. }
  200. handshakeConfig := HandshakeConfig{
  201. tryInterval: c.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
  202. retries: int64(c.GetInt("handshakes.retries", DefaultHandshakeRetries)),
  203. triggerBuffer: c.GetInt("handshakes.trigger_buffer", DefaultHandshakeTriggerBuffer),
  204. messageMetrics: messageMetrics,
  205. }
  206. handshakeManager := NewHandshakeManager(l, hostMap, lightHouse, udpConns[0], handshakeConfig)
  207. lightHouse.handshakeTrigger = handshakeManager.trigger
  208. ds, err := newDnsServerFromConfig(ctx, l, pki, hostMap, c)
  209. if err != nil {
  210. l.Warn("Failed to start DNS responder", "error", err)
  211. }
  212. pinThreads := c.GetBool("tun.pin_threads", true)
  213. cpuAffinity := parseCpuAffinity(c, l, routines)
  214. var defaultCpuAffinity []int
  215. staged := parseStagedConfig(c, l)
  216. if pinThreads && routines > 1 && len(cpuAffinity) == 0 && !configTest {
  217. // The operator didn't choose pin CPUs, so pick a default set that
  218. // prefers performance cores and doesn't stack co-located instances
  219. // onto allowed[0].
  220. // key is used to seed the spreading of routines->cores.
  221. // use PID if you want to ensure many different Nebulas in VMs or containers land on different cores
  222. // use port if you want to always end up on the same cores, ideal for benchmarking.
  223. key := uint64(os.Getpid()) //default to PID
  224. pinKeyStr := strings.ToLower(c.GetString("tun.pin_threads_key", ""))
  225. switch pinKeyStr {
  226. case "":
  227. l.Debug("tun.pin_threads_key is empty, using PID")
  228. case "pid":
  229. l.Debug("tun.pin_threads_key is PID")
  230. case "port":
  231. if ap, err := udpConns[0].LocalAddr(); err == nil && ap.Port() != 0 {
  232. l.Info("tun.pin_threads_key is port number")
  233. key = uint64(ap.Port())
  234. } else {
  235. l.Warn("Failed to get a port number for tun.pin_threads_key, falling back to PID", "err", err)
  236. }
  237. default:
  238. l.Warn("tun.pin_threads_key is invalid, using PID")
  239. }
  240. defaultCpuAffinity = cpupick.Default(routines, key, l)
  241. }
  242. ifConfig := &InterfaceConfig{
  243. HostMap: hostMap,
  244. Inside: tun,
  245. Outside: udpConns[0],
  246. pki: pki,
  247. Firewall: fw,
  248. DnsServer: ds,
  249. HandshakeManager: handshakeManager,
  250. connectionManager: connManager,
  251. lightHouse: lightHouse,
  252. tryPromoteEvery: c.GetUint32("counters.try_promote", defaultPromoteEvery),
  253. reQueryEvery: c.GetUint32("counters.requery_every_packets", defaultReQueryEvery),
  254. reQueryWait: c.GetDuration("timers.requery_wait_duration", defaultReQueryWait),
  255. DropLocalBroadcast: c.GetBool("tun.drop_local_broadcast", false),
  256. DropMulticast: c.GetBool("tun.drop_multicast", false),
  257. routines: routines,
  258. MessageMetrics: messageMetrics,
  259. version: buildVersion,
  260. relayManager: NewRelayManager(ctx, l, hostMap, c),
  261. punchy: punchy,
  262. ConntrackCacheTimeout: conntrackCacheTimeout,
  263. CpuAffinity: cpuAffinity,
  264. defaultCpuAffinity: defaultCpuAffinity,
  265. PinThreads: pinThreads,
  266. staged: staged,
  267. l: l,
  268. }
  269. var ifce *Interface
  270. var emitStats func()
  271. if !configTest {
  272. ifce, err = NewInterface(ctx, ifConfig)
  273. if err != nil {
  274. return nil, fmt.Errorf("failed to initialize interface: %s", err)
  275. }
  276. ifce.writers = udpConns
  277. lightHouse.ifce = ifce
  278. ifce.RegisterConfigChangeCallbacks(c)
  279. // These are only read at startup
  280. c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
  281. r.RestartRequiredIfChanged(
  282. "routines", "tun.routines", "listen.routines", "firewall.conntrack.routine_cache_timeout",
  283. "listen.port", "listen.host", "stats.message_metrics",
  284. "handshakes.try_interval", "handshakes.retries", "handshakes.trigger_buffer",
  285. "tun.drop_local_broadcast", "tun.drop_multicast",
  286. )
  287. r.RestartRequiredIfChanged(osStartupOnlyKeys...)
  288. })
  289. ifce.reloadDisconnectInvalid(c)
  290. ifce.reloadSendRecvError(c)
  291. ifce.reloadAcceptRecvError(c)
  292. handshakeManager.f = ifce
  293. go handshakeManager.Run(ctx)
  294. punchy.Start(ctx, ifce, hostMap, lightHouse)
  295. // On the stats server's loop, so the gauges follow the interval it accepted
  296. emitStats = ifce.statsEmitter()
  297. }
  298. stats, err := newStatsServerFromConfig(ctx, l, c, buildVersion, configTest, emitStats)
  299. if err != nil {
  300. return nil, util.ContextualizeIfNeeded("Failed to start stats emitter", err)
  301. }
  302. if configTest {
  303. return nil, nil
  304. }
  305. attachCommands(l, c, ssh, ifce)
  306. networkChanges := udp.NewNetworkChangeMonitor(ctx, l, c)
  307. return &Control{
  308. state: StateReady,
  309. f: ifce,
  310. l: l,
  311. ctx: ctx,
  312. cancel: cancel,
  313. sshStart: sshStart,
  314. statsStart: stats.Start,
  315. dnsStart: ds.Start,
  316. lighthouseStart: lightHouse.StartUpdateWorker,
  317. networkChangeStart: networkChanges.Start,
  318. connectionManagerStart: connManager.Start,
  319. }, nil
  320. }
  321. // parseCpuAffinity reads `tun.cpu_affinity` from the config — a list of
  322. // integer CPU IDs, one per TUN reader goroutine. Empty / unset returns nil
  323. // (listenIn falls back to spreading queues across the allowed CPU set).
  324. // Length mismatch with `routines` is a warning, not an error: shorter lists
  325. // are modulo-cycled across queues, longer lists' tail is ignored. Invalid
  326. // entries (non-integer, or a CPU ID we're not allowed to run on) are also a
  327. // warning and disable the override entirely so we don't silently pin to the
  328. // wrong CPU. Entries are validated against the process's current affinity
  329. // mask (util.AllowedCPUs) rather than 0..NumCPU-1: under a cgroup cpuset or
  330. // taskset the runnable IDs are frequently not that contiguous range, and
  331. // pinning to an unrunnable ID always fails. If the allowed set can't be
  332. // determined we fall back to a plain non-negative check.
  333. func parseCpuAffinity(c *config.C, l *slog.Logger, routines int) []int {
  334. raw := c.Get("tun.cpu_affinity")
  335. if raw == nil {
  336. return nil
  337. }
  338. rv, ok := raw.([]any)
  339. if !ok {
  340. l.Warn("tun.cpu_affinity must be a list of integers; ignoring", "value", raw)
  341. return nil
  342. }
  343. // allowed is the set of CPU IDs we're actually permitted to run on. A nil
  344. // slice (unsupported platform or lookup error) means "can't tell", so we
  345. // only apply the weaker non-negative check in that case.
  346. allowed, err := util.AllowedCPUs()
  347. if err != nil {
  348. l.Warn("could not determine allowed CPUs; validating tun.cpu_affinity against non-negative only", "error", err)
  349. allowed = nil
  350. }
  351. cpus := make([]int, 0, len(rv))
  352. for i, e := range rv {
  353. var cpu int
  354. switch v := e.(type) {
  355. case int:
  356. cpu = v
  357. case int64:
  358. cpu = int(v)
  359. case float64:
  360. cpu = int(v)
  361. default:
  362. l.Warn("tun.cpu_affinity entry not an integer; ignoring affinity",
  363. "index", i, "value", e)
  364. return nil
  365. }
  366. if cpu < 0 {
  367. l.Warn("tun.cpu_affinity entry out of range; ignoring affinity",
  368. "index", i, "cpu", cpu)
  369. return nil
  370. }
  371. if len(allowed) > 0 && !slices.Contains(allowed, cpu) {
  372. l.Warn("tun.cpu_affinity entry not in allowed CPU set; ignoring affinity",
  373. "index", i, "cpu", cpu, "allowed", allowed)
  374. return nil
  375. }
  376. cpus = append(cpus, cpu)
  377. }
  378. if len(cpus) != routines {
  379. l.Warn("tun.cpu_affinity length doesn't match routines; queues will modulo-cycle through the list",
  380. "affinity_len", len(cpus), "routines", routines)
  381. }
  382. return cpus
  383. }
  384. func moduleVersion() string {
  385. info, ok := debug.ReadBuildInfo()
  386. if !ok {
  387. return ""
  388. }
  389. for _, dep := range info.Deps {
  390. if dep.Path == "github.com/slackhq/nebula" {
  391. return strings.TrimPrefix(dep.Version, "v")
  392. }
  393. }
  394. return ""
  395. }