1
0

main.go 14 KB

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