3
0

main.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. package nebula
  2. import (
  3. "context"
  4. "encoding/binary"
  5. "fmt"
  6. "net"
  7. "time"
  8. "github.com/sirupsen/logrus"
  9. "github.com/slackhq/nebula/config"
  10. "github.com/slackhq/nebula/overlay"
  11. "github.com/slackhq/nebula/sshd"
  12. "github.com/slackhq/nebula/udp"
  13. "github.com/slackhq/nebula/util"
  14. "gopkg.in/yaml.v2"
  15. )
  16. type m map[string]interface{}
  17. func Main(c *config.C, configTest bool, buildVersion string, logger *logrus.Logger, tunFd *int) (retcon *Control, reterr error) {
  18. ctx, cancel := context.WithCancel(context.Background())
  19. // Automatically cancel the context if Main returns an error, to signal all created goroutines to quit.
  20. defer func() {
  21. if reterr != nil {
  22. cancel()
  23. }
  24. }()
  25. l := logger
  26. l.Formatter = &logrus.TextFormatter{
  27. FullTimestamp: true,
  28. }
  29. // Print the config if in test, the exit comes later
  30. if configTest {
  31. b, err := yaml.Marshal(c.Settings)
  32. if err != nil {
  33. return nil, err
  34. }
  35. // Print the final config
  36. l.Println(string(b))
  37. }
  38. err := configLogger(l, c)
  39. if err != nil {
  40. return nil, util.ContextualizeIfNeeded("Failed to configure the logger", err)
  41. }
  42. c.RegisterReloadCallback(func(c *config.C) {
  43. err := configLogger(l, c)
  44. if err != nil {
  45. l.WithError(err).Error("Failed to configure the logger")
  46. }
  47. })
  48. pki, err := NewPKIFromConfig(l, c)
  49. if err != nil {
  50. return nil, util.ContextualizeIfNeeded("Failed to load PKI from config", err)
  51. }
  52. certificate := pki.GetCertState().Certificate
  53. fw, err := NewFirewallFromConfig(l, certificate, c)
  54. if err != nil {
  55. return nil, util.ContextualizeIfNeeded("Error while loading firewall rules", err)
  56. }
  57. l.WithField("firewallHash", fw.GetRuleHash()).Info("Firewall started")
  58. // TODO: make sure mask is 4 bytes
  59. tunCidr := certificate.Details.Ips[0]
  60. ssh, err := sshd.NewSSHServer(l.WithField("subsystem", "sshd"))
  61. wireSSHReload(l, ssh, c)
  62. var sshStart func()
  63. if c.GetBool("sshd.enabled", false) {
  64. sshStart, err = configSSH(l, ssh, c)
  65. if err != nil {
  66. return nil, util.ContextualizeIfNeeded("Error while configuring the sshd", err)
  67. }
  68. }
  69. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  70. // All non system modifying configuration consumption should live above this line
  71. // tun config, listeners, anything modifying the computer should be below
  72. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  73. var routines int
  74. // If `routines` is set, use that and ignore the specific values
  75. if routines = c.GetInt("routines", 0); routines != 0 {
  76. if routines < 1 {
  77. routines = 1
  78. }
  79. if routines > 1 {
  80. l.WithField("routines", routines).Info("Using multiple routines")
  81. }
  82. } else {
  83. // deprecated and undocumented
  84. tunQueues := c.GetInt("tun.routines", 1)
  85. udpQueues := c.GetInt("listen.routines", 1)
  86. if tunQueues > udpQueues {
  87. routines = tunQueues
  88. } else {
  89. routines = udpQueues
  90. }
  91. if routines != 1 {
  92. l.WithField("routines", routines).Warn("Setting tun.routines and listen.routines is deprecated. Use `routines` instead")
  93. }
  94. }
  95. // EXPERIMENTAL
  96. // Intentionally not documented yet while we do more testing and determine
  97. // a good default value.
  98. conntrackCacheTimeout := c.GetDuration("firewall.conntrack.routine_cache_timeout", 0)
  99. if routines > 1 && !c.IsSet("firewall.conntrack.routine_cache_timeout") {
  100. // Use a different default if we are running with multiple routines
  101. conntrackCacheTimeout = 1 * time.Second
  102. }
  103. if conntrackCacheTimeout > 0 {
  104. l.WithField("duration", conntrackCacheTimeout).Info("Using routine-local conntrack cache")
  105. }
  106. var tun overlay.Device
  107. if !configTest {
  108. c.CatchHUP(ctx)
  109. tun, err = overlay.NewDeviceFromConfig(c, l, tunCidr, tunFd, routines)
  110. if err != nil {
  111. return nil, util.ContextualizeIfNeeded("Failed to get a tun/tap device", err)
  112. }
  113. defer func() {
  114. if reterr != nil {
  115. tun.Close()
  116. }
  117. }()
  118. }
  119. // set up our UDP listener
  120. udpConns := make([]udp.Conn, routines)
  121. port := c.GetInt("listen.port", 0)
  122. if !configTest {
  123. rawListenHost := c.GetString("listen.host", "0.0.0.0")
  124. var listenHost *net.IPAddr
  125. if rawListenHost == "[::]" {
  126. // Old guidance was to provide the literal `[::]` in `listen.host` but that won't resolve.
  127. listenHost = &net.IPAddr{IP: net.IPv6zero}
  128. } else {
  129. listenHost, err = net.ResolveIPAddr("ip", rawListenHost)
  130. if err != nil {
  131. return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
  132. }
  133. }
  134. for i := 0; i < routines; i++ {
  135. udpServer, err := udp.NewListener(l, listenHost.IP, port, routines > 1, c.GetInt("listen.batch", 64))
  136. if err != nil {
  137. return nil, util.NewContextualError("Failed to open udp listener", m{"queue": i}, err)
  138. }
  139. udpServer.ReloadConfig(c)
  140. udpConns[i] = udpServer
  141. }
  142. }
  143. // Set up my internal host map
  144. var preferredRanges []*net.IPNet
  145. rawPreferredRanges := c.GetStringSlice("preferred_ranges", []string{})
  146. // First, check if 'preferred_ranges' is set and fallback to 'local_range'
  147. if len(rawPreferredRanges) > 0 {
  148. for _, rawPreferredRange := range rawPreferredRanges {
  149. _, preferredRange, err := net.ParseCIDR(rawPreferredRange)
  150. if err != nil {
  151. return nil, util.ContextualizeIfNeeded("Failed to parse preferred ranges", err)
  152. }
  153. preferredRanges = append(preferredRanges, preferredRange)
  154. }
  155. }
  156. // local_range was superseded by preferred_ranges. If it is still present,
  157. // merge the local_range setting into preferred_ranges. We will probably
  158. // deprecate local_range and remove in the future.
  159. rawLocalRange := c.GetString("local_range", "")
  160. if rawLocalRange != "" {
  161. _, localRange, err := net.ParseCIDR(rawLocalRange)
  162. if err != nil {
  163. return nil, util.ContextualizeIfNeeded("Failed to parse local_range", err)
  164. }
  165. // Check if the entry for local_range was already specified in
  166. // preferred_ranges. Don't put it into the slice twice if so.
  167. var found bool
  168. for _, r := range preferredRanges {
  169. if r.String() == localRange.String() {
  170. found = true
  171. break
  172. }
  173. }
  174. if !found {
  175. preferredRanges = append(preferredRanges, localRange)
  176. }
  177. }
  178. hostMap := NewHostMap(l, tunCidr, preferredRanges)
  179. hostMap.metricsEnabled = c.GetBool("stats.message_metrics", false)
  180. l.
  181. WithField("network", hostMap.vpnCIDR.String()).
  182. WithField("preferredRanges", hostMap.preferredRanges).
  183. Info("Main HostMap created")
  184. punchy := NewPunchyFromConfig(l, c)
  185. lightHouse, err := NewLightHouseFromConfig(ctx, l, c, tunCidr, udpConns[0], punchy)
  186. if err != nil {
  187. return nil, util.ContextualizeIfNeeded("Failed to initialize lighthouse handler", err)
  188. }
  189. var messageMetrics *MessageMetrics
  190. if c.GetBool("stats.message_metrics", false) {
  191. messageMetrics = newMessageMetrics()
  192. } else {
  193. messageMetrics = newMessageMetricsOnlyRecvError()
  194. }
  195. useRelays := c.GetBool("relay.use_relays", DefaultUseRelays) && !c.GetBool("relay.am_relay", false)
  196. handshakeConfig := HandshakeConfig{
  197. tryInterval: c.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
  198. retries: c.GetInt("handshakes.retries", DefaultHandshakeRetries),
  199. triggerBuffer: c.GetInt("handshakes.trigger_buffer", DefaultHandshakeTriggerBuffer),
  200. useRelays: useRelays,
  201. messageMetrics: messageMetrics,
  202. }
  203. handshakeManager := NewHandshakeManager(l, hostMap, lightHouse, udpConns[0], handshakeConfig)
  204. lightHouse.handshakeTrigger = handshakeManager.trigger
  205. serveDns := false
  206. if c.GetBool("lighthouse.serve_dns", false) {
  207. if c.GetBool("lighthouse.am_lighthouse", false) {
  208. serveDns = true
  209. } else {
  210. l.Warn("DNS server refusing to run because this host is not a lighthouse.")
  211. }
  212. }
  213. checkInterval := c.GetInt("timers.connection_alive_interval", 5)
  214. pendingDeletionInterval := c.GetInt("timers.pending_deletion_interval", 10)
  215. ifConfig := &InterfaceConfig{
  216. HostMap: hostMap,
  217. Inside: tun,
  218. Outside: udpConns[0],
  219. pki: pki,
  220. Cipher: c.GetString("cipher", "aes"),
  221. Firewall: fw,
  222. ServeDns: serveDns,
  223. HandshakeManager: handshakeManager,
  224. lightHouse: lightHouse,
  225. checkInterval: time.Second * time.Duration(checkInterval),
  226. pendingDeletionInterval: time.Second * time.Duration(pendingDeletionInterval),
  227. tryPromoteEvery: c.GetUint32("counters.try_promote", defaultPromoteEvery),
  228. reQueryEvery: c.GetUint32("counters.requery_every_packets", defaultReQueryEvery),
  229. reQueryWait: c.GetDuration("timers.requery_wait_duration", defaultReQueryWait),
  230. DropLocalBroadcast: c.GetBool("tun.drop_local_broadcast", false),
  231. DropMulticast: c.GetBool("tun.drop_multicast", false),
  232. routines: routines,
  233. MessageMetrics: messageMetrics,
  234. version: buildVersion,
  235. disconnectInvalid: c.GetBool("pki.disconnect_invalid", false),
  236. relayManager: NewRelayManager(ctx, l, hostMap, c),
  237. punchy: punchy,
  238. ConntrackCacheTimeout: conntrackCacheTimeout,
  239. l: l,
  240. }
  241. switch ifConfig.Cipher {
  242. case "aes":
  243. noiseEndianness = binary.BigEndian
  244. case "chachapoly":
  245. noiseEndianness = binary.LittleEndian
  246. default:
  247. return nil, fmt.Errorf("unknown cipher: %v", ifConfig.Cipher)
  248. }
  249. var ifce *Interface
  250. if !configTest {
  251. ifce, err = NewInterface(ctx, ifConfig)
  252. if err != nil {
  253. return nil, fmt.Errorf("failed to initialize interface: %s", err)
  254. }
  255. // TODO: Better way to attach these, probably want a new interface in InterfaceConfig
  256. // I don't want to make this initial commit too far-reaching though
  257. ifce.writers = udpConns
  258. lightHouse.ifce = ifce
  259. loadMultiPortConfig := func(c *config.C) {
  260. ifce.multiPort.Rx = c.GetBool("tun.multiport.rx_enabled", false)
  261. tx := c.GetBool("tun.multiport.tx_enabled", false)
  262. if tx && ifce.udpRaw == nil {
  263. ifce.udpRaw, err = udp.NewRawConn(l, c.GetString("listen.host", "0.0.0.0"), port, uint16(port))
  264. if err != nil {
  265. l.WithError(err).Error("Failed to get raw socket for tun.multiport.tx_enabled")
  266. ifce.udpRaw = nil
  267. tx = false
  268. }
  269. }
  270. if tx {
  271. ifce.multiPort.TxBasePort = uint16(port)
  272. ifce.multiPort.TxPorts = c.GetInt("tun.multiport.tx_ports", 100)
  273. ifce.multiPort.TxHandshake = c.GetBool("tun.multiport.tx_handshake", false)
  274. ifce.multiPort.TxHandshakeDelay = c.GetInt("tun.multiport.tx_handshake_delay", 2)
  275. ifce.udpRaw.ReloadConfig(c)
  276. }
  277. ifce.multiPort.Tx = tx
  278. // TODO: if we upstream this, make this cleaner
  279. handshakeManager.udpRaw = ifce.udpRaw
  280. handshakeManager.multiPort = ifce.multiPort
  281. l.WithField("multiPort", ifce.multiPort).Info("Multiport configured")
  282. }
  283. loadMultiPortConfig(c)
  284. c.RegisterReloadCallback(loadMultiPortConfig)
  285. ifce.RegisterConfigChangeCallbacks(c)
  286. ifce.reloadSendRecvError(c)
  287. handshakeManager.f = ifce
  288. go handshakeManager.Run(ctx)
  289. }
  290. // TODO - stats third-party modules start uncancellable goroutines. Update those libs to accept
  291. // a context so that they can exit when the context is Done.
  292. statsStart, err := startStats(l, c, buildVersion, configTest)
  293. if err != nil {
  294. return nil, util.ContextualizeIfNeeded("Failed to start stats emitter", err)
  295. }
  296. if configTest {
  297. return nil, nil
  298. }
  299. //TODO: check if we _should_ be emitting stats
  300. go ifce.emitStats(ctx, c.GetDuration("stats.interval", time.Second*10))
  301. attachCommands(l, c, ssh, ifce)
  302. // Start DNS server last to allow using the nebula IP as lighthouse.dns.host
  303. var dnsStart func()
  304. if lightHouse.amLighthouse && serveDns {
  305. l.Debugln("Starting dns server")
  306. dnsStart = dnsMain(l, hostMap, c)
  307. }
  308. return &Control{
  309. ifce,
  310. l,
  311. cancel,
  312. sshStart,
  313. statsStart,
  314. dnsStart,
  315. lightHouse.StartUpdateWorker,
  316. }, nil
  317. }