main.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. for i := 0; i < routines; i++ {
  132. udpServer, err := udp.NewListener(l, c.GetString("listen.host", "0.0.0.0"), port, routines > 1, c.GetInt("listen.batch", 64))
  133. if err != nil {
  134. return nil, util.NewContextualError("Failed to open udp listener", m{"queue": i}, err)
  135. }
  136. udpServer.ReloadConfig(c)
  137. udpConns[i] = udpServer
  138. }
  139. }
  140. // Set up my internal host map
  141. var preferredRanges []*net.IPNet
  142. rawPreferredRanges := c.GetStringSlice("preferred_ranges", []string{})
  143. // First, check if 'preferred_ranges' is set and fallback to 'local_range'
  144. if len(rawPreferredRanges) > 0 {
  145. for _, rawPreferredRange := range rawPreferredRanges {
  146. _, preferredRange, err := net.ParseCIDR(rawPreferredRange)
  147. if err != nil {
  148. return nil, util.NewContextualError("Failed to parse preferred ranges", nil, err)
  149. }
  150. preferredRanges = append(preferredRanges, preferredRange)
  151. }
  152. }
  153. // local_range was superseded by preferred_ranges. If it is still present,
  154. // merge the local_range setting into preferred_ranges. We will probably
  155. // deprecate local_range and remove in the future.
  156. rawLocalRange := c.GetString("local_range", "")
  157. if rawLocalRange != "" {
  158. _, localRange, err := net.ParseCIDR(rawLocalRange)
  159. if err != nil {
  160. return nil, util.NewContextualError("Failed to parse local_range", nil, err)
  161. }
  162. // Check if the entry for local_range was already specified in
  163. // preferred_ranges. Don't put it into the slice twice if so.
  164. var found bool
  165. for _, r := range preferredRanges {
  166. if r.String() == localRange.String() {
  167. found = true
  168. break
  169. }
  170. }
  171. if !found {
  172. preferredRanges = append(preferredRanges, localRange)
  173. }
  174. }
  175. hostMap := NewHostMap(l, "main", tunCidr, preferredRanges)
  176. hostMap.metricsEnabled = c.GetBool("stats.message_metrics", false)
  177. l.WithField("network", hostMap.vpnCIDR).WithField("preferredRanges", hostMap.preferredRanges).Info("Main HostMap created")
  178. /*
  179. config.SetDefault("promoter.interval", 10)
  180. go hostMap.Promoter(config.GetInt("promoter.interval"))
  181. */
  182. punchy := NewPunchyFromConfig(l, c)
  183. if punchy.GetPunch() && !configTest {
  184. l.Info("UDP hole punching enabled")
  185. go hostMap.Punchy(ctx, udpConns[0])
  186. }
  187. lightHouse, err := NewLightHouseFromConfig(l, c, tunCidr, udpConns[0], punchy)
  188. switch {
  189. case errors.As(err, &util.ContextualError{}):
  190. return nil, err
  191. case err != nil:
  192. return nil, util.NewContextualError("Failed to initialize lighthouse handler", nil, err)
  193. }
  194. var messageMetrics *MessageMetrics
  195. if c.GetBool("stats.message_metrics", false) {
  196. messageMetrics = newMessageMetrics()
  197. } else {
  198. messageMetrics = newMessageMetricsOnlyRecvError()
  199. }
  200. useRelays := c.GetBool("relay.use_relays", DefaultUseRelays) && !c.GetBool("relay.am_relay", false)
  201. handshakeConfig := HandshakeConfig{
  202. tryInterval: c.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
  203. retries: c.GetInt("handshakes.retries", DefaultHandshakeRetries),
  204. triggerBuffer: c.GetInt("handshakes.trigger_buffer", DefaultHandshakeTriggerBuffer),
  205. useRelays: useRelays,
  206. messageMetrics: messageMetrics,
  207. }
  208. handshakeManager := NewHandshakeManager(l, tunCidr, preferredRanges, hostMap, lightHouse, udpConns[0], handshakeConfig)
  209. lightHouse.handshakeTrigger = handshakeManager.trigger
  210. //TODO: These will be reused for psk
  211. //handshakeMACKey := config.GetString("handshake_mac.key", "")
  212. //handshakeAcceptedMACKeys := config.GetStringSlice("handshake_mac.accepted_keys", []string{})
  213. serveDns := false
  214. if c.GetBool("lighthouse.serve_dns", false) {
  215. if c.GetBool("lighthouse.am_lighthouse", false) {
  216. serveDns = true
  217. } else {
  218. l.Warn("DNS server refusing to run because this host is not a lighthouse.")
  219. }
  220. }
  221. checkInterval := c.GetInt("timers.connection_alive_interval", 5)
  222. pendingDeletionInterval := c.GetInt("timers.pending_deletion_interval", 10)
  223. ifConfig := &InterfaceConfig{
  224. HostMap: hostMap,
  225. Inside: tun,
  226. Outside: udpConns[0],
  227. certState: cs,
  228. Cipher: c.GetString("cipher", "aes"),
  229. Firewall: fw,
  230. ServeDns: serveDns,
  231. HandshakeManager: handshakeManager,
  232. lightHouse: lightHouse,
  233. checkInterval: checkInterval,
  234. pendingDeletionInterval: pendingDeletionInterval,
  235. DropLocalBroadcast: c.GetBool("tun.drop_local_broadcast", false),
  236. DropMulticast: c.GetBool("tun.drop_multicast", false),
  237. routines: routines,
  238. MessageMetrics: messageMetrics,
  239. version: buildVersion,
  240. caPool: caPool,
  241. disconnectInvalid: c.GetBool("pki.disconnect_invalid", false),
  242. relayManager: NewRelayManager(ctx, l, hostMap, c),
  243. ConntrackCacheTimeout: conntrackCacheTimeout,
  244. l: l,
  245. }
  246. switch ifConfig.Cipher {
  247. case "aes":
  248. noiseEndianness = binary.BigEndian
  249. case "chachapoly":
  250. noiseEndianness = binary.LittleEndian
  251. default:
  252. return nil, fmt.Errorf("unknown cipher: %v", ifConfig.Cipher)
  253. }
  254. var ifce *Interface
  255. if !configTest {
  256. ifce, err = NewInterface(ctx, ifConfig)
  257. if err != nil {
  258. return nil, fmt.Errorf("failed to initialize interface: %s", err)
  259. }
  260. // TODO: Better way to attach these, probably want a new interface in InterfaceConfig
  261. // I don't want to make this initial commit too far-reaching though
  262. ifce.writers = udpConns
  263. ifce.RegisterConfigChangeCallbacks(c)
  264. ifce.reloadSendRecvError(c)
  265. go handshakeManager.Run(ctx, ifce)
  266. go lightHouse.LhUpdateWorker(ctx, ifce)
  267. }
  268. // TODO - stats third-party modules start uncancellable goroutines. Update those libs to accept
  269. // a context so that they can exit when the context is Done.
  270. statsStart, err := startStats(l, c, buildVersion, configTest)
  271. if err != nil {
  272. return nil, util.NewContextualError("Failed to start stats emitter", nil, err)
  273. }
  274. if configTest {
  275. return nil, nil
  276. }
  277. //TODO: check if we _should_ be emitting stats
  278. go ifce.emitStats(ctx, c.GetDuration("stats.interval", time.Second*10))
  279. attachCommands(l, ssh, hostMap, handshakeManager.pendingHostMap, lightHouse, ifce)
  280. // Start DNS server last to allow using the nebula IP as lighthouse.dns.host
  281. var dnsStart func()
  282. if lightHouse.amLighthouse && serveDns {
  283. l.Debugln("Starting dns server")
  284. dnsStart = dnsMain(l, hostMap, c)
  285. }
  286. return &Control{ifce, l, cancel, sshStart, statsStart, dnsStart}, nil
  287. }