main.go 17 KB

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