main.go 14 KB

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