main.go 19 KB

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