main.go 11 KB

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