main.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. var tun overlay.Device
  100. if !configTest {
  101. c.CatchHUP(ctx)
  102. if deviceFactory == nil {
  103. deviceFactory = overlay.NewDeviceFromConfig
  104. }
  105. tun, err = deviceFactory(c, l, pki.getCertState().myVpnNetworks, routines)
  106. if err != nil {
  107. return nil, util.ContextualizeIfNeeded("Failed to get a tun/tap device", err)
  108. }
  109. defer func() {
  110. if reterr != nil {
  111. tun.Close()
  112. }
  113. }()
  114. }
  115. // set up our UDP listener
  116. udpConns := make([]udp.Conn, routines)
  117. port := c.GetInt("listen.port", 0)
  118. // Callers get no handle to these until the Control is returned, release them on any error.
  119. defer func() {
  120. if reterr != nil {
  121. for _, u := range udpConns {
  122. if u != nil {
  123. _ = u.Close()
  124. }
  125. }
  126. }
  127. }()
  128. if !configTest {
  129. rawListenHost := c.GetString("listen.host", "0.0.0.0")
  130. var listenHost netip.Addr
  131. if rawListenHost == "[::]" {
  132. // Old guidance was to provide the literal `[::]` in `listen.host` but that won't resolve.
  133. listenHost = netip.IPv6Unspecified()
  134. } else {
  135. ips, err := net.DefaultResolver.LookupNetIP(context.Background(), "ip", rawListenHost)
  136. if err != nil {
  137. return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
  138. }
  139. if len(ips) == 0 {
  140. return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
  141. }
  142. listenHost = ips[0].Unmap()
  143. }
  144. for i := 0; i < routines; i++ {
  145. listen := netip.AddrPortFrom(listenHost, uint16(port))
  146. l.Info("listening", "addr", listen)
  147. batchSize := c.GetInt("listen.batch", 64)
  148. if batchSize < 1 {
  149. oldBatch := batchSize
  150. batchSize = 1
  151. l.Warn("listen.batch size is invalid", "provided", oldBatch, "overridden to", batchSize)
  152. }
  153. udpSettings := udp.Settings{
  154. Listen: listen,
  155. Multi: routines > 1,
  156. Batch: batchSize,
  157. Offloads: c.GetBool("listen.udp_offloads", false),
  158. }
  159. udpServer, err := udp.NewListener(l, udpSettings)
  160. if err != nil {
  161. return nil, util.NewContextualError("Failed to open udp listener", m{"queue": i}, err)
  162. }
  163. udpServer.ReloadConfig(c)
  164. udpConns[i] = udpServer
  165. // If port is dynamic, discover it before the next pass through the for loop
  166. // This way all routines will use the same port correctly
  167. if port == 0 {
  168. uPort, err := udpServer.LocalAddr()
  169. if err != nil {
  170. return nil, util.NewContextualError("Failed to get listening port", nil, err)
  171. }
  172. port = int(uPort.Port())
  173. }
  174. }
  175. }
  176. hostMap := NewHostMapFromConfig(l, c)
  177. punchy := NewPunchyFromConfig(l, c, udpConns[0])
  178. connManager := newConnectionManagerFromConfig(l, c, hostMap, punchy)
  179. lightHouse, err := NewLightHouseFromConfig(ctx, l, c, pki.getCertState(), udpConns[0], punchy)
  180. if err != nil {
  181. return nil, util.ContextualizeIfNeeded("Failed to initialize lighthouse handler", err)
  182. }
  183. var messageMetrics *MessageMetrics
  184. if c.GetBool("stats.message_metrics", false) {
  185. messageMetrics = newMessageMetrics()
  186. } else {
  187. messageMetrics = newMessageMetricsOnlyRecvError()
  188. }
  189. handshakeConfig := HandshakeConfig{
  190. tryInterval: c.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
  191. retries: int64(c.GetInt("handshakes.retries", DefaultHandshakeRetries)),
  192. triggerBuffer: c.GetInt("handshakes.trigger_buffer", DefaultHandshakeTriggerBuffer),
  193. messageMetrics: messageMetrics,
  194. }
  195. handshakeManager := NewHandshakeManager(l, hostMap, lightHouse, udpConns[0], handshakeConfig)
  196. lightHouse.handshakeTrigger = handshakeManager.trigger
  197. ds, err := newDnsServerFromConfig(ctx, l, pki, hostMap, c)
  198. if err != nil {
  199. l.Warn("Failed to start DNS responder", "error", err)
  200. }
  201. pinThreads := c.GetBool("tun.pin_threads", true)
  202. cpuAffinity := parseCpuAffinity(c, l, routines)
  203. if pinThreads && routines > 1 && len(cpuAffinity) == 0 && !configTest {
  204. // The operator didn't choose pin CPUs, so pick a default set that
  205. // prefers performance cores and doesn't stack co-located instances
  206. // onto allowed[0].
  207. // key is used to seed the spreading of routines->cores.
  208. // use PID if you want to ensure many different Nebulas in VMs or containers land on different cores
  209. // use port if you want to always end up on the same cores, ideal for benchmarking.
  210. key := uint64(os.Getpid()) //default to PID
  211. pinKeyStr := strings.ToLower(c.GetString("tun.pin_threads_key", ""))
  212. switch pinKeyStr {
  213. case "":
  214. l.Debug("tun.pin_threads_key is empty, using PID")
  215. case "pid":
  216. l.Debug("tun.pin_threads_key is PID")
  217. case "port":
  218. if ap, err := udpConns[0].LocalAddr(); err == nil && ap.Port() != 0 {
  219. l.Info("tun.pin_threads_key is port number")
  220. key = uint64(ap.Port())
  221. } else {
  222. l.Warn("Failed to get a port number for tun.pin_threads_key, falling back to PID", "err", err)
  223. }
  224. default:
  225. l.Warn("tun.pin_threads_key is invalid, using PID")
  226. }
  227. cpuAffinity = cpupick.Default(routines, key, l)
  228. }
  229. ifConfig := &InterfaceConfig{
  230. HostMap: hostMap,
  231. Inside: tun,
  232. Outside: udpConns[0],
  233. pki: pki,
  234. Firewall: fw,
  235. DnsServer: ds,
  236. HandshakeManager: handshakeManager,
  237. connectionManager: connManager,
  238. lightHouse: lightHouse,
  239. tryPromoteEvery: c.GetUint32("counters.try_promote", defaultPromoteEvery),
  240. reQueryEvery: c.GetUint32("counters.requery_every_packets", defaultReQueryEvery),
  241. reQueryWait: c.GetDuration("timers.requery_wait_duration", defaultReQueryWait),
  242. DropLocalBroadcast: c.GetBool("tun.drop_local_broadcast", false),
  243. DropMulticast: c.GetBool("tun.drop_multicast", false),
  244. routines: routines,
  245. MessageMetrics: messageMetrics,
  246. version: buildVersion,
  247. relayManager: NewRelayManager(ctx, l, hostMap, c),
  248. punchy: punchy,
  249. CpuAffinity: cpuAffinity,
  250. PinThreads: pinThreads,
  251. l: l,
  252. }
  253. var ifce *Interface
  254. if !configTest {
  255. ifce, err = NewInterface(ctx, ifConfig)
  256. if err != nil {
  257. return nil, fmt.Errorf("failed to initialize interface: %s", err)
  258. }
  259. ifce.writers = udpConns
  260. lightHouse.ifce = ifce
  261. ifce.RegisterConfigChangeCallbacks(c)
  262. ifce.reloadDisconnectInvalid(c)
  263. ifce.reloadSendRecvError(c)
  264. ifce.reloadAcceptRecvError(c)
  265. handshakeManager.f = ifce
  266. go handshakeManager.Run(ctx)
  267. go ifce.firewall.Conntrack.Run(ctx)
  268. punchy.Start(ctx, ifce, hostMap, lightHouse)
  269. }
  270. stats, err := newStatsServerFromConfig(ctx, l, c, buildVersion, configTest)
  271. if err != nil {
  272. return nil, util.ContextualizeIfNeeded("Failed to start stats emitter", err)
  273. }
  274. if configTest {
  275. return nil, nil
  276. }
  277. go ifce.emitStats(ctx, c.GetDuration("stats.interval", time.Second*10))
  278. attachCommands(l, c, ssh, ifce)
  279. networkChanges := udp.NewNetworkChangeMonitor(ctx, l, c)
  280. return &Control{
  281. state: StateReady,
  282. f: ifce,
  283. l: l,
  284. ctx: ctx,
  285. cancel: cancel,
  286. sshStart: sshStart,
  287. statsStart: stats.Start,
  288. dnsStart: ds.Start,
  289. lighthouseStart: lightHouse.StartUpdateWorker,
  290. networkChangeStart: networkChanges.Start,
  291. connectionManagerStart: connManager.Start,
  292. }, nil
  293. }
  294. // parseCpuAffinity reads `tun.cpu_affinity` from the config — a list of
  295. // integer CPU IDs, one per TUN reader goroutine. Empty / unset returns nil
  296. // (listenIn falls back to spreading queues across the allowed CPU set).
  297. // Length mismatch with `routines` is a warning, not an error: shorter lists
  298. // are modulo-cycled across queues, longer lists' tail is ignored. Invalid
  299. // entries (non-integer, or a CPU ID we're not allowed to run on) are also a
  300. // warning and disable the override entirely so we don't silently pin to the
  301. // wrong CPU. Entries are validated against the process's current affinity
  302. // mask (util.AllowedCPUs) rather than 0..NumCPU-1: under a cgroup cpuset or
  303. // taskset the runnable IDs are frequently not that contiguous range, and
  304. // pinning to an unrunnable ID always fails. If the allowed set can't be
  305. // determined we fall back to a plain non-negative check.
  306. func parseCpuAffinity(c *config.C, l *slog.Logger, routines int) []int {
  307. raw := c.Get("tun.cpu_affinity")
  308. if raw == nil {
  309. return nil
  310. }
  311. rv, ok := raw.([]any)
  312. if !ok {
  313. l.Warn("tun.cpu_affinity must be a list of integers; ignoring", "value", raw)
  314. return nil
  315. }
  316. // allowed is the set of CPU IDs we're actually permitted to run on. A nil
  317. // slice (unsupported platform or lookup error) means "can't tell", so we
  318. // only apply the weaker non-negative check in that case.
  319. allowed, err := util.AllowedCPUs()
  320. if err != nil {
  321. l.Warn("could not determine allowed CPUs; validating tun.cpu_affinity against non-negative only", "error", err)
  322. allowed = nil
  323. }
  324. cpus := make([]int, 0, len(rv))
  325. for i, e := range rv {
  326. var cpu int
  327. switch v := e.(type) {
  328. case int:
  329. cpu = v
  330. case int64:
  331. cpu = int(v)
  332. case float64:
  333. cpu = int(v)
  334. default:
  335. l.Warn("tun.cpu_affinity entry not an integer; ignoring affinity",
  336. "index", i, "value", e)
  337. return nil
  338. }
  339. if cpu < 0 {
  340. l.Warn("tun.cpu_affinity entry out of range; ignoring affinity",
  341. "index", i, "cpu", cpu)
  342. return nil
  343. }
  344. if len(allowed) > 0 && !slices.Contains(allowed, cpu) {
  345. l.Warn("tun.cpu_affinity entry not in allowed CPU set; ignoring affinity",
  346. "index", i, "cpu", cpu, "allowed", allowed)
  347. return nil
  348. }
  349. cpus = append(cpus, cpu)
  350. }
  351. if len(cpus) != routines {
  352. l.Warn("tun.cpu_affinity length doesn't match routines; queues will modulo-cycle through the list",
  353. "affinity_len", len(cpus), "routines", routines)
  354. }
  355. return cpus
  356. }
  357. func moduleVersion() string {
  358. info, ok := debug.ReadBuildInfo()
  359. if !ok {
  360. return ""
  361. }
  362. for _, dep := range info.Deps {
  363. if dep.Path == "github.com/slackhq/nebula" {
  364. return strings.TrimPrefix(dep.Version, "v")
  365. }
  366. }
  367. return ""
  368. }