main.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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.
  178. WithField("network", hostMap.vpnCIDR.String()).
  179. WithField("preferredRanges", hostMap.preferredRanges).
  180. Info("Main HostMap created")
  181. /*
  182. config.SetDefault("promoter.interval", 10)
  183. go hostMap.Promoter(config.GetInt("promoter.interval"))
  184. */
  185. punchy := NewPunchyFromConfig(l, c)
  186. lightHouse, err := NewLightHouseFromConfig(l, c, tunCidr, udpConns[0], punchy)
  187. switch {
  188. case errors.As(err, &util.ContextualError{}):
  189. return nil, err
  190. case err != nil:
  191. return nil, util.NewContextualError("Failed to initialize lighthouse handler", nil, err)
  192. }
  193. var messageMetrics *MessageMetrics
  194. if c.GetBool("stats.message_metrics", false) {
  195. messageMetrics = newMessageMetrics()
  196. } else {
  197. messageMetrics = newMessageMetricsOnlyRecvError()
  198. }
  199. useRelays := c.GetBool("relay.use_relays", DefaultUseRelays) && !c.GetBool("relay.am_relay", false)
  200. handshakeConfig := HandshakeConfig{
  201. tryInterval: c.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
  202. retries: c.GetInt("handshakes.retries", DefaultHandshakeRetries),
  203. triggerBuffer: c.GetInt("handshakes.trigger_buffer", DefaultHandshakeTriggerBuffer),
  204. useRelays: useRelays,
  205. messageMetrics: messageMetrics,
  206. }
  207. handshakeManager := NewHandshakeManager(l, tunCidr, preferredRanges, hostMap, lightHouse, udpConns[0], handshakeConfig)
  208. lightHouse.handshakeTrigger = handshakeManager.trigger
  209. //TODO: These will be reused for psk
  210. //handshakeMACKey := config.GetString("handshake_mac.key", "")
  211. //handshakeAcceptedMACKeys := config.GetStringSlice("handshake_mac.accepted_keys", []string{})
  212. serveDns := false
  213. if c.GetBool("lighthouse.serve_dns", false) {
  214. if c.GetBool("lighthouse.am_lighthouse", false) {
  215. serveDns = true
  216. } else {
  217. l.Warn("DNS server refusing to run because this host is not a lighthouse.")
  218. }
  219. }
  220. checkInterval := c.GetInt("timers.connection_alive_interval", 5)
  221. pendingDeletionInterval := c.GetInt("timers.pending_deletion_interval", 10)
  222. ifConfig := &InterfaceConfig{
  223. HostMap: hostMap,
  224. Inside: tun,
  225. Outside: udpConns[0],
  226. certState: cs,
  227. Cipher: c.GetString("cipher", "aes"),
  228. Firewall: fw,
  229. ServeDns: serveDns,
  230. HandshakeManager: handshakeManager,
  231. lightHouse: lightHouse,
  232. checkInterval: time.Second * time.Duration(checkInterval),
  233. pendingDeletionInterval: time.Second * time.Duration(pendingDeletionInterval),
  234. DropLocalBroadcast: c.GetBool("tun.drop_local_broadcast", false),
  235. DropMulticast: c.GetBool("tun.drop_multicast", false),
  236. routines: routines,
  237. MessageMetrics: messageMetrics,
  238. version: buildVersion,
  239. caPool: caPool,
  240. disconnectInvalid: c.GetBool("pki.disconnect_invalid", false),
  241. relayManager: NewRelayManager(ctx, l, hostMap, c),
  242. punchy: punchy,
  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. loadMultiPortConfig := func(c *config.C) {
  264. ifce.multiPort.Rx = c.GetBool("tun.multiport.rx_enabled", false)
  265. tx := c.GetBool("tun.multiport.tx_enabled", false)
  266. if tx && ifce.udpRaw == nil {
  267. ifce.udpRaw, err = udp.NewRawConn(l, c.GetString("listen.host", "0.0.0.0"), port, uint16(port))
  268. if err != nil {
  269. l.WithError(err).Error("Failed to get raw socket for tun.multiport.tx_enabled")
  270. ifce.udpRaw = nil
  271. tx = false
  272. }
  273. }
  274. if tx {
  275. ifce.multiPort.TxBasePort = uint16(port)
  276. ifce.multiPort.TxPorts = c.GetInt("tun.multiport.tx_ports", 100)
  277. ifce.multiPort.TxHandshake = c.GetBool("tun.multiport.tx_handshake", false)
  278. ifce.multiPort.TxHandshakeDelay = c.GetInt("tun.multiport.tx_handshake_delay", 2)
  279. ifce.udpRaw.ReloadConfig(c)
  280. }
  281. ifce.multiPort.Tx = tx
  282. // TODO: if we upstream this, make this cleaner
  283. handshakeManager.udpRaw = ifce.udpRaw
  284. handshakeManager.multiPort = ifce.multiPort
  285. l.WithField("multiPort", ifce.multiPort).Info("Multiport configured")
  286. }
  287. loadMultiPortConfig(c)
  288. c.RegisterReloadCallback(loadMultiPortConfig)
  289. ifce.RegisterConfigChangeCallbacks(c)
  290. ifce.reloadSendRecvError(c)
  291. go handshakeManager.Run(ctx, ifce)
  292. go lightHouse.LhUpdateWorker(ctx, ifce)
  293. }
  294. // TODO - stats third-party modules start uncancellable goroutines. Update those libs to accept
  295. // a context so that they can exit when the context is Done.
  296. statsStart, err := startStats(l, c, buildVersion, configTest)
  297. if err != nil {
  298. return nil, util.NewContextualError("Failed to start stats emitter", nil, err)
  299. }
  300. if configTest {
  301. return nil, nil
  302. }
  303. //TODO: check if we _should_ be emitting stats
  304. go ifce.emitStats(ctx, c.GetDuration("stats.interval", time.Second*10))
  305. attachCommands(l, c, ssh, hostMap, handshakeManager.pendingHostMap, lightHouse, ifce)
  306. // Start DNS server last to allow using the nebula IP as lighthouse.dns.host
  307. var dnsStart func()
  308. if lightHouse.amLighthouse && serveDns {
  309. l.Debugln("Starting dns server")
  310. dnsStart = dnsMain(l, hostMap, c)
  311. }
  312. return &Control{ifce, l, cancel, sshStart, statsStart, dnsStart}, nil
  313. }