main.go 9.7 KB

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