1
0

main.go 15 KB

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