main.go 14 KB

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