main.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. package nebula
  2. import (
  3. "context"
  4. "fmt"
  5. "log/slog"
  6. "net"
  7. "net/netip"
  8. "runtime/debug"
  9. "strings"
  10. "time"
  11. "github.com/slackhq/nebula/config"
  12. "github.com/slackhq/nebula/noiseutil"
  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. // maxRoutines caps routines below the RejectHeadroom nonce gap so concurrent senders can't race the counter past wrap.
  21. const maxRoutines = 1 << 16
  22. // The reject headroom must exceed every sender that can be mid-reservation at once, about two per routine.
  23. const _ = noiseutil.RejectHeadroom - 4*maxRoutines
  24. func Main(c *config.C, configTest bool, buildVersion string, l *slog.Logger, deviceFactory overlay.DeviceFactory) (retcon *Control, reterr error) {
  25. ctx, cancel := context.WithCancel(context.Background())
  26. // The goroutines started below stop only when this context does, and only a caller holding the
  27. // Control can arrange that. Cancel whenever we are not handing one back, which covers an error
  28. // and a config test alike: a config test used to leave the lighthouse query worker, and a
  29. // hostname resolver per dns named static host, running for the life of the process.
  30. defer func() {
  31. if retcon == nil {
  32. cancel()
  33. }
  34. }()
  35. if buildVersion == "" {
  36. buildVersion = moduleVersion()
  37. }
  38. // Print the config if in test, the exit comes later
  39. if configTest {
  40. b, err := yaml.Marshal(c.Settings)
  41. if err != nil {
  42. return nil, err
  43. }
  44. // Print the final config
  45. l.Info(string(b))
  46. }
  47. pki, err := NewPKIFromConfig(l, c)
  48. if err != nil {
  49. return nil, util.ContextualizeIfNeeded("Failed to load PKI from config", err)
  50. }
  51. fw, err := NewFirewallFromConfig(l, pki.getCertState(), c)
  52. if err != nil {
  53. return nil, util.ContextualizeIfNeeded("Error while loading firewall rules", err)
  54. }
  55. l.Info("Firewall started", "firewallHashes", fw.GetRuleHashes())
  56. ssh, err := sshd.NewSSHServer(ctx, l.With("subsystem", "sshd"))
  57. if err != nil {
  58. return nil, util.ContextualizeIfNeeded("Error while creating SSH server", err)
  59. }
  60. wireSSHReload(l, ssh, c)
  61. var sshStart func()
  62. if c.GetBool("sshd.enabled", false) {
  63. sshStart, err = configSSH(l, ssh, c)
  64. if err != nil {
  65. l.Warn("Failed to configure sshd, ssh debugging will not be available", "error", err)
  66. sshStart = nil
  67. }
  68. }
  69. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  70. // All non system modifying configuration consumption should live above this line
  71. // tun config, listeners, anything modifying the computer should be below
  72. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  73. var routines int
  74. // If `routines` is set, use that and ignore the specific values
  75. if routines = c.GetInt("routines", 0); routines != 0 {
  76. if routines < 1 {
  77. routines = 1
  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. if routines > maxRoutines {
  89. l.Warn("Using multiple routines", "routines", maxRoutines, "clamped", true, "requestedRoutines", routines)
  90. routines = maxRoutines
  91. } else if routines > 1 {
  92. l.Info("Using multiple routines", "routines", routines)
  93. }
  94. // EXPERIMENTAL
  95. // Intentionally not documented yet while we do more testing and determine
  96. // a good default value.
  97. conntrackCacheTimeout := c.GetDuration("firewall.conntrack.routine_cache_timeout", 0)
  98. if routines > 1 && !c.IsSet("firewall.conntrack.routine_cache_timeout") {
  99. // Use a different default if we are running with multiple routines
  100. conntrackCacheTimeout = 1 * time.Second
  101. }
  102. if conntrackCacheTimeout > 0 {
  103. l.Info("Using routine-local conntrack cache", "duration", conntrackCacheTimeout)
  104. }
  105. var tun overlay.Device
  106. if !configTest {
  107. c.CatchHUP(ctx)
  108. if deviceFactory == nil {
  109. deviceFactory = overlay.NewDeviceFromConfig
  110. }
  111. tun, err = deviceFactory(c, l, pki.getCertState().myVpnNetworks, routines)
  112. if err != nil {
  113. return nil, util.ContextualizeIfNeeded("Failed to get a tun/tap device", err)
  114. }
  115. defer func() {
  116. if reterr != nil {
  117. tun.Close()
  118. }
  119. }()
  120. }
  121. // set up our UDP listener
  122. udpConns := make([]udp.Conn, routines)
  123. port := c.GetInt("listen.port", 0)
  124. // Callers get no handle to these until the Control is returned, release them on any error.
  125. defer func() {
  126. if reterr != nil {
  127. for _, u := range udpConns {
  128. if u != nil {
  129. _ = u.Close()
  130. }
  131. }
  132. }
  133. }()
  134. if !configTest {
  135. rawListenHost := c.GetString("listen.host", "0.0.0.0")
  136. var listenHost netip.Addr
  137. if rawListenHost == "[::]" {
  138. // Old guidance was to provide the literal `[::]` in `listen.host` but that won't resolve.
  139. listenHost = netip.IPv6Unspecified()
  140. } else {
  141. ips, err := net.DefaultResolver.LookupNetIP(context.Background(), "ip", rawListenHost)
  142. if err != nil {
  143. return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
  144. }
  145. if len(ips) == 0 {
  146. return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
  147. }
  148. listenHost = ips[0].Unmap()
  149. }
  150. for i := 0; i < routines; i++ {
  151. l.Info("listening", "addr", netip.AddrPortFrom(listenHost, uint16(port)))
  152. udpServer, err := udp.NewListener(l, listenHost, port, routines > 1, c.GetInt("listen.batch", 64))
  153. if err != nil {
  154. return nil, util.NewContextualError("Failed to open udp listener", m{"queue": i}, err)
  155. }
  156. udpServer.ReloadConfig(c)
  157. udpConns[i] = udpServer
  158. // If port is dynamic, discover it before the next pass through the for loop
  159. // This way all routines will use the same port correctly
  160. if port == 0 {
  161. uPort, err := udpServer.LocalAddr()
  162. if err != nil {
  163. return nil, util.NewContextualError("Failed to get listening port", nil, err)
  164. }
  165. port = int(uPort.Port())
  166. }
  167. }
  168. }
  169. hostMap := NewHostMapFromConfig(l, c)
  170. punchy := NewPunchyFromConfig(l, c, udpConns[0])
  171. connManager := newConnectionManagerFromConfig(l, c, hostMap, punchy)
  172. lightHouse, err := NewLightHouseFromConfig(ctx, l, c, pki.getCertState(), udpConns[0], punchy)
  173. if err != nil {
  174. return nil, util.ContextualizeIfNeeded("Failed to initialize lighthouse handler", err)
  175. }
  176. var messageMetrics *MessageMetrics
  177. if c.GetBool("stats.message_metrics", false) {
  178. messageMetrics = newMessageMetrics()
  179. } else {
  180. messageMetrics = newMessageMetricsOnlyRecvError()
  181. }
  182. handshakeConfig := HandshakeConfig{
  183. tryInterval: c.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
  184. retries: int64(c.GetInt("handshakes.retries", DefaultHandshakeRetries)),
  185. triggerBuffer: c.GetInt("handshakes.trigger_buffer", DefaultHandshakeTriggerBuffer),
  186. messageMetrics: messageMetrics,
  187. }
  188. handshakeManager := NewHandshakeManager(l, hostMap, lightHouse, udpConns[0], handshakeConfig)
  189. lightHouse.handshakeTrigger = handshakeManager.trigger
  190. ds, err := newDnsServerFromConfig(ctx, l, pki, hostMap, c)
  191. if err != nil {
  192. l.Warn("Failed to start DNS responder", "error", err)
  193. }
  194. ifConfig := &InterfaceConfig{
  195. HostMap: hostMap,
  196. Inside: tun,
  197. Outside: udpConns[0],
  198. pki: pki,
  199. Firewall: fw,
  200. DnsServer: ds,
  201. HandshakeManager: handshakeManager,
  202. connectionManager: connManager,
  203. lightHouse: lightHouse,
  204. tryPromoteEvery: c.GetUint32("counters.try_promote", defaultPromoteEvery),
  205. reQueryEvery: c.GetUint32("counters.requery_every_packets", defaultReQueryEvery),
  206. reQueryWait: c.GetDuration("timers.requery_wait_duration", defaultReQueryWait),
  207. DropLocalBroadcast: c.GetBool("tun.drop_local_broadcast", false),
  208. DropMulticast: c.GetBool("tun.drop_multicast", false),
  209. routines: routines,
  210. MessageMetrics: messageMetrics,
  211. version: buildVersion,
  212. relayManager: NewRelayManager(ctx, l, hostMap, c),
  213. punchy: punchy,
  214. ConntrackCacheTimeout: conntrackCacheTimeout,
  215. l: l,
  216. }
  217. var ifce *Interface
  218. if !configTest {
  219. ifce, err = NewInterface(ctx, ifConfig)
  220. if err != nil {
  221. return nil, fmt.Errorf("failed to initialize interface: %s", err)
  222. }
  223. ifce.writers = udpConns
  224. lightHouse.ifce = ifce
  225. ifce.RegisterConfigChangeCallbacks(c)
  226. ifce.reloadDisconnectInvalid(c)
  227. ifce.reloadSendRecvError(c)
  228. ifce.reloadAcceptRecvError(c)
  229. handshakeManager.f = ifce
  230. go handshakeManager.Run(ctx)
  231. punchy.Start(ctx, ifce, hostMap, lightHouse)
  232. }
  233. stats, err := newStatsServerFromConfig(ctx, l, c, buildVersion, configTest)
  234. if err != nil {
  235. return nil, util.ContextualizeIfNeeded("Failed to start stats emitter", err)
  236. }
  237. if configTest {
  238. return nil, nil
  239. }
  240. go ifce.emitStats(ctx, c.GetDuration("stats.interval", time.Second*10))
  241. attachCommands(l, c, ssh, ifce)
  242. networkChanges := udp.NewNetworkChangeMonitor(ctx, l, c)
  243. return &Control{
  244. state: StateReady,
  245. f: ifce,
  246. l: l,
  247. ctx: ctx,
  248. cancel: cancel,
  249. sshStart: sshStart,
  250. statsStart: stats.Start,
  251. dnsStart: ds.Start,
  252. lighthouseStart: lightHouse.StartUpdateWorker,
  253. networkChangeStart: networkChanges.Start,
  254. connectionManagerStart: connManager.Start,
  255. }, nil
  256. }
  257. func moduleVersion() string {
  258. info, ok := debug.ReadBuildInfo()
  259. if !ok {
  260. return ""
  261. }
  262. for _, dep := range info.Deps {
  263. if dep.Path == "github.com/slackhq/nebula" {
  264. return strings.TrimPrefix(dep.Version, "v")
  265. }
  266. }
  267. return ""
  268. }