main.go 10 KB

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