main.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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)
  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)
  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. avoidCPUs := parseAvoidCPUs(c, l)
  214. if len(avoidCPUs) > 0 && !pinThreads {
  215. l.Warn("tun.avoid_cpus has no effect with tun.pin_threads disabled")
  216. }
  217. // Keeping every thread of the process off avoidCPUs, not just the pinned readers, is parked for now:
  218. //if err := cpupick.Avoid(avoidCPUs, !configTest); err != nil && !errors.Is(err, errors.ErrUnsupported) {
  219. // return nil, fmt.Errorf("tun.avoid_cpus: %w", err)
  220. //}
  221. cpuAffinity := parseCpuAffinity(c, l, routines, avoidCPUs)
  222. if pinThreads && routines > 1 && len(cpuAffinity) == 0 && !configTest {
  223. // The operator didn't choose pin CPUs, so pick a default set that
  224. // prefers performance cores, skips tun.avoid_cpus and doesn't stack
  225. // co-located instances onto allowed[0].
  226. // key is used to seed the spreading of routines->cores.
  227. // use PID if you want to ensure many different Nebulas in VMs or containers land on different cores
  228. // use port if you want to always end up on the same cores, ideal for benchmarking.
  229. key := uint64(os.Getpid()) //default to PID
  230. pinKeyStr := strings.ToLower(c.GetString("tun.pin_threads_key", ""))
  231. switch pinKeyStr {
  232. case "":
  233. l.Debug("tun.pin_threads_key is empty, using PID")
  234. case "pid":
  235. l.Debug("tun.pin_threads_key is PID")
  236. case "port":
  237. if ap, err := udpConns[0].LocalAddr(); err == nil && ap.Port() != 0 {
  238. l.Info("tun.pin_threads_key is port number")
  239. key = uint64(ap.Port())
  240. } else {
  241. l.Warn("Failed to get a port number for tun.pin_threads_key, falling back to PID", "err", err)
  242. }
  243. default:
  244. l.Warn("tun.pin_threads_key is invalid, using PID")
  245. }
  246. cpuAffinity = cpupick.Default(routines, key, avoidCPUs, l)
  247. }
  248. ifConfig := &InterfaceConfig{
  249. HostMap: hostMap,
  250. Inside: tun,
  251. Outside: udpConns[0],
  252. pki: pki,
  253. Firewall: fw,
  254. DnsServer: ds,
  255. HandshakeManager: handshakeManager,
  256. connectionManager: connManager,
  257. lightHouse: lightHouse,
  258. tryPromoteEvery: c.GetUint32("counters.try_promote", defaultPromoteEvery),
  259. reQueryEvery: c.GetUint32("counters.requery_every_packets", defaultReQueryEvery),
  260. reQueryWait: c.GetDuration("timers.requery_wait_duration", defaultReQueryWait),
  261. DropLocalBroadcast: c.GetBool("tun.drop_local_broadcast", false),
  262. DropMulticast: c.GetBool("tun.drop_multicast", false),
  263. routines: routines,
  264. MessageMetrics: messageMetrics,
  265. version: buildVersion,
  266. relayManager: NewRelayManager(ctx, l, hostMap, c),
  267. punchy: punchy,
  268. ConntrackCacheTimeout: conntrackCacheTimeout,
  269. CpuAffinity: cpuAffinity,
  270. AvoidCPUs: avoidCPUs,
  271. PinThreads: pinThreads,
  272. l: l,
  273. }
  274. var ifce *Interface
  275. var emitStats func()
  276. if !configTest {
  277. ifce, err = NewInterface(ctx, ifConfig)
  278. if err != nil {
  279. return nil, fmt.Errorf("failed to initialize interface: %s", err)
  280. }
  281. ifce.writers = udpConns
  282. lightHouse.ifce = ifce
  283. ifce.RegisterConfigChangeCallbacks(c)
  284. ifce.reloadDisconnectInvalid(c)
  285. ifce.reloadSendRecvError(c)
  286. ifce.reloadAcceptRecvError(c)
  287. handshakeManager.f = ifce
  288. go handshakeManager.Run(ctx)
  289. punchy.Start(ctx, ifce, hostMap, lightHouse)
  290. // On the stats server's loop, so the gauges follow the interval it accepted
  291. emitStats = ifce.statsEmitter()
  292. }
  293. stats, err := newStatsServerFromConfig(ctx, l, c, buildVersion, configTest, emitStats)
  294. if err != nil {
  295. return nil, util.ContextualizeIfNeeded("Failed to start stats emitter", err)
  296. }
  297. if configTest {
  298. return nil, nil
  299. }
  300. attachCommands(l, c, ssh, ifce)
  301. networkChanges := udp.NewNetworkChangeMonitor(ctx, l, c)
  302. return &Control{
  303. state: StateReady,
  304. f: ifce,
  305. l: l,
  306. ctx: ctx,
  307. cancel: cancel,
  308. sshStart: sshStart,
  309. statsStart: stats.Start,
  310. dnsStart: ds.Start,
  311. lighthouseStart: lightHouse.StartUpdateWorker,
  312. networkChangeStart: networkChanges.Start,
  313. connectionManagerStart: connManager.Start,
  314. }, nil
  315. }
  316. // parseCpuAffinity reads `tun.cpu_affinity` from the config — a list of
  317. // integer CPU IDs, one per TUN reader goroutine. Empty / unset returns nil
  318. // (listenIn falls back to spreading queues across the allowed CPU set).
  319. // Length mismatch with `routines` is a warning, not an error: shorter lists
  320. // are modulo-cycled across queues, longer lists' tail is ignored. Invalid
  321. // entries (non-integer, or a CPU ID we're not allowed to run on) are also a
  322. // warning and disable the override entirely so we don't silently pin to the
  323. // wrong CPU. Entries are validated against the process's current affinity
  324. // mask (util.AllowedCPUs) rather than 0..NumCPU-1: under a cgroup cpuset or
  325. // taskset the runnable IDs are frequently not that contiguous range, and
  326. // pinning to an unrunnable ID always fails. If the allowed set can't be
  327. // determined we fall back to a plain non-negative check. An entry listed in
  328. // avoid (tun.avoid_cpus) contradicts the operator's own config and is treated
  329. // the same as any other invalid entry.
  330. func parseCpuAffinity(c *config.C, l *slog.Logger, routines int, avoid []int) []int {
  331. raw := c.Get("tun.cpu_affinity")
  332. if raw == nil {
  333. return nil
  334. }
  335. rv, ok := raw.([]any)
  336. if !ok {
  337. l.Warn("tun.cpu_affinity must be a list of integers; ignoring", "value", raw)
  338. return nil
  339. }
  340. // allowed is the set of CPU IDs we're actually permitted to run on. A nil
  341. // slice (unsupported platform or lookup error) means "can't tell", so we
  342. // only apply the weaker non-negative check in that case.
  343. allowed, err := util.AllowedCPUs()
  344. if err != nil {
  345. l.Warn("could not determine allowed CPUs; validating tun.cpu_affinity against non-negative only", "error", err)
  346. allowed = nil
  347. }
  348. cpus := make([]int, 0, len(rv))
  349. for i, e := range rv {
  350. var cpu int
  351. switch v := e.(type) {
  352. case int:
  353. cpu = v
  354. case int64:
  355. cpu = int(v)
  356. case float64:
  357. cpu = int(v)
  358. default:
  359. l.Warn("tun.cpu_affinity entry not an integer; ignoring affinity",
  360. "index", i, "value", e)
  361. return nil
  362. }
  363. if cpu < 0 {
  364. l.Warn("tun.cpu_affinity entry out of range; ignoring affinity",
  365. "index", i, "cpu", cpu)
  366. return nil
  367. }
  368. if len(allowed) > 0 && !slices.Contains(allowed, cpu) {
  369. l.Warn("tun.cpu_affinity entry not in allowed CPU set; ignoring affinity",
  370. "index", i, "cpu", cpu, "allowed", allowed)
  371. return nil
  372. }
  373. if slices.Contains(avoid, cpu) {
  374. l.Warn("tun.cpu_affinity entry is listed in tun.avoid_cpus; ignoring affinity",
  375. "index", i, "cpu", cpu)
  376. return nil
  377. }
  378. cpus = append(cpus, cpu)
  379. }
  380. if len(cpus) != routines {
  381. l.Warn("tun.cpu_affinity length doesn't match routines; queues will modulo-cycle through the list",
  382. "affinity_len", len(cpus), "routines", routines)
  383. }
  384. return cpus
  385. }
  386. // parseAvoidCPUs reads tun.avoid_cpus, a list of CPU IDs the tun readers must not be pinned to. IDs outside the
  387. // allowed set are accepted, since one config may serve differently shaped hosts. Like tun.cpu_affinity, an invalid
  388. // list is a warning and is ignored entirely, as is one covering every allowed CPU, which would leave nowhere to pin.
  389. func parseAvoidCPUs(c *config.C, l *slog.Logger) []int {
  390. raw := c.Get("tun.avoid_cpus")
  391. if raw == nil {
  392. return nil
  393. }
  394. values, ok := raw.([]any)
  395. if !ok {
  396. l.Warn("tun.avoid_cpus must be a list of integers; ignoring", "value", raw)
  397. return nil
  398. }
  399. cpus := make([]int, 0, len(values))
  400. for i, value := range values {
  401. cpu, ok := value.(int)
  402. if !ok || cpu < 0 {
  403. l.Warn("tun.avoid_cpus entry not a non-negative integer; ignoring avoid_cpus", "index", i, "value", value)
  404. return nil
  405. }
  406. cpus = append(cpus, cpu)
  407. }
  408. if allowed, err := util.AllowedCPUs(); err == nil && len(allowed) > 0 &&
  409. !slices.ContainsFunc(allowed, func(cpu int) bool { return !slices.Contains(cpus, cpu) }) {
  410. l.Warn("tun.avoid_cpus covers every allowed CPU; ignoring avoid_cpus", "cpus", cpus, "allowed", allowed)
  411. return nil
  412. }
  413. return cpus
  414. }
  415. func moduleVersion() string {
  416. info, ok := debug.ReadBuildInfo()
  417. if !ok {
  418. return ""
  419. }
  420. for _, dep := range info.Deps {
  421. if dep.Path == "github.com/slackhq/nebula" {
  422. return strings.TrimPrefix(dep.Version, "v")
  423. }
  424. }
  425. return ""
  426. }