main.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. hostMap.established = newEstablishedRemotes(udpConns)
  189. punchy := NewPunchyFromConfig(l, c, udpConns[0])
  190. connManager := newConnectionManagerFromConfig(l, c, hostMap, punchy)
  191. lightHouse, err := NewLightHouseFromConfig(ctx, l, c, pki.getCertState(), udpConns[0], punchy)
  192. if err != nil {
  193. return nil, util.ContextualizeIfNeeded("Failed to initialize lighthouse handler", err)
  194. }
  195. var messageMetrics *MessageMetrics
  196. if c.GetBool("stats.message_metrics", false) {
  197. messageMetrics = newMessageMetrics()
  198. } else {
  199. messageMetrics = newMessageMetricsOnlyRecvError()
  200. }
  201. handshakeConfig := HandshakeConfig{
  202. tryInterval: c.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
  203. retries: int64(c.GetInt("handshakes.retries", DefaultHandshakeRetries)),
  204. triggerBuffer: c.GetInt("handshakes.trigger_buffer", DefaultHandshakeTriggerBuffer),
  205. messageMetrics: messageMetrics,
  206. }
  207. handshakeManager := NewHandshakeManager(l, hostMap, lightHouse, udpConns[0], handshakeConfig)
  208. lightHouse.handshakeTrigger = handshakeManager.trigger
  209. ds, err := newDnsServerFromConfig(ctx, l, pki, hostMap, c)
  210. if err != nil {
  211. l.Warn("Failed to start DNS responder", "error", err)
  212. }
  213. pinThreads := c.GetBool("tun.pin_threads", true)
  214. cpuAffinity := parseCpuAffinity(c, l, routines)
  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. l: l,
  265. }
  266. var ifce *Interface
  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. }
  282. stats, err := newStatsServerFromConfig(ctx, l, c, buildVersion, configTest)
  283. if err != nil {
  284. return nil, util.ContextualizeIfNeeded("Failed to start stats emitter", err)
  285. }
  286. if configTest {
  287. return nil, nil
  288. }
  289. go ifce.emitStats(ctx, c.GetDuration("stats.interval", time.Second*10))
  290. attachCommands(l, c, ssh, ifce)
  291. networkChanges := udp.NewNetworkChangeMonitor(ctx, l, c)
  292. return &Control{
  293. state: StateReady,
  294. f: ifce,
  295. l: l,
  296. ctx: ctx,
  297. cancel: cancel,
  298. sshStart: sshStart,
  299. statsStart: stats.Start,
  300. dnsStart: ds.Start,
  301. lighthouseStart: lightHouse.StartUpdateWorker,
  302. networkChangeStart: networkChanges.Start,
  303. connectionManagerStart: connManager.Start,
  304. }, nil
  305. }
  306. // parseCpuAffinity reads `tun.cpu_affinity` from the config — a list of
  307. // integer CPU IDs, one per TUN reader goroutine. Empty / unset returns nil
  308. // (listenIn falls back to spreading queues across the allowed CPU set).
  309. // Length mismatch with `routines` is a warning, not an error: shorter lists
  310. // are modulo-cycled across queues, longer lists' tail is ignored. Invalid
  311. // entries (non-integer, or a CPU ID we're not allowed to run on) are also a
  312. // warning and disable the override entirely so we don't silently pin to the
  313. // wrong CPU. Entries are validated against the process's current affinity
  314. // mask (util.AllowedCPUs) rather than 0..NumCPU-1: under a cgroup cpuset or
  315. // taskset the runnable IDs are frequently not that contiguous range, and
  316. // pinning to an unrunnable ID always fails. If the allowed set can't be
  317. // determined we fall back to a plain non-negative check.
  318. func parseCpuAffinity(c *config.C, l *slog.Logger, routines int) []int {
  319. raw := c.Get("tun.cpu_affinity")
  320. if raw == nil {
  321. return nil
  322. }
  323. rv, ok := raw.([]any)
  324. if !ok {
  325. l.Warn("tun.cpu_affinity must be a list of integers; ignoring", "value", raw)
  326. return nil
  327. }
  328. // allowed is the set of CPU IDs we're actually permitted to run on. A nil
  329. // slice (unsupported platform or lookup error) means "can't tell", so we
  330. // only apply the weaker non-negative check in that case.
  331. allowed, err := util.AllowedCPUs()
  332. if err != nil {
  333. l.Warn("could not determine allowed CPUs; validating tun.cpu_affinity against non-negative only", "error", err)
  334. allowed = nil
  335. }
  336. cpus := make([]int, 0, len(rv))
  337. for i, e := range rv {
  338. var cpu int
  339. switch v := e.(type) {
  340. case int:
  341. cpu = v
  342. case int64:
  343. cpu = int(v)
  344. case float64:
  345. cpu = int(v)
  346. default:
  347. l.Warn("tun.cpu_affinity entry not an integer; ignoring affinity",
  348. "index", i, "value", e)
  349. return nil
  350. }
  351. if cpu < 0 {
  352. l.Warn("tun.cpu_affinity entry out of range; ignoring affinity",
  353. "index", i, "cpu", cpu)
  354. return nil
  355. }
  356. if len(allowed) > 0 && !slices.Contains(allowed, cpu) {
  357. l.Warn("tun.cpu_affinity entry not in allowed CPU set; ignoring affinity",
  358. "index", i, "cpu", cpu, "allowed", allowed)
  359. return nil
  360. }
  361. cpus = append(cpus, cpu)
  362. }
  363. if len(cpus) != routines {
  364. l.Warn("tun.cpu_affinity length doesn't match routines; queues will modulo-cycle through the list",
  365. "affinity_len", len(cpus), "routines", routines)
  366. }
  367. return cpus
  368. }
  369. func moduleVersion() string {
  370. info, ok := debug.ReadBuildInfo()
  371. if !ok {
  372. return ""
  373. }
  374. for _, dep := range info.Deps {
  375. if dep.Path == "github.com/slackhq/nebula" {
  376. return strings.TrimPrefix(dep.Version, "v")
  377. }
  378. }
  379. return ""
  380. }