main.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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/iputil"
  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. routes, err := parseRoutes(c, tunCidr)
  69. if err != nil {
  70. return nil, util.NewContextualError("Could not parse tun.routes", nil, err)
  71. }
  72. unsafeRoutes, err := parseUnsafeRoutes(c, tunCidr)
  73. if err != nil {
  74. return nil, util.NewContextualError("Could not parse tun.unsafe_routes", nil, err)
  75. }
  76. ssh, err := sshd.NewSSHServer(l.WithField("subsystem", "sshd"))
  77. wireSSHReload(l, ssh, c)
  78. var sshStart func()
  79. if c.GetBool("sshd.enabled", false) {
  80. sshStart, err = configSSH(l, ssh, c)
  81. if err != nil {
  82. return nil, util.NewContextualError("Error while configuring the sshd", nil, err)
  83. }
  84. }
  85. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  86. // All non system modifying configuration consumption should live above this line
  87. // tun config, listeners, anything modifying the computer should be below
  88. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  89. var routines int
  90. // If `routines` is set, use that and ignore the specific values
  91. if routines = c.GetInt("routines", 0); routines != 0 {
  92. if routines < 1 {
  93. routines = 1
  94. }
  95. if routines > 1 {
  96. l.WithField("routines", routines).Info("Using multiple routines")
  97. }
  98. } else {
  99. // deprecated and undocumented
  100. tunQueues := c.GetInt("tun.routines", 1)
  101. udpQueues := c.GetInt("listen.routines", 1)
  102. if tunQueues > udpQueues {
  103. routines = tunQueues
  104. } else {
  105. routines = udpQueues
  106. }
  107. if routines != 1 {
  108. l.WithField("routines", routines).Warn("Setting tun.routines and listen.routines is deprecated. Use `routines` instead")
  109. }
  110. }
  111. // EXPERIMENTAL
  112. // Intentionally not documented yet while we do more testing and determine
  113. // a good default value.
  114. conntrackCacheTimeout := c.GetDuration("firewall.conntrack.routine_cache_timeout", 0)
  115. if routines > 1 && !c.IsSet("firewall.conntrack.routine_cache_timeout") {
  116. // Use a different default if we are running with multiple routines
  117. conntrackCacheTimeout = 1 * time.Second
  118. }
  119. if conntrackCacheTimeout > 0 {
  120. l.WithField("duration", conntrackCacheTimeout).Info("Using routine-local conntrack cache")
  121. }
  122. var tun overlay.Device
  123. if !configTest {
  124. c.CatchHUP(ctx)
  125. switch {
  126. case c.GetBool("tun.disabled", false):
  127. tun = newDisabledTun(tunCidr, c.GetInt("tun.tx_queue", 500), c.GetBool("stats.message_metrics", false), l)
  128. case tunFd != nil:
  129. tun, err = newTunFromFd(
  130. l,
  131. *tunFd,
  132. tunCidr,
  133. c.GetInt("tun.mtu", DEFAULT_MTU),
  134. routes,
  135. unsafeRoutes,
  136. c.GetInt("tun.tx_queue", 500),
  137. )
  138. default:
  139. tun, err = newTun(
  140. l,
  141. c.GetString("tun.dev", ""),
  142. tunCidr,
  143. c.GetInt("tun.mtu", DEFAULT_MTU),
  144. routes,
  145. unsafeRoutes,
  146. c.GetInt("tun.tx_queue", 500),
  147. routines > 1,
  148. )
  149. }
  150. if err != nil {
  151. return nil, util.NewContextualError("Failed to get a tun/tap device", nil, err)
  152. }
  153. }
  154. defer func() {
  155. if reterr != nil {
  156. tun.Close()
  157. }
  158. }()
  159. // set up our UDP listener
  160. udpConns := make([]*udp.Conn, routines)
  161. port := c.GetInt("listen.port", 0)
  162. if !configTest {
  163. for i := 0; i < routines; i++ {
  164. udpServer, err := udp.NewListener(l, c.GetString("listen.host", "0.0.0.0"), port, routines > 1, c.GetInt("listen.batch", 64))
  165. if err != nil {
  166. return nil, util.NewContextualError("Failed to open udp listener", m{"queue": i}, err)
  167. }
  168. udpServer.ReloadConfig(c)
  169. udpConns[i] = udpServer
  170. // If port is dynamic, discover it
  171. if port == 0 {
  172. uPort, err := udpServer.LocalAddr()
  173. if err != nil {
  174. return nil, util.NewContextualError("Failed to get listening port", nil, err)
  175. }
  176. port = int(uPort.Port)
  177. }
  178. }
  179. }
  180. // Set up my internal host map
  181. var preferredRanges []*net.IPNet
  182. rawPreferredRanges := c.GetStringSlice("preferred_ranges", []string{})
  183. // First, check if 'preferred_ranges' is set and fallback to 'local_range'
  184. if len(rawPreferredRanges) > 0 {
  185. for _, rawPreferredRange := range rawPreferredRanges {
  186. _, preferredRange, err := net.ParseCIDR(rawPreferredRange)
  187. if err != nil {
  188. return nil, util.NewContextualError("Failed to parse preferred ranges", nil, err)
  189. }
  190. preferredRanges = append(preferredRanges, preferredRange)
  191. }
  192. }
  193. // local_range was superseded by preferred_ranges. If it is still present,
  194. // merge the local_range setting into preferred_ranges. We will probably
  195. // deprecate local_range and remove in the future.
  196. rawLocalRange := c.GetString("local_range", "")
  197. if rawLocalRange != "" {
  198. _, localRange, err := net.ParseCIDR(rawLocalRange)
  199. if err != nil {
  200. return nil, util.NewContextualError("Failed to parse local_range", nil, err)
  201. }
  202. // Check if the entry for local_range was already specified in
  203. // preferred_ranges. Don't put it into the slice twice if so.
  204. var found bool
  205. for _, r := range preferredRanges {
  206. if r.String() == localRange.String() {
  207. found = true
  208. break
  209. }
  210. }
  211. if !found {
  212. preferredRanges = append(preferredRanges, localRange)
  213. }
  214. }
  215. hostMap := NewHostMap(l, "main", tunCidr, preferredRanges)
  216. hostMap.addUnsafeRoutes(&unsafeRoutes)
  217. hostMap.metricsEnabled = c.GetBool("stats.message_metrics", false)
  218. l.WithField("network", hostMap.vpnCIDR).WithField("preferredRanges", hostMap.preferredRanges).Info("Main HostMap created")
  219. /*
  220. config.SetDefault("promoter.interval", 10)
  221. go hostMap.Promoter(config.GetInt("promoter.interval"))
  222. */
  223. punchy := NewPunchyFromConfig(c)
  224. if punchy.Punch && !configTest {
  225. l.Info("UDP hole punching enabled")
  226. go hostMap.Punchy(ctx, udpConns[0])
  227. }
  228. amLighthouse := c.GetBool("lighthouse.am_lighthouse", false)
  229. // fatal if am_lighthouse is enabled but we are using an ephemeral port
  230. if amLighthouse && (c.GetInt("listen.port", 0) == 0) {
  231. return nil, util.NewContextualError("lighthouse.am_lighthouse enabled on node but no port number is set in config", nil, nil)
  232. }
  233. // warn if am_lighthouse is enabled but upstream lighthouses exists
  234. rawLighthouseHosts := c.GetStringSlice("lighthouse.hosts", []string{})
  235. if amLighthouse && len(rawLighthouseHosts) != 0 {
  236. l.Warn("lighthouse.am_lighthouse enabled on node but upstream lighthouses exist in config")
  237. }
  238. lighthouseHosts := make([]iputil.VpnIp, len(rawLighthouseHosts))
  239. for i, host := range rawLighthouseHosts {
  240. ip := net.ParseIP(host)
  241. if ip == nil {
  242. return nil, util.NewContextualError("Unable to parse lighthouse host entry", m{"host": host, "entry": i + 1}, nil)
  243. }
  244. if !tunCidr.Contains(ip) {
  245. return nil, util.NewContextualError("lighthouse host is not in our subnet, invalid", m{"vpnIp": ip, "network": tunCidr.String()}, nil)
  246. }
  247. lighthouseHosts[i] = iputil.Ip2VpnIp(ip)
  248. }
  249. lightHouse := NewLightHouse(
  250. l,
  251. amLighthouse,
  252. tunCidr,
  253. lighthouseHosts,
  254. //TODO: change to a duration
  255. c.GetInt("lighthouse.interval", 10),
  256. uint32(port),
  257. udpConns[0],
  258. punchy.Respond,
  259. punchy.Delay,
  260. c.GetBool("stats.lighthouse_metrics", false),
  261. )
  262. remoteAllowList, err := NewRemoteAllowListFromConfig(c, "lighthouse.remote_allow_list", "lighthouse.remote_allow_ranges")
  263. if err != nil {
  264. return nil, util.NewContextualError("Invalid lighthouse.remote_allow_list", nil, err)
  265. }
  266. lightHouse.SetRemoteAllowList(remoteAllowList)
  267. localAllowList, err := NewLocalAllowListFromConfig(c, "lighthouse.local_allow_list")
  268. if err != nil {
  269. return nil, util.NewContextualError("Invalid lighthouse.local_allow_list", nil, err)
  270. }
  271. lightHouse.SetLocalAllowList(localAllowList)
  272. //TODO: Move all of this inside functions in lighthouse.go
  273. for k, v := range c.GetMap("static_host_map", map[interface{}]interface{}{}) {
  274. ip := net.ParseIP(fmt.Sprintf("%v", k))
  275. vpnIp := iputil.Ip2VpnIp(ip)
  276. if !tunCidr.Contains(ip) {
  277. return nil, util.NewContextualError("static_host_map key is not in our subnet, invalid", m{"vpnIp": vpnIp, "network": tunCidr.String()}, nil)
  278. }
  279. vals, ok := v.([]interface{})
  280. if ok {
  281. for _, v := range vals {
  282. ip, port, err := udp.ParseIPAndPort(fmt.Sprintf("%v", v))
  283. if err != nil {
  284. return nil, util.NewContextualError("Static host address could not be parsed", m{"vpnIp": vpnIp}, err)
  285. }
  286. lightHouse.AddStaticRemote(vpnIp, udp.NewAddr(ip, port))
  287. }
  288. } else {
  289. ip, port, err := udp.ParseIPAndPort(fmt.Sprintf("%v", v))
  290. if err != nil {
  291. return nil, util.NewContextualError("Static host address could not be parsed", m{"vpnIp": vpnIp}, err)
  292. }
  293. lightHouse.AddStaticRemote(vpnIp, udp.NewAddr(ip, port))
  294. }
  295. }
  296. err = lightHouse.ValidateLHStaticEntries()
  297. if err != nil {
  298. l.WithError(err).Error("Lighthouse unreachable")
  299. }
  300. var messageMetrics *MessageMetrics
  301. if c.GetBool("stats.message_metrics", false) {
  302. messageMetrics = newMessageMetrics()
  303. } else {
  304. messageMetrics = newMessageMetricsOnlyRecvError()
  305. }
  306. handshakeConfig := HandshakeConfig{
  307. tryInterval: c.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
  308. retries: c.GetInt("handshakes.retries", DefaultHandshakeRetries),
  309. triggerBuffer: c.GetInt("handshakes.trigger_buffer", DefaultHandshakeTriggerBuffer),
  310. messageMetrics: messageMetrics,
  311. }
  312. handshakeManager := NewHandshakeManager(l, tunCidr, preferredRanges, hostMap, lightHouse, udpConns[0], handshakeConfig)
  313. lightHouse.handshakeTrigger = handshakeManager.trigger
  314. //TODO: These will be reused for psk
  315. //handshakeMACKey := config.GetString("handshake_mac.key", "")
  316. //handshakeAcceptedMACKeys := config.GetStringSlice("handshake_mac.accepted_keys", []string{})
  317. serveDns := false
  318. if c.GetBool("lighthouse.serve_dns", false) {
  319. if c.GetBool("lighthouse.am_lighthouse", false) {
  320. serveDns = true
  321. } else {
  322. l.Warn("DNS server refusing to run because this host is not a lighthouse.")
  323. }
  324. }
  325. checkInterval := c.GetInt("timers.connection_alive_interval", 5)
  326. pendingDeletionInterval := c.GetInt("timers.pending_deletion_interval", 10)
  327. ifConfig := &InterfaceConfig{
  328. HostMap: hostMap,
  329. Inside: tun,
  330. Outside: udpConns[0],
  331. certState: cs,
  332. Cipher: c.GetString("cipher", "aes"),
  333. Firewall: fw,
  334. ServeDns: serveDns,
  335. HandshakeManager: handshakeManager,
  336. lightHouse: lightHouse,
  337. checkInterval: checkInterval,
  338. pendingDeletionInterval: pendingDeletionInterval,
  339. DropLocalBroadcast: c.GetBool("tun.drop_local_broadcast", false),
  340. DropMulticast: c.GetBool("tun.drop_multicast", false),
  341. routines: routines,
  342. MessageMetrics: messageMetrics,
  343. version: buildVersion,
  344. caPool: caPool,
  345. disconnectInvalid: c.GetBool("pki.disconnect_invalid", false),
  346. ConntrackCacheTimeout: conntrackCacheTimeout,
  347. l: l,
  348. }
  349. switch ifConfig.Cipher {
  350. case "aes":
  351. noiseEndianness = binary.BigEndian
  352. case "chachapoly":
  353. noiseEndianness = binary.LittleEndian
  354. default:
  355. return nil, fmt.Errorf("unknown cipher: %v", ifConfig.Cipher)
  356. }
  357. var ifce *Interface
  358. if !configTest {
  359. ifce, err = NewInterface(ctx, ifConfig)
  360. if err != nil {
  361. return nil, fmt.Errorf("failed to initialize interface: %s", err)
  362. }
  363. // TODO: Better way to attach these, probably want a new interface in InterfaceConfig
  364. // I don't want to make this initial commit too far-reaching though
  365. ifce.writers = udpConns
  366. ifce.RegisterConfigChangeCallbacks(c)
  367. go handshakeManager.Run(ctx, ifce)
  368. go lightHouse.LhUpdateWorker(ctx, ifce)
  369. }
  370. // TODO - stats third-party modules start uncancellable goroutines. Update those libs to accept
  371. // a context so that they can exit when the context is Done.
  372. statsStart, err := startStats(l, c, buildVersion, configTest)
  373. if err != nil {
  374. return nil, util.NewContextualError("Failed to start stats emitter", nil, err)
  375. }
  376. if configTest {
  377. return nil, nil
  378. }
  379. //TODO: check if we _should_ be emitting stats
  380. go ifce.emitStats(ctx, c.GetDuration("stats.interval", time.Second*10))
  381. attachCommands(l, ssh, hostMap, handshakeManager.pendingHostMap, lightHouse, ifce)
  382. // Start DNS server last to allow using the nebula IP as lighthouse.dns.host
  383. var dnsStart func()
  384. if amLighthouse && serveDns {
  385. l.Debugln("Starting dns server")
  386. dnsStart = dnsMain(l, hostMap, c)
  387. }
  388. return &Control{ifce, l, cancel, sshStart, statsStart, dnsStart}, nil
  389. }