main.go 14 KB

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