main.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. // Automatically cancel the context if Main returns an error, to signal all created goroutines to quit.
  27. defer func() {
  28. if reterr != nil {
  29. cancel()
  30. }
  31. }()
  32. if buildVersion == "" {
  33. buildVersion = moduleVersion()
  34. }
  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. } else {
  77. // deprecated and undocumented
  78. tunQueues := c.GetInt("tun.routines", 1)
  79. udpQueues := c.GetInt("listen.routines", 1)
  80. routines = max(tunQueues, udpQueues)
  81. if routines != 1 {
  82. l.Warn("Setting tun.routines and listen.routines is deprecated. Use `routines` instead", "routines", routines)
  83. }
  84. }
  85. if routines > maxRoutines {
  86. l.Warn("Using multiple routines", "routines", maxRoutines, "clamped", true, "requestedRoutines", routines)
  87. routines = maxRoutines
  88. } else if routines > 1 {
  89. l.Info("Using multiple routines", "routines", routines)
  90. }
  91. // EXPERIMENTAL
  92. // Intentionally not documented yet while we do more testing and determine
  93. // a good default value.
  94. conntrackCacheTimeout := c.GetDuration("firewall.conntrack.routine_cache_timeout", 0)
  95. if routines > 1 && !c.IsSet("firewall.conntrack.routine_cache_timeout") {
  96. // Use a different default if we are running with multiple routines
  97. conntrackCacheTimeout = 1 * time.Second
  98. }
  99. if conntrackCacheTimeout > 0 {
  100. l.Info("Using routine-local conntrack cache", "duration", conntrackCacheTimeout)
  101. }
  102. var tun overlay.Device
  103. if !configTest {
  104. c.CatchHUP(ctx)
  105. if deviceFactory == nil {
  106. deviceFactory = overlay.NewDeviceFromConfig
  107. }
  108. tun, err = deviceFactory(c, l, pki.getCertState().myVpnNetworks, routines)
  109. if err != nil {
  110. return nil, util.ContextualizeIfNeeded("Failed to get a tun/tap device", err)
  111. }
  112. defer func() {
  113. if reterr != nil {
  114. tun.Close()
  115. }
  116. }()
  117. }
  118. // set up our UDP listener
  119. udpConns := make([]udp.Conn, routines)
  120. port := c.GetInt("listen.port", 0)
  121. // Callers get no handle to these until the Control is returned, release them on any error.
  122. defer func() {
  123. if reterr != nil {
  124. for _, u := range udpConns {
  125. if u != nil {
  126. _ = u.Close()
  127. }
  128. }
  129. }
  130. }()
  131. if !configTest {
  132. rawListenHost := c.GetString("listen.host", "0.0.0.0")
  133. var listenHost netip.Addr
  134. if rawListenHost == "[::]" {
  135. // Old guidance was to provide the literal `[::]` in `listen.host` but that won't resolve.
  136. listenHost = netip.IPv6Unspecified()
  137. } else {
  138. ips, err := net.DefaultResolver.LookupNetIP(context.Background(), "ip", rawListenHost)
  139. if err != nil {
  140. return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
  141. }
  142. if len(ips) == 0 {
  143. return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
  144. }
  145. listenHost = ips[0].Unmap()
  146. }
  147. for i := 0; i < routines; i++ {
  148. l.Info("listening", "addr", netip.AddrPortFrom(listenHost, uint16(port)))
  149. udpServer, err := udp.NewListener(l, listenHost, port, routines > 1, c.GetInt("listen.batch", 64))
  150. if err != nil {
  151. return nil, util.NewContextualError("Failed to open udp listener", m{"queue": i}, err)
  152. }
  153. udpServer.ReloadConfig(c)
  154. udpConns[i] = udpServer
  155. // If port is dynamic, discover it before the next pass through the for loop
  156. // This way all routines will use the same port correctly
  157. if port == 0 {
  158. uPort, err := udpServer.LocalAddr()
  159. if err != nil {
  160. return nil, util.NewContextualError("Failed to get listening port", nil, err)
  161. }
  162. port = int(uPort.Port())
  163. }
  164. }
  165. }
  166. hostMap := NewHostMapFromConfig(l, c)
  167. punchy := NewPunchyFromConfig(l, c, udpConns[0])
  168. connManager := newConnectionManagerFromConfig(l, c, hostMap, punchy)
  169. lightHouse, err := NewLightHouseFromConfig(ctx, l, c, pki.getCertState(), udpConns[0], punchy)
  170. if err != nil {
  171. return nil, util.ContextualizeIfNeeded("Failed to initialize lighthouse handler", err)
  172. }
  173. var messageMetrics *MessageMetrics
  174. if c.GetBool("stats.message_metrics", false) {
  175. messageMetrics = newMessageMetrics()
  176. } else {
  177. messageMetrics = newMessageMetricsOnlyRecvError()
  178. }
  179. handshakeConfig := HandshakeConfig{
  180. tryInterval: c.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
  181. retries: int64(c.GetInt("handshakes.retries", DefaultHandshakeRetries)),
  182. triggerBuffer: c.GetInt("handshakes.trigger_buffer", DefaultHandshakeTriggerBuffer),
  183. messageMetrics: messageMetrics,
  184. }
  185. handshakeManager := NewHandshakeManager(l, hostMap, lightHouse, udpConns[0], handshakeConfig)
  186. lightHouse.handshakeTrigger = handshakeManager.trigger
  187. ds, err := newDnsServerFromConfig(ctx, l, pki, hostMap, c)
  188. if err != nil {
  189. l.Warn("Failed to start DNS responder", "error", err)
  190. }
  191. ifConfig := &InterfaceConfig{
  192. HostMap: hostMap,
  193. Inside: tun,
  194. Outside: udpConns[0],
  195. pki: pki,
  196. Firewall: fw,
  197. DnsServer: ds,
  198. HandshakeManager: handshakeManager,
  199. connectionManager: connManager,
  200. lightHouse: lightHouse,
  201. tryPromoteEvery: c.GetUint32("counters.try_promote", defaultPromoteEvery),
  202. reQueryEvery: c.GetUint32("counters.requery_every_packets", defaultReQueryEvery),
  203. reQueryWait: c.GetDuration("timers.requery_wait_duration", defaultReQueryWait),
  204. DropLocalBroadcast: c.GetBool("tun.drop_local_broadcast", false),
  205. DropMulticast: c.GetBool("tun.drop_multicast", false),
  206. routines: routines,
  207. MessageMetrics: messageMetrics,
  208. version: buildVersion,
  209. relayManager: NewRelayManager(ctx, l, hostMap, c),
  210. punchy: punchy,
  211. ConntrackCacheTimeout: conntrackCacheTimeout,
  212. l: l,
  213. }
  214. var ifce *Interface
  215. if !configTest {
  216. ifce, err = NewInterface(ctx, ifConfig)
  217. if err != nil {
  218. return nil, fmt.Errorf("failed to initialize interface: %s", err)
  219. }
  220. ifce.writers = udpConns
  221. lightHouse.ifce = ifce
  222. ifce.RegisterConfigChangeCallbacks(c)
  223. ifce.reloadDisconnectInvalid(c)
  224. ifce.reloadSendRecvError(c)
  225. ifce.reloadAcceptRecvError(c)
  226. handshakeManager.f = ifce
  227. go handshakeManager.Run(ctx)
  228. punchy.Start(ctx, ifce, hostMap, lightHouse)
  229. }
  230. stats, err := newStatsServerFromConfig(ctx, l, c, buildVersion, configTest)
  231. if err != nil {
  232. return nil, util.ContextualizeIfNeeded("Failed to start stats emitter", err)
  233. }
  234. if configTest {
  235. return nil, nil
  236. }
  237. go ifce.emitStats(ctx, c.GetDuration("stats.interval", time.Second*10))
  238. attachCommands(l, c, ssh, ifce)
  239. networkChanges := udp.NewNetworkChangeMonitor(ctx, l, c)
  240. return &Control{
  241. state: StateReady,
  242. f: ifce,
  243. l: l,
  244. ctx: ctx,
  245. cancel: cancel,
  246. sshStart: sshStart,
  247. statsStart: stats.Start,
  248. dnsStart: ds.Start,
  249. lighthouseStart: lightHouse.StartUpdateWorker,
  250. networkChangeStart: networkChanges.Start,
  251. connectionManagerStart: connManager.Start,
  252. }, nil
  253. }
  254. func moduleVersion() string {
  255. info, ok := debug.ReadBuildInfo()
  256. if !ok {
  257. return ""
  258. }
  259. for _, dep := range info.Deps {
  260. if dep.Path == "github.com/slackhq/nebula" {
  261. return strings.TrimPrefix(dep.Version, "v")
  262. }
  263. }
  264. return ""
  265. }