main.go 14 KB

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