main.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. package nebula
  2. import (
  3. "context"
  4. "fmt"
  5. "log/slog"
  6. "math"
  7. "net"
  8. "net/netip"
  9. "os"
  10. "runtime/debug"
  11. "slices"
  12. "strings"
  13. "time"
  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. // Automatically cancel the context if Main returns an error, to signal all created goroutines to quit.
  31. defer func() {
  32. if reterr != nil {
  33. cancel()
  34. }
  35. }()
  36. if buildVersion == "" {
  37. buildVersion = moduleVersion()
  38. }
  39. // Debug builds (-tags debug) serve pprof on :6060; a no-op otherwise.
  40. startPprofServer(ctx, l)
  41. // Print the config if in test, the exit comes later
  42. if configTest {
  43. b, err := yaml.Marshal(c.Settings)
  44. if err != nil {
  45. return nil, err
  46. }
  47. // Print the final config
  48. l.Info(string(b))
  49. }
  50. pki, err := NewPKIFromConfig(l, c)
  51. if err != nil {
  52. return nil, util.ContextualizeIfNeeded("Failed to load PKI from config", err)
  53. }
  54. fw, err := NewFirewallFromConfig(l, pki.getCertState(), c)
  55. if err != nil {
  56. return nil, util.ContextualizeIfNeeded("Error while loading firewall rules", err)
  57. }
  58. l.Info("Firewall started", "firewallHashes", fw.GetRuleHashes())
  59. ssh, err := sshd.NewSSHServer(ctx, l.With("subsystem", "sshd"))
  60. if err != nil {
  61. return nil, util.ContextualizeIfNeeded("Error while creating SSH server", err)
  62. }
  63. wireSSHReload(l, ssh, c)
  64. var sshStart func()
  65. if c.GetBool("sshd.enabled", false) {
  66. sshStart, err = configSSH(l, ssh, c)
  67. if err != nil {
  68. l.Warn("Failed to configure sshd, ssh debugging will not be available", "error", err)
  69. sshStart = nil
  70. }
  71. }
  72. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  73. // All non system modifying configuration consumption should live above this line
  74. // tun config, listeners, anything modifying the computer should be below
  75. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  76. var routines int
  77. // If `routines` is set, use that and ignore the specific values
  78. if routines = c.GetInt("routines", 0); routines != 0 {
  79. if routines < 1 {
  80. routines = 1
  81. }
  82. } else {
  83. // deprecated and undocumented
  84. tunQueues := c.GetInt("tun.routines", 1)
  85. udpQueues := c.GetInt("listen.routines", 1)
  86. routines = max(tunQueues, udpQueues)
  87. if routines != 1 {
  88. l.Warn("Setting tun.routines and listen.routines is deprecated. Use `routines` instead", "routines", routines)
  89. }
  90. }
  91. if routines > maxRoutines {
  92. l.Warn("Using multiple routines", "routines", maxRoutines, "clamped", true, "requestedRoutines", routines)
  93. routines = maxRoutines
  94. } else if routines > 1 {
  95. l.Info("Using multiple routines", "routines", routines)
  96. }
  97. // EXPERIMENTAL
  98. // Intentionally not documented yet while we do more testing and determine
  99. // a good default value.
  100. conntrackCacheTimeout := c.GetDuration("firewall.conntrack.routine_cache_timeout", 0)
  101. if routines > 1 && !c.IsSet("firewall.conntrack.routine_cache_timeout") {
  102. // Use a different default if we are running with multiple routines
  103. conntrackCacheTimeout = 1 * time.Second
  104. }
  105. if conntrackCacheTimeout > 0 {
  106. l.Info("Using routine-local conntrack cache", "duration", conntrackCacheTimeout)
  107. }
  108. var tun overlay.Device
  109. if !configTest {
  110. c.CatchHUP(ctx)
  111. if deviceFactory == nil {
  112. deviceFactory = overlay.NewDeviceFromConfig
  113. }
  114. tun, err = deviceFactory(c, l, pki.getCertState().myVpnNetworks, routines)
  115. if err != nil {
  116. return nil, util.ContextualizeIfNeeded("Failed to get a tun/tap device", err)
  117. }
  118. defer func() {
  119. if reterr != nil {
  120. tun.Close()
  121. }
  122. }()
  123. }
  124. // set up our UDP listener
  125. udpConns := make([]udp.Conn, routines)
  126. port := c.GetInt("listen.port", 0)
  127. // Multiport lanes: bind `routines` consecutive UDP ports (listen.port+i)
  128. // instead of SO_REUSEPORT sharing one, and negotiate one extra tunnel per
  129. // routine with capable peers so each routine's traffic rides its own
  130. // underlay 5-tuple. Defaults on, degrading gracefully when preconditions
  131. // aren't met — managed deployments (dnclient) can't be hard-errored on
  132. // config they don't control.
  133. multiport := c.GetBool("multiport.enabled", true)
  134. if multiport && routines < 2 {
  135. l.Info("multiport disabled: requires routines > 1")
  136. multiport = false
  137. }
  138. if multiport && port != 0 && port+routines-1 > math.MaxUint16 {
  139. l.Warn("multiport disabled: would bind ports beyond 65535", "listen.port", port, "routines", routines)
  140. multiport = false
  141. }
  142. // Callers get no handle to these until the Control is returned, release them on any error.
  143. defer func() {
  144. if reterr != nil {
  145. for _, u := range udpConns {
  146. if u != nil {
  147. _ = u.Close()
  148. }
  149. }
  150. }
  151. }()
  152. if !configTest {
  153. rawListenHost := c.GetString("listen.host", "0.0.0.0")
  154. var listenHost netip.Addr
  155. if rawListenHost == "[::]" {
  156. // Old guidance was to provide the literal `[::]` in `listen.host` but that won't resolve.
  157. listenHost = netip.IPv6Unspecified()
  158. } else {
  159. ips, err := net.DefaultResolver.LookupNetIP(context.Background(), "ip", rawListenHost)
  160. if err != nil {
  161. return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
  162. }
  163. if len(ips) == 0 {
  164. return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
  165. }
  166. listenHost = ips[0].Unmap()
  167. }
  168. batchSize := c.GetInt("listen.batch", 64)
  169. if batchSize < 1 {
  170. oldBatch := batchSize
  171. batchSize = 1
  172. l.Warn("listen.batch size is invalid", "provided", oldBatch, "overridden to", batchSize)
  173. }
  174. offloads := c.GetBool("listen.udp_offloads", false)
  175. // Every lane socket needs its own reader; a platform that can't run
  176. // multiple readers would silently strand sockets 1..n-1 as blackholes.
  177. // Probe capability before committing to per-port binds.
  178. if multiport {
  179. probe, err := udp.NewListener(l, udp.Settings{
  180. Listen: netip.AddrPortFrom(listenHost, 0),
  181. Batch: 1,
  182. })
  183. if err != nil {
  184. // We could not confirm support, so don't gamble a bound port range on it. The real bind below reports
  185. // the underlying error if it is not transient.
  186. l.Warn("multiport disabled: could not probe udp reader support", "error", err)
  187. multiport = false
  188. } else {
  189. if !probe.SupportsMultipleReaders() {
  190. l.Warn("multiport disabled: this platform does not support multiple udp readers")
  191. multiport = false
  192. }
  193. _ = probe.Close()
  194. }
  195. }
  196. // With a dynamic listen.port, multiport binds socket 0 dynamically and
  197. // then claims the next routines-1 ports above it; if that range turns
  198. // out to be partially occupied, re-roll with a fresh dynamic port.
  199. dynamic := port == 0
  200. var bindErr error
  201. for attempt := 0; attempt < 6; attempt++ {
  202. bindErr = nil
  203. for i := 0; i < routines; i++ {
  204. lPort := port
  205. if multiport {
  206. lPort = port + i
  207. }
  208. udpServer, err := udp.NewListener(l, udp.Settings{
  209. Listen: netip.AddrPortFrom(listenHost, uint16(lPort)),
  210. // Multiport gives every routine its own port, so SO_REUSEPORT sharing is neither needed nor wanted:
  211. // the destination port alone must decide which socket, and therefore which routine, sees a flow.
  212. Multi: routines > 1 && !multiport,
  213. Batch: batchSize,
  214. Offloads: offloads,
  215. })
  216. if err != nil {
  217. bindErr = util.NewContextualError("Failed to open udp listener", m{"queue": i}, err)
  218. break
  219. }
  220. udpServer.ReloadConfig(c)
  221. udpConns[i] = udpServer
  222. // If port is dynamic, discover it before the next pass through the for loop
  223. // This way all routines will use the same port correctly
  224. if port == 0 {
  225. uPort, err := udpServer.LocalAddr()
  226. if err != nil {
  227. return nil, util.NewContextualError("Failed to get listening port", nil, err)
  228. }
  229. port = int(uPort.Port())
  230. if multiport && port+routines-1 > math.MaxUint16 {
  231. bindErr = util.NewContextualError("multiport dynamic port too close to 65535", m{"port": port}, nil)
  232. break
  233. }
  234. }
  235. bound := port
  236. if multiport {
  237. bound = port + i
  238. }
  239. l.Info("listening", "addr", netip.AddrPortFrom(listenHost, uint16(bound)), "socket", i)
  240. }
  241. if bindErr == nil {
  242. break
  243. }
  244. if !(multiport && dynamic) {
  245. return nil, bindErr
  246. }
  247. for i := range udpConns {
  248. if udpConns[i] != nil {
  249. _ = udpConns[i].Close()
  250. udpConns[i] = nil
  251. }
  252. }
  253. port = 0
  254. l.Debug("multiport dynamic port range collided, retrying", "attempt", attempt+1)
  255. }
  256. if bindErr != nil {
  257. return nil, bindErr
  258. }
  259. }
  260. hostMap := NewHostMapFromConfig(l, c)
  261. punchy := NewPunchyFromConfig(l, c, udpConns[0])
  262. connManager := newConnectionManagerFromConfig(l, c, hostMap, punchy)
  263. lightHouse, err := NewLightHouseFromConfig(ctx, l, c, pki.getCertState(), udpConns[0], punchy)
  264. if err != nil {
  265. return nil, util.ContextualizeIfNeeded("Failed to initialize lighthouse handler", err)
  266. }
  267. var messageMetrics *MessageMetrics
  268. if c.GetBool("stats.message_metrics", false) {
  269. messageMetrics = newMessageMetrics()
  270. } else {
  271. messageMetrics = newMessageMetricsOnlyRecvError()
  272. }
  273. handshakeConfig := HandshakeConfig{
  274. tryInterval: c.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
  275. retries: int64(c.GetInt("handshakes.retries", DefaultHandshakeRetries)),
  276. triggerBuffer: c.GetInt("handshakes.trigger_buffer", DefaultHandshakeTriggerBuffer),
  277. messageMetrics: messageMetrics,
  278. }
  279. if multiport {
  280. lanes := c.GetInt("multiport.lanes", 0)
  281. if lanes <= 0 || lanes > routines {
  282. lanes = routines
  283. }
  284. handshakeConfig.laneCount = lanes
  285. handshakeConfig.lanePortCount = uint16(routines)
  286. handshakeConfig.laneBasePort = uint16(port)
  287. }
  288. handshakeManager := NewHandshakeManager(l, hostMap, lightHouse, udpConns[0], handshakeConfig)
  289. lightHouse.handshakeTrigger = handshakeManager.trigger
  290. ds, err := newDnsServerFromConfig(ctx, l, pki, hostMap, c)
  291. if err != nil {
  292. l.Warn("Failed to start DNS responder", "error", err)
  293. }
  294. pinThreads := c.GetBool("tun.pin_threads", true)
  295. cpuAffinity := parseCpuAffinity(c, l, routines)
  296. if pinThreads && routines > 1 && len(cpuAffinity) == 0 && !configTest {
  297. // The operator didn't choose pin CPUs, so pick a default set that
  298. // prefers performance cores and doesn't stack co-located instances
  299. // onto allowed[0].
  300. // key is used to seed the spreading of routines->cores.
  301. // use PID if you want to ensure many different Nebulas in VMs or containers land on different cores
  302. // use port if you want to always end up on the same cores, ideal for benchmarking.
  303. key := uint64(os.Getpid()) //default to PID
  304. pinKeyStr := strings.ToLower(c.GetString("tun.pin_threads_key", ""))
  305. switch pinKeyStr {
  306. case "":
  307. l.Debug("tun.pin_threads_key is empty, using PID")
  308. case "pid":
  309. l.Debug("tun.pin_threads_key is PID")
  310. case "port":
  311. if ap, err := udpConns[0].LocalAddr(); err == nil && ap.Port() != 0 {
  312. l.Info("tun.pin_threads_key is port number")
  313. key = uint64(ap.Port())
  314. } else {
  315. l.Warn("Failed to get a port number for tun.pin_threads_key, falling back to PID", "err", err)
  316. }
  317. default:
  318. l.Warn("tun.pin_threads_key is invalid, using PID")
  319. }
  320. cpuAffinity = cpupick.Default(routines, key, l)
  321. }
  322. ifConfig := &InterfaceConfig{
  323. HostMap: hostMap,
  324. Inside: tun,
  325. Outside: udpConns[0],
  326. pki: pki,
  327. Firewall: fw,
  328. DnsServer: ds,
  329. HandshakeManager: handshakeManager,
  330. connectionManager: connManager,
  331. lightHouse: lightHouse,
  332. tryPromoteEvery: c.GetUint32("counters.try_promote", defaultPromoteEvery),
  333. reQueryEvery: c.GetUint32("counters.requery_every_packets", defaultReQueryEvery),
  334. reQueryWait: c.GetDuration("timers.requery_wait_duration", defaultReQueryWait),
  335. DropLocalBroadcast: c.GetBool("tun.drop_local_broadcast", false),
  336. DropMulticast: c.GetBool("tun.drop_multicast", false),
  337. routines: routines,
  338. Multiport: multiport,
  339. LaneCount: handshakeConfig.laneCount,
  340. MessageMetrics: messageMetrics,
  341. version: buildVersion,
  342. relayManager: NewRelayManager(ctx, l, hostMap, c),
  343. punchy: punchy,
  344. ConntrackCacheTimeout: conntrackCacheTimeout,
  345. CpuAffinity: cpuAffinity,
  346. PinThreads: pinThreads,
  347. l: l,
  348. }
  349. var ifce *Interface
  350. if !configTest {
  351. ifce, err = NewInterface(ctx, ifConfig)
  352. if err != nil {
  353. return nil, fmt.Errorf("failed to initialize interface: %s", err)
  354. }
  355. ifce.writers = udpConns
  356. lightHouse.ifce = ifce
  357. ifce.RegisterConfigChangeCallbacks(c)
  358. ifce.reloadDisconnectInvalid(c)
  359. ifce.reloadSendRecvError(c)
  360. ifce.reloadAcceptRecvError(c)
  361. handshakeManager.f = ifce
  362. go handshakeManager.Run(ctx)
  363. punchy.Start(ctx, ifce, hostMap, lightHouse)
  364. }
  365. stats, err := newStatsServerFromConfig(ctx, l, c, buildVersion, configTest)
  366. if err != nil {
  367. return nil, util.ContextualizeIfNeeded("Failed to start stats emitter", err)
  368. }
  369. if configTest {
  370. return nil, nil
  371. }
  372. go ifce.emitStats(ctx, c.GetDuration("stats.interval", time.Second*10))
  373. attachCommands(l, c, ssh, ifce)
  374. networkChanges := udp.NewNetworkChangeMonitor(ctx, l, c)
  375. return &Control{
  376. state: StateReady,
  377. f: ifce,
  378. l: l,
  379. ctx: ctx,
  380. cancel: cancel,
  381. sshStart: sshStart,
  382. statsStart: stats.Start,
  383. dnsStart: ds.Start,
  384. lighthouseStart: lightHouse.StartUpdateWorker,
  385. networkChangeStart: networkChanges.Start,
  386. connectionManagerStart: connManager.Start,
  387. }, nil
  388. }
  389. // parseCpuAffinity reads `tun.cpu_affinity` from the config — a list of
  390. // integer CPU IDs, one per TUN reader goroutine. Empty / unset returns nil
  391. // (listenIn falls back to spreading queues across the allowed CPU set).
  392. // Length mismatch with `routines` is a warning, not an error: shorter lists
  393. // are modulo-cycled across queues, longer lists' tail is ignored. Invalid
  394. // entries (non-integer, or a CPU ID we're not allowed to run on) are also a
  395. // warning and disable the override entirely so we don't silently pin to the
  396. // wrong CPU. Entries are validated against the process's current affinity
  397. // mask (util.AllowedCPUs) rather than 0..NumCPU-1: under a cgroup cpuset or
  398. // taskset the runnable IDs are frequently not that contiguous range, and
  399. // pinning to an unrunnable ID always fails. If the allowed set can't be
  400. // determined we fall back to a plain non-negative check.
  401. func parseCpuAffinity(c *config.C, l *slog.Logger, routines int) []int {
  402. raw := c.Get("tun.cpu_affinity")
  403. if raw == nil {
  404. return nil
  405. }
  406. rv, ok := raw.([]any)
  407. if !ok {
  408. l.Warn("tun.cpu_affinity must be a list of integers; ignoring", "value", raw)
  409. return nil
  410. }
  411. // allowed is the set of CPU IDs we're actually permitted to run on. A nil
  412. // slice (unsupported platform or lookup error) means "can't tell", so we
  413. // only apply the weaker non-negative check in that case.
  414. allowed, err := util.AllowedCPUs()
  415. if err != nil {
  416. l.Warn("could not determine allowed CPUs; validating tun.cpu_affinity against non-negative only", "error", err)
  417. allowed = nil
  418. }
  419. cpus := make([]int, 0, len(rv))
  420. for i, e := range rv {
  421. var cpu int
  422. switch v := e.(type) {
  423. case int:
  424. cpu = v
  425. case int64:
  426. cpu = int(v)
  427. case float64:
  428. cpu = int(v)
  429. default:
  430. l.Warn("tun.cpu_affinity entry not an integer; ignoring affinity",
  431. "index", i, "value", e)
  432. return nil
  433. }
  434. if cpu < 0 {
  435. l.Warn("tun.cpu_affinity entry out of range; ignoring affinity",
  436. "index", i, "cpu", cpu)
  437. return nil
  438. }
  439. if len(allowed) > 0 && !slices.Contains(allowed, cpu) {
  440. l.Warn("tun.cpu_affinity entry not in allowed CPU set; ignoring affinity",
  441. "index", i, "cpu", cpu, "allowed", allowed)
  442. return nil
  443. }
  444. cpus = append(cpus, cpu)
  445. }
  446. if len(cpus) != routines {
  447. l.Warn("tun.cpu_affinity length doesn't match routines; queues will modulo-cycle through the list",
  448. "affinity_len", len(cpus), "routines", routines)
  449. }
  450. return cpus
  451. }
  452. func moduleVersion() string {
  453. info, ok := debug.ReadBuildInfo()
  454. if !ok {
  455. return ""
  456. }
  457. for _, dep := range info.Deps {
  458. if dep.Path == "github.com/slackhq/nebula" {
  459. return strings.TrimPrefix(dep.Version, "v")
  460. }
  461. }
  462. return ""
  463. }