main.go 8.9 KB

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