main.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. package nebula
  2. import (
  3. "context"
  4. "encoding/binary"
  5. "errors"
  6. "fmt"
  7. "net"
  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, tunFd *int) (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.NewContextualError("Failed to configure the logger", nil, 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. caPool, err := loadCAFromConfig(l, c)
  50. if err != nil {
  51. //The errors coming out of loadCA are already nicely formatted
  52. return nil, util.NewContextualError("Failed to load ca from config", nil, err)
  53. }
  54. l.WithField("fingerprints", caPool.GetFingerprints()).Debug("Trusted CA fingerprints")
  55. cs, err := NewCertStateFromConfig(c)
  56. if err != nil {
  57. //The errors coming out of NewCertStateFromConfig are already nicely formatted
  58. return nil, util.NewContextualError("Failed to load certificate from config", nil, err)
  59. }
  60. l.WithField("cert", cs.certificate).Debug("Client nebula certificate")
  61. fw, err := NewFirewallFromConfig(l, cs.certificate, c)
  62. if err != nil {
  63. return nil, util.NewContextualError("Error while loading firewall rules", nil, err)
  64. }
  65. l.WithField("firewallHash", fw.GetRuleHash()).Info("Firewall started")
  66. // TODO: make sure mask is 4 bytes
  67. tunCidr := cs.certificate.Details.Ips[0]
  68. ssh, err := sshd.NewSSHServer(l.WithField("subsystem", "sshd"))
  69. wireSSHReload(l, ssh, c)
  70. var sshStart func()
  71. if c.GetBool("sshd.enabled", false) {
  72. sshStart, err = configSSH(l, ssh, c)
  73. if err != nil {
  74. return nil, util.NewContextualError("Error while configuring the sshd", nil, err)
  75. }
  76. }
  77. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  78. // All non system modifying configuration consumption should live above this line
  79. // tun config, listeners, anything modifying the computer should be below
  80. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  81. var routines int
  82. // If `routines` is set, use that and ignore the specific values
  83. if routines = c.GetInt("routines", 0); routines != 0 {
  84. if routines < 1 {
  85. routines = 1
  86. }
  87. if routines > 1 {
  88. l.WithField("routines", routines).Info("Using multiple routines")
  89. }
  90. } else {
  91. // deprecated and undocumented
  92. tunQueues := c.GetInt("tun.routines", 1)
  93. udpQueues := c.GetInt("listen.routines", 1)
  94. if tunQueues > udpQueues {
  95. routines = tunQueues
  96. } else {
  97. routines = udpQueues
  98. }
  99. if routines != 1 {
  100. l.WithField("routines", routines).Warn("Setting tun.routines and listen.routines is deprecated. Use `routines` instead")
  101. }
  102. }
  103. // EXPERIMENTAL
  104. // Intentionally not documented yet while we do more testing and determine
  105. // a good default value.
  106. conntrackCacheTimeout := c.GetDuration("firewall.conntrack.routine_cache_timeout", 0)
  107. if routines > 1 && !c.IsSet("firewall.conntrack.routine_cache_timeout") {
  108. // Use a different default if we are running with multiple routines
  109. conntrackCacheTimeout = 1 * time.Second
  110. }
  111. if conntrackCacheTimeout > 0 {
  112. l.WithField("duration", conntrackCacheTimeout).Info("Using routine-local conntrack cache")
  113. }
  114. var tun overlay.Device
  115. if !configTest {
  116. c.CatchHUP(ctx)
  117. tun, err = overlay.NewDeviceFromConfig(c, l, tunCidr, tunFd, routines)
  118. if err != nil {
  119. return nil, util.NewContextualError("Failed to get a tun/tap device", nil, err)
  120. }
  121. defer func() {
  122. if reterr != nil {
  123. tun.Close()
  124. }
  125. }()
  126. }
  127. // set up our UDP listener
  128. udpConns := make([]udp.Conn, routines)
  129. port := c.GetInt("listen.port", 0)
  130. if !configTest {
  131. rawListenHost := c.GetString("listen.host", "0.0.0.0")
  132. var listenHost *net.IPAddr
  133. if rawListenHost == "[::]" {
  134. // Old guidance was to provide the literal `[::]` in `listen.host` but that won't resolve.
  135. listenHost = &net.IPAddr{IP: net.IPv6zero}
  136. } else {
  137. listenHost, err = net.ResolveIPAddr("ip", rawListenHost)
  138. if err != nil {
  139. return nil, util.NewContextualError("Failed to resolve listen.host", nil, err)
  140. }
  141. }
  142. for i := 0; i < routines; i++ {
  143. udpServer, err := udp.NewListener(l, listenHost.IP, port, routines > 1, c.GetInt("listen.batch", 64))
  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. }
  150. }
  151. // Set up my internal host map
  152. var preferredRanges []*net.IPNet
  153. rawPreferredRanges := c.GetStringSlice("preferred_ranges", []string{})
  154. // First, check if 'preferred_ranges' is set and fallback to 'local_range'
  155. if len(rawPreferredRanges) > 0 {
  156. for _, rawPreferredRange := range rawPreferredRanges {
  157. _, preferredRange, err := net.ParseCIDR(rawPreferredRange)
  158. if err != nil {
  159. return nil, util.NewContextualError("Failed to parse preferred ranges", nil, err)
  160. }
  161. preferredRanges = append(preferredRanges, preferredRange)
  162. }
  163. }
  164. // local_range was superseded by preferred_ranges. If it is still present,
  165. // merge the local_range setting into preferred_ranges. We will probably
  166. // deprecate local_range and remove in the future.
  167. rawLocalRange := c.GetString("local_range", "")
  168. if rawLocalRange != "" {
  169. _, localRange, err := net.ParseCIDR(rawLocalRange)
  170. if err != nil {
  171. return nil, util.NewContextualError("Failed to parse local_range", nil, err)
  172. }
  173. // Check if the entry for local_range was already specified in
  174. // preferred_ranges. Don't put it into the slice twice if so.
  175. var found bool
  176. for _, r := range preferredRanges {
  177. if r.String() == localRange.String() {
  178. found = true
  179. break
  180. }
  181. }
  182. if !found {
  183. preferredRanges = append(preferredRanges, localRange)
  184. }
  185. }
  186. hostMap := NewHostMap(l, "main", tunCidr, preferredRanges)
  187. hostMap.metricsEnabled = c.GetBool("stats.message_metrics", false)
  188. l.
  189. WithField("network", hostMap.vpnCIDR.String()).
  190. WithField("preferredRanges", hostMap.preferredRanges).
  191. Info("Main HostMap created")
  192. /*
  193. config.SetDefault("promoter.interval", 10)
  194. go hostMap.Promoter(config.GetInt("promoter.interval"))
  195. */
  196. punchy := NewPunchyFromConfig(l, c)
  197. lightHouse, err := NewLightHouseFromConfig(ctx, l, c, tunCidr, udpConns[0], punchy)
  198. switch {
  199. case errors.As(err, &util.ContextualError{}):
  200. return nil, err
  201. case err != nil:
  202. return nil, util.NewContextualError("Failed to initialize lighthouse handler", nil, err)
  203. }
  204. var messageMetrics *MessageMetrics
  205. if c.GetBool("stats.message_metrics", false) {
  206. messageMetrics = newMessageMetrics()
  207. } else {
  208. messageMetrics = newMessageMetricsOnlyRecvError()
  209. }
  210. useRelays := c.GetBool("relay.use_relays", DefaultUseRelays) && !c.GetBool("relay.am_relay", false)
  211. handshakeConfig := HandshakeConfig{
  212. tryInterval: c.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
  213. retries: c.GetInt("handshakes.retries", DefaultHandshakeRetries),
  214. triggerBuffer: c.GetInt("handshakes.trigger_buffer", DefaultHandshakeTriggerBuffer),
  215. useRelays: useRelays,
  216. messageMetrics: messageMetrics,
  217. }
  218. handshakeManager := NewHandshakeManager(l, tunCidr, preferredRanges, hostMap, lightHouse, udpConns[0], handshakeConfig)
  219. lightHouse.handshakeTrigger = handshakeManager.trigger
  220. //TODO: These will be reused for psk
  221. //handshakeMACKey := config.GetString("handshake_mac.key", "")
  222. //handshakeAcceptedMACKeys := config.GetStringSlice("handshake_mac.accepted_keys", []string{})
  223. serveDns := false
  224. if c.GetBool("lighthouse.serve_dns", false) {
  225. if c.GetBool("lighthouse.am_lighthouse", false) {
  226. serveDns = true
  227. } else {
  228. l.Warn("DNS server refusing to run because this host is not a lighthouse.")
  229. }
  230. }
  231. checkInterval := c.GetInt("timers.connection_alive_interval", 5)
  232. pendingDeletionInterval := c.GetInt("timers.pending_deletion_interval", 10)
  233. ifConfig := &InterfaceConfig{
  234. HostMap: hostMap,
  235. Inside: tun,
  236. Outside: udpConns[0],
  237. certState: cs,
  238. Cipher: c.GetString("cipher", "aes"),
  239. Firewall: fw,
  240. ServeDns: serveDns,
  241. HandshakeManager: handshakeManager,
  242. lightHouse: lightHouse,
  243. checkInterval: time.Second * time.Duration(checkInterval),
  244. pendingDeletionInterval: time.Second * time.Duration(pendingDeletionInterval),
  245. DropLocalBroadcast: c.GetBool("tun.drop_local_broadcast", false),
  246. DropMulticast: c.GetBool("tun.drop_multicast", false),
  247. routines: routines,
  248. MessageMetrics: messageMetrics,
  249. version: buildVersion,
  250. caPool: caPool,
  251. disconnectInvalid: c.GetBool("pki.disconnect_invalid", false),
  252. relayManager: NewRelayManager(ctx, l, hostMap, c),
  253. punchy: punchy,
  254. ConntrackCacheTimeout: conntrackCacheTimeout,
  255. l: l,
  256. }
  257. switch ifConfig.Cipher {
  258. case "aes":
  259. noiseEndianness = binary.BigEndian
  260. case "chachapoly":
  261. noiseEndianness = binary.LittleEndian
  262. default:
  263. return nil, fmt.Errorf("unknown cipher: %v", ifConfig.Cipher)
  264. }
  265. var ifce *Interface
  266. if !configTest {
  267. ifce, err = NewInterface(ctx, ifConfig)
  268. if err != nil {
  269. return nil, fmt.Errorf("failed to initialize interface: %s", err)
  270. }
  271. // TODO: Better way to attach these, probably want a new interface in InterfaceConfig
  272. // I don't want to make this initial commit too far-reaching though
  273. ifce.writers = udpConns
  274. ifce.RegisterConfigChangeCallbacks(c)
  275. ifce.reloadSendRecvError(c)
  276. go handshakeManager.Run(ctx, ifce)
  277. go lightHouse.LhUpdateWorker(ctx, ifce)
  278. }
  279. httpListen := c.GetString("http.listen", "")
  280. if httpListen == "" {
  281. if httpListen = c.GetString("stats.listen", ""); httpListen != "" {
  282. l.Warn("http.listen is undef, falling back to stats.listen. stats.listen will be deprecated in a future release.")
  283. }
  284. }
  285. // TODO - stats third-party modules start uncancellable goroutines. Update those libs to accept
  286. // a context so that they can exit when the context is Done.
  287. statsHTTPHandler, err := startStats(l, c, httpListen, buildVersion, configTest)
  288. if err != nil {
  289. return nil, util.NewContextualError("Failed to start stats emitter", nil, err)
  290. }
  291. httpStart, err := startHttp(l, c, httpListen, statsHTTPHandler)
  292. if err != nil {
  293. return nil, util.NewContextualError("Failed to start http server", nil, err)
  294. }
  295. if configTest {
  296. return nil, nil
  297. }
  298. //TODO: check if we _should_ be emitting stats
  299. go ifce.emitStats(ctx, c.GetDuration("stats.interval", time.Second*10))
  300. attachCommands(l, c, ssh, hostMap, handshakeManager.pendingHostMap, lightHouse, ifce)
  301. // Start DNS server last to allow using the nebula IP as lighthouse.dns.host
  302. var dnsStart func()
  303. if lightHouse.amLighthouse && serveDns {
  304. l.Debugln("Starting dns server")
  305. dnsStart = dnsMain(l, hostMap, c)
  306. }
  307. return &Control{ifce, l, cancel, sshStart, httpStart, dnsStart}, nil
  308. }