main.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. package nebula
  2. import (
  3. "context"
  4. "fmt"
  5. "net"
  6. "net/netip"
  7. "time"
  8. "github.com/sirupsen/logrus"
  9. "github.com/slackhq/nebula/config"
  10. "github.com/slackhq/nebula/overlay"
  11. "github.com/slackhq/nebula/sshd"
  12. "github.com/slackhq/nebula/udp"
  13. "github.com/slackhq/nebula/util"
  14. "gopkg.in/yaml.v3"
  15. )
  16. type m = map[string]any
  17. func Main(c *config.C, configTest bool, buildVersion string, logger *logrus.Logger, deviceFactory overlay.DeviceFactory) (retcon *Control, reterr error) {
  18. ctx, cancel := context.WithCancel(context.Background())
  19. // Automatically cancel the context if Main returns an error, to signal all created goroutines to quit.
  20. defer func() {
  21. if reterr != nil {
  22. cancel()
  23. }
  24. }()
  25. l := logger
  26. l.Formatter = &logrus.TextFormatter{
  27. FullTimestamp: true,
  28. }
  29. // Print the config if in test, the exit comes later
  30. if configTest {
  31. b, err := yaml.Marshal(c.Settings)
  32. if err != nil {
  33. return nil, err
  34. }
  35. // Print the final config
  36. l.Println(string(b))
  37. }
  38. err := configLogger(l, c)
  39. if err != nil {
  40. return nil, util.ContextualizeIfNeeded("Failed to configure the logger", err)
  41. }
  42. c.RegisterReloadCallback(func(c *config.C) {
  43. err := configLogger(l, c)
  44. if err != nil {
  45. l.WithError(err).Error("Failed to configure the logger")
  46. }
  47. })
  48. pki, err := NewPKIFromConfig(l, c)
  49. if err != nil {
  50. return nil, util.ContextualizeIfNeeded("Failed to load PKI from config", err)
  51. }
  52. fw, err := NewFirewallFromConfig(l, pki.getCertState(), c)
  53. if err != nil {
  54. return nil, util.ContextualizeIfNeeded("Error while loading firewall rules", err)
  55. }
  56. l.WithField("firewallHashes", fw.GetRuleHashes()).Info("Firewall started")
  57. ssh, err := sshd.NewSSHServer(l.WithField("subsystem", "sshd"))
  58. if err != nil {
  59. return nil, util.ContextualizeIfNeeded("Error while creating SSH server", err)
  60. }
  61. wireSSHReload(l, ssh, c)
  62. var sshStart func()
  63. if c.GetBool("sshd.enabled", false) {
  64. sshStart, err = configSSH(l, ssh, c)
  65. if err != nil {
  66. return nil, util.ContextualizeIfNeeded("Error while configuring the sshd", err)
  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. if routines > 1 {
  80. l.WithField("routines", routines).Info("Using multiple routines")
  81. }
  82. } else {
  83. // deprecated and undocumented
  84. tunQueues := c.GetInt("tun.routines", 1)
  85. udpQueues := c.GetInt("listen.routines", 1)
  86. if tunQueues > udpQueues {
  87. routines = tunQueues
  88. } else {
  89. routines = udpQueues
  90. }
  91. if routines != 1 {
  92. l.WithField("routines", routines).Warn("Setting tun.routines and listen.routines is deprecated. Use `routines` instead")
  93. }
  94. }
  95. // EXPERIMENTAL
  96. // Intentionally not documented yet while we do more testing and determine
  97. // a good default value.
  98. conntrackCacheTimeout := c.GetDuration("firewall.conntrack.routine_cache_timeout", 0)
  99. if routines > 1 && !c.IsSet("firewall.conntrack.routine_cache_timeout") {
  100. // Use a different default if we are running with multiple routines
  101. conntrackCacheTimeout = 1 * time.Second
  102. }
  103. if conntrackCacheTimeout > 0 {
  104. l.WithField("duration", conntrackCacheTimeout).Info("Using routine-local conntrack cache")
  105. }
  106. var tun overlay.Device
  107. if !configTest {
  108. c.CatchHUP(ctx)
  109. if deviceFactory == nil {
  110. deviceFactory = overlay.NewDeviceFromConfig
  111. }
  112. tun, err = deviceFactory(c, l, pki.getCertState().myVpnNetworks, routines)
  113. if err != nil {
  114. return nil, util.ContextualizeIfNeeded("Failed to get a tun/tap device", err)
  115. }
  116. defer func() {
  117. if reterr != nil {
  118. tun.Close()
  119. }
  120. }()
  121. }
  122. // set up our UDP listener
  123. udpConns := make([]udp.Conn, routines)
  124. port := c.GetInt("listen.port", 0)
  125. if !configTest {
  126. rawListenHost := c.GetString("listen.host", "0.0.0.0")
  127. var listenHost netip.Addr
  128. if rawListenHost == "[::]" {
  129. // Old guidance was to provide the literal `[::]` in `listen.host` but that won't resolve.
  130. listenHost = netip.IPv6Unspecified()
  131. } else {
  132. ips, err := net.DefaultResolver.LookupNetIP(context.Background(), "ip", rawListenHost)
  133. if err != nil {
  134. return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
  135. }
  136. if len(ips) == 0 {
  137. return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
  138. }
  139. listenHost = ips[0].Unmap()
  140. }
  141. for i := 0; i < routines; i++ {
  142. l.Infof("listening on %v", netip.AddrPortFrom(listenHost, uint16(port)))
  143. udpServer, err := udp.NewListener(l, listenHost, port, routines > 1, c.GetInt("listen.batch", 128))
  144. if err != nil {
  145. return nil, util.NewContextualError("Failed to open udp listener", m{"queue": i}, err)
  146. }
  147. udpServer.ReloadConfig(c)
  148. udpConns[i] = udpServer
  149. // If port is dynamic, discover it before the next pass through the for loop
  150. // This way all routines will use the same port correctly
  151. if port == 0 {
  152. uPort, err := udpServer.LocalAddr()
  153. if err != nil {
  154. return nil, util.NewContextualError("Failed to get listening port", nil, err)
  155. }
  156. port = int(uPort.Port())
  157. }
  158. }
  159. }
  160. hostMap := NewHostMapFromConfig(l, c)
  161. punchy := NewPunchyFromConfig(l, c)
  162. connManager := newConnectionManagerFromConfig(l, c, hostMap, punchy)
  163. lightHouse, err := NewLightHouseFromConfig(ctx, l, c, pki.getCertState(), udpConns[0], punchy)
  164. if err != nil {
  165. return nil, util.ContextualizeIfNeeded("Failed to initialize lighthouse handler", err)
  166. }
  167. var messageMetrics *MessageMetrics
  168. if c.GetBool("stats.message_metrics", false) {
  169. messageMetrics = newMessageMetrics()
  170. } else {
  171. messageMetrics = newMessageMetricsOnlyRecvError()
  172. }
  173. useRelays := c.GetBool("relay.use_relays", DefaultUseRelays) && !c.GetBool("relay.am_relay", false)
  174. handshakeConfig := HandshakeConfig{
  175. tryInterval: c.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
  176. retries: int64(c.GetInt("handshakes.retries", DefaultHandshakeRetries)),
  177. triggerBuffer: c.GetInt("handshakes.trigger_buffer", DefaultHandshakeTriggerBuffer),
  178. useRelays: useRelays,
  179. messageMetrics: messageMetrics,
  180. }
  181. handshakeManager := NewHandshakeManager(l, hostMap, lightHouse, udpConns[0], handshakeConfig)
  182. lightHouse.handshakeTrigger = handshakeManager.trigger
  183. serveDns := false
  184. if c.GetBool("lighthouse.serve_dns", false) {
  185. if c.GetBool("lighthouse.am_lighthouse", false) {
  186. serveDns = true
  187. } else {
  188. l.Warn("DNS server refusing to run because this host is not a lighthouse.")
  189. }
  190. }
  191. batchCfg := BatchConfig{
  192. InboundBatchSize: c.GetInt("batch.inbound_size", inboundBatchSizeDefault),
  193. OutboundBatchSize: c.GetInt("batch.outbound_size", outboundBatchSizeDefault),
  194. FlushInterval: c.GetDuration("batch.flush_interval", batchFlushIntervalDefault),
  195. MaxOutstandingPerChan: c.GetInt("batch.max_outstanding", maxOutstandingBatchesDefault),
  196. MaxPendingPackets: c.GetInt("batch.max_pending_packets", 0),
  197. MaxPendingBytes: c.GetInt("batch.max_pending_bytes", 0),
  198. MaxSendBuffersPerChan: c.GetInt("batch.max_send_buffers_per_routine", 0),
  199. }
  200. ifConfig := &InterfaceConfig{
  201. HostMap: hostMap,
  202. Inside: tun,
  203. Outside: udpConns[0],
  204. pki: pki,
  205. Firewall: fw,
  206. ServeDns: serveDns,
  207. HandshakeManager: handshakeManager,
  208. connectionManager: connManager,
  209. lightHouse: lightHouse,
  210. tryPromoteEvery: c.GetUint32("counters.try_promote", defaultPromoteEvery),
  211. reQueryEvery: c.GetUint32("counters.requery_every_packets", defaultReQueryEvery),
  212. reQueryWait: c.GetDuration("timers.requery_wait_duration", defaultReQueryWait),
  213. DropLocalBroadcast: c.GetBool("tun.drop_local_broadcast", false),
  214. DropMulticast: c.GetBool("tun.drop_multicast", false),
  215. routines: routines,
  216. MessageMetrics: messageMetrics,
  217. version: buildVersion,
  218. relayManager: NewRelayManager(ctx, l, hostMap, c),
  219. punchy: punchy,
  220. ConntrackCacheTimeout: conntrackCacheTimeout,
  221. BatchConfig: batchCfg,
  222. l: l,
  223. }
  224. var ifce *Interface
  225. if !configTest {
  226. ifce, err = NewInterface(ctx, ifConfig)
  227. if err != nil {
  228. return nil, fmt.Errorf("failed to initialize interface: %s", err)
  229. }
  230. ifce.writers = udpConns
  231. lightHouse.ifce = ifce
  232. ifce.RegisterConfigChangeCallbacks(c)
  233. ifce.reloadDisconnectInvalid(c)
  234. ifce.reloadSendRecvError(c)
  235. handshakeManager.f = ifce
  236. go handshakeManager.Run(ctx)
  237. }
  238. statsStart, err := startStats(l, c, buildVersion, configTest)
  239. if err != nil {
  240. return nil, util.ContextualizeIfNeeded("Failed to start stats emitter", err)
  241. }
  242. if configTest {
  243. return nil, nil
  244. }
  245. go ifce.emitStats(ctx, c.GetDuration("stats.interval", time.Second*10))
  246. attachCommands(l, c, ssh, ifce)
  247. // Start DNS server last to allow using the nebula IP as lighthouse.dns.host
  248. var dnsStart func()
  249. if lightHouse.amLighthouse && serveDns {
  250. l.Debugln("Starting dns server")
  251. dnsStart = dnsMain(l, pki.getCertState(), hostMap, c)
  252. }
  253. return &Control{
  254. f: ifce,
  255. l: l,
  256. ctx: ctx,
  257. cancel: cancel,
  258. sshStart: sshStart,
  259. statsStart: statsStart,
  260. dnsStart: dnsStart,
  261. lighthouseStart: lightHouse.StartUpdateWorker,
  262. connectionManagerStart: connManager.Start,
  263. }, nil
  264. }