main.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. MessageMetrics: messageMetrics,
  195. version: buildVersion,
  196. relayManager: NewRelayManager(ctx, l, hostMap, c),
  197. punchy: punchy,
  198. ConntrackCacheTimeout: conntrackCacheTimeout,
  199. CpuAffinity: parseCpuAffinity(c, l, routines),
  200. l: l,
  201. }
  202. var ifce *Interface
  203. if !configTest {
  204. ifce, err = NewInterface(ctx, ifConfig)
  205. if err != nil {
  206. return nil, fmt.Errorf("failed to initialize interface: %s", err)
  207. }
  208. ifce.writers = udpConns
  209. lightHouse.ifce = ifce
  210. ifce.RegisterConfigChangeCallbacks(c)
  211. ifce.reloadDisconnectInvalid(c)
  212. ifce.reloadSendRecvError(c)
  213. ifce.reloadAcceptRecvError(c)
  214. ifce.reloadEcn(c)
  215. handshakeManager.f = ifce
  216. go handshakeManager.Run(ctx)
  217. punchy.Start(ctx, ifce, hostMap, lightHouse)
  218. }
  219. stats, err := newStatsServerFromConfig(ctx, l, c, buildVersion, configTest)
  220. if err != nil {
  221. return nil, util.ContextualizeIfNeeded("Failed to start stats emitter", err)
  222. }
  223. if configTest {
  224. return nil, nil
  225. }
  226. go ifce.emitStats(ctx, c.GetDuration("stats.interval", time.Second*10))
  227. attachCommands(l, c, ssh, ifce)
  228. return &Control{
  229. state: StateReady,
  230. f: ifce,
  231. l: l,
  232. ctx: ctx,
  233. cancel: cancel,
  234. sshStart: sshStart,
  235. statsStart: stats.Start,
  236. dnsStart: ds.Start,
  237. lighthouseStart: lightHouse.StartUpdateWorker,
  238. connectionManagerStart: connManager.Start,
  239. }, nil
  240. }
  241. // parseCpuAffinity reads `tun.cpu_affinity` from the config — a list of
  242. // integer CPU IDs, one per TUN reader goroutine. Empty / unset returns nil
  243. // (listenIn falls back to its default `i % NumCPU` pinning). Length
  244. // mismatch with `routines` is a warning, not an error: shorter lists are
  245. // modulo-cycled across queues, longer lists' tail is ignored. Invalid
  246. // entries (non-integer, out of range) are also a warning and disable the
  247. // override entirely so we don't silently pin to the wrong CPU.
  248. func parseCpuAffinity(c *config.C, l *slog.Logger, routines int) []int {
  249. raw := c.Get("tun.cpu_affinity")
  250. if raw == nil {
  251. return nil
  252. }
  253. rv, ok := raw.([]any)
  254. if !ok {
  255. l.Warn("tun.cpu_affinity must be a list of integers; ignoring", "value", raw)
  256. return nil
  257. }
  258. nCPU := runtime.NumCPU()
  259. cpus := make([]int, 0, len(rv))
  260. for i, e := range rv {
  261. var cpu int
  262. switch v := e.(type) {
  263. case int:
  264. cpu = v
  265. case int64:
  266. cpu = int(v)
  267. case float64:
  268. cpu = int(v)
  269. default:
  270. l.Warn("tun.cpu_affinity entry not an integer; ignoring affinity",
  271. "index", i, "value", e)
  272. return nil
  273. }
  274. if cpu < 0 || cpu >= nCPU {
  275. l.Warn("tun.cpu_affinity entry out of range; ignoring affinity",
  276. "index", i, "cpu", cpu, "num_cpu", nCPU)
  277. return nil
  278. }
  279. cpus = append(cpus, cpu)
  280. }
  281. if len(cpus) != routines {
  282. l.Warn("tun.cpu_affinity length doesn't match routines; queues will modulo-cycle through the list",
  283. "affinity_len", len(cpus), "routines", routines)
  284. }
  285. return cpus
  286. }
  287. func moduleVersion() string {
  288. info, ok := debug.ReadBuildInfo()
  289. if !ok {
  290. return ""
  291. }
  292. for _, dep := range info.Deps {
  293. if dep.Path == "github.com/slackhq/nebula" {
  294. return strings.TrimPrefix(dep.Version, "v")
  295. }
  296. }
  297. return ""
  298. }