main.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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, 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. punchy := NewPunchyFromConfig(l, c)
  193. lightHouse, err := NewLightHouseFromConfig(ctx, l, c, tunCidr, udpConns[0], punchy)
  194. switch {
  195. case errors.As(err, &util.ContextualError{}):
  196. return nil, err
  197. case err != nil:
  198. return nil, util.NewContextualError("Failed to initialize lighthouse handler", nil, err)
  199. }
  200. var messageMetrics *MessageMetrics
  201. if c.GetBool("stats.message_metrics", false) {
  202. messageMetrics = newMessageMetrics()
  203. } else {
  204. messageMetrics = newMessageMetricsOnlyRecvError()
  205. }
  206. useRelays := c.GetBool("relay.use_relays", DefaultUseRelays) && !c.GetBool("relay.am_relay", false)
  207. handshakeConfig := HandshakeConfig{
  208. tryInterval: c.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
  209. retries: c.GetInt("handshakes.retries", DefaultHandshakeRetries),
  210. triggerBuffer: c.GetInt("handshakes.trigger_buffer", DefaultHandshakeTriggerBuffer),
  211. useRelays: useRelays,
  212. messageMetrics: messageMetrics,
  213. }
  214. handshakeManager := NewHandshakeManager(l, tunCidr, preferredRanges, hostMap, lightHouse, udpConns[0], handshakeConfig)
  215. lightHouse.handshakeTrigger = handshakeManager.trigger
  216. serveDns := false
  217. if c.GetBool("lighthouse.serve_dns", false) {
  218. if c.GetBool("lighthouse.am_lighthouse", false) {
  219. serveDns = true
  220. } else {
  221. l.Warn("DNS server refusing to run because this host is not a lighthouse.")
  222. }
  223. }
  224. checkInterval := c.GetInt("timers.connection_alive_interval", 5)
  225. pendingDeletionInterval := c.GetInt("timers.pending_deletion_interval", 10)
  226. ifConfig := &InterfaceConfig{
  227. HostMap: hostMap,
  228. Inside: tun,
  229. Outside: udpConns[0],
  230. certState: cs,
  231. Cipher: c.GetString("cipher", "aes"),
  232. Firewall: fw,
  233. ServeDns: serveDns,
  234. HandshakeManager: handshakeManager,
  235. lightHouse: lightHouse,
  236. checkInterval: time.Second * time.Duration(checkInterval),
  237. pendingDeletionInterval: time.Second * time.Duration(pendingDeletionInterval),
  238. DropLocalBroadcast: c.GetBool("tun.drop_local_broadcast", false),
  239. DropMulticast: c.GetBool("tun.drop_multicast", false),
  240. routines: routines,
  241. MessageMetrics: messageMetrics,
  242. version: buildVersion,
  243. caPool: caPool,
  244. disconnectInvalid: c.GetBool("pki.disconnect_invalid", false),
  245. relayManager: NewRelayManager(ctx, l, hostMap, c),
  246. punchy: punchy,
  247. ConntrackCacheTimeout: conntrackCacheTimeout,
  248. l: l,
  249. }
  250. switch ifConfig.Cipher {
  251. case "aes":
  252. noiseEndianness = binary.BigEndian
  253. case "chachapoly":
  254. noiseEndianness = binary.LittleEndian
  255. default:
  256. return nil, fmt.Errorf("unknown cipher: %v", ifConfig.Cipher)
  257. }
  258. var ifce *Interface
  259. if !configTest {
  260. ifce, err = NewInterface(ctx, ifConfig)
  261. if err != nil {
  262. return nil, fmt.Errorf("failed to initialize interface: %s", err)
  263. }
  264. // TODO: Better way to attach these, probably want a new interface in InterfaceConfig
  265. // I don't want to make this initial commit too far-reaching though
  266. ifce.writers = udpConns
  267. lightHouse.ifce = ifce
  268. ifce.RegisterConfigChangeCallbacks(c)
  269. ifce.reloadSendRecvError(c)
  270. go handshakeManager.Run(ctx, ifce)
  271. }
  272. // TODO - stats third-party modules start uncancellable goroutines. Update those libs to accept
  273. // a context so that they can exit when the context is Done.
  274. statsStart, err := startStats(l, c, buildVersion, configTest)
  275. if err != nil {
  276. return nil, util.NewContextualError("Failed to start stats emitter", nil, err)
  277. }
  278. if configTest {
  279. return nil, nil
  280. }
  281. //TODO: check if we _should_ be emitting stats
  282. go ifce.emitStats(ctx, c.GetDuration("stats.interval", time.Second*10))
  283. attachCommands(l, c, ssh, ifce)
  284. // Start DNS server last to allow using the nebula IP as lighthouse.dns.host
  285. var dnsStart func()
  286. if lightHouse.amLighthouse && serveDns {
  287. l.Debugln("Starting dns server")
  288. dnsStart = dnsMain(l, hostMap, c)
  289. }
  290. return &Control{
  291. ifce,
  292. l,
  293. cancel,
  294. sshStart,
  295. statsStart,
  296. dnsStart,
  297. lightHouse.StartUpdateWorker,
  298. }, nil
  299. }