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/sshd"
  12. "github.com/slackhq/nebula/udp"
  13. "gopkg.in/yaml.v2"
  14. )
  15. type m map[string]interface{}
  16. func Main(c *config.C, configTest bool, buildVersion string, logger *logrus.Logger, tunFd *int) (retcon *Control, reterr error) {
  17. ctx, cancel := context.WithCancel(context.Background())
  18. // Automatically cancel the context if Main returns an error, to signal all created goroutines to quit.
  19. defer func() {
  20. if reterr != nil {
  21. cancel()
  22. }
  23. }()
  24. l := logger
  25. l.Formatter = &logrus.TextFormatter{
  26. FullTimestamp: true,
  27. }
  28. // Print the config if in test, the exit comes later
  29. if configTest {
  30. b, err := yaml.Marshal(c.Settings)
  31. if err != nil {
  32. return nil, err
  33. }
  34. // Print the final config
  35. l.Println(string(b))
  36. }
  37. err := configLogger(l, c)
  38. if err != nil {
  39. return nil, NewContextualError("Failed to configure the logger", nil, err)
  40. }
  41. c.RegisterReloadCallback(func(c *config.C) {
  42. err := configLogger(l, c)
  43. if err != nil {
  44. l.WithError(err).Error("Failed to configure the logger")
  45. }
  46. })
  47. caPool, err := loadCAFromConfig(l, c)
  48. if err != nil {
  49. //The errors coming out of loadCA are already nicely formatted
  50. return nil, NewContextualError("Failed to load ca from config", nil, err)
  51. }
  52. l.WithField("fingerprints", caPool.GetFingerprints()).Debug("Trusted CA fingerprints")
  53. cs, err := NewCertStateFromConfig(c)
  54. if err != nil {
  55. //The errors coming out of NewCertStateFromConfig are already nicely formatted
  56. return nil, NewContextualError("Failed to load certificate from config", nil, err)
  57. }
  58. l.WithField("cert", cs.certificate).Debug("Client nebula certificate")
  59. fw, err := NewFirewallFromConfig(l, cs.certificate, c)
  60. if err != nil {
  61. return nil, NewContextualError("Error while loading firewall rules", nil, err)
  62. }
  63. l.WithField("firewallHash", fw.GetRuleHash()).Info("Firewall started")
  64. // TODO: make sure mask is 4 bytes
  65. tunCidr := cs.certificate.Details.Ips[0]
  66. routes, err := parseRoutes(c, tunCidr)
  67. if err != nil {
  68. return nil, NewContextualError("Could not parse tun.routes", nil, err)
  69. }
  70. unsafeRoutes, err := parseUnsafeRoutes(c, tunCidr)
  71. if err != nil {
  72. return nil, NewContextualError("Could not parse tun.unsafe_routes", nil, err)
  73. }
  74. ssh, err := sshd.NewSSHServer(l.WithField("subsystem", "sshd"))
  75. wireSSHReload(l, ssh, c)
  76. var sshStart func()
  77. if c.GetBool("sshd.enabled", false) {
  78. sshStart, err = configSSH(l, ssh, c)
  79. if err != nil {
  80. return nil, NewContextualError("Error while configuring the sshd", nil, err)
  81. }
  82. }
  83. psk, err := NewPskFromConfig(c, iputil.Ip2VpnIp(tunCidr.IP))
  84. if err != nil {
  85. return nil, NewContextualError("Failed to create psk", nil, err)
  86. }
  87. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  88. // All non system modifying configuration consumption should live above this line
  89. // tun config, listeners, anything modifying the computer should be below
  90. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  91. var routines int
  92. // If `routines` is set, use that and ignore the specific values
  93. if routines = c.GetInt("routines", 0); routines != 0 {
  94. if routines < 1 {
  95. routines = 1
  96. }
  97. if routines > 1 {
  98. l.WithField("routines", routines).Info("Using multiple routines")
  99. }
  100. } else {
  101. // deprecated and undocumented
  102. tunQueues := c.GetInt("tun.routines", 1)
  103. udpQueues := c.GetInt("listen.routines", 1)
  104. if tunQueues > udpQueues {
  105. routines = tunQueues
  106. } else {
  107. routines = udpQueues
  108. }
  109. if routines != 1 {
  110. l.WithField("routines", routines).Warn("Setting tun.routines and listen.routines is deprecated. Use `routines` instead")
  111. }
  112. }
  113. // EXPERIMENTAL
  114. // Intentionally not documented yet while we do more testing and determine
  115. // a good default value.
  116. conntrackCacheTimeout := c.GetDuration("firewall.conntrack.routine_cache_timeout", 0)
  117. if routines > 1 && !c.IsSet("firewall.conntrack.routine_cache_timeout") {
  118. // Use a different default if we are running with multiple routines
  119. conntrackCacheTimeout = 1 * time.Second
  120. }
  121. if conntrackCacheTimeout > 0 {
  122. l.WithField("duration", conntrackCacheTimeout).Info("Using routine-local conntrack cache")
  123. }
  124. var tun Inside
  125. if !configTest {
  126. c.CatchHUP(ctx)
  127. switch {
  128. case c.GetBool("tun.disabled", false):
  129. tun = newDisabledTun(tunCidr, c.GetInt("tun.tx_queue", 500), c.GetBool("stats.message_metrics", false), l)
  130. case tunFd != nil:
  131. tun, err = newTunFromFd(
  132. l,
  133. *tunFd,
  134. tunCidr,
  135. c.GetInt("tun.mtu", DEFAULT_MTU),
  136. routes,
  137. unsafeRoutes,
  138. c.GetInt("tun.tx_queue", 500),
  139. )
  140. default:
  141. tun, err = newTun(
  142. l,
  143. c.GetString("tun.dev", ""),
  144. tunCidr,
  145. c.GetInt("tun.mtu", DEFAULT_MTU),
  146. routes,
  147. unsafeRoutes,
  148. c.GetInt("tun.tx_queue", 500),
  149. routines > 1,
  150. )
  151. }
  152. if err != nil {
  153. return nil, NewContextualError("Failed to get a tun/tap device", nil, err)
  154. }
  155. }
  156. defer func() {
  157. if reterr != nil {
  158. tun.Close()
  159. }
  160. }()
  161. // set up our UDP listener
  162. udpConns := make([]*udp.Conn, routines)
  163. port := c.GetInt("listen.port", 0)
  164. if !configTest {
  165. for i := 0; i < routines; i++ {
  166. udpServer, err := udp.NewListener(l, c.GetString("listen.host", "0.0.0.0"), port, routines > 1, c.GetInt("listen.batch", 64))
  167. if err != nil {
  168. return nil, NewContextualError("Failed to open udp listener", m{"queue": i}, err)
  169. }
  170. udpServer.ReloadConfig(c)
  171. udpConns[i] = udpServer
  172. // If port is dynamic, discover it
  173. if port == 0 {
  174. uPort, err := udpServer.LocalAddr()
  175. if err != nil {
  176. return nil, NewContextualError("Failed to get listening port", nil, err)
  177. }
  178. port = int(uPort.Port)
  179. }
  180. }
  181. }
  182. // Set up my internal host map
  183. var preferredRanges []*net.IPNet
  184. rawPreferredRanges := c.GetStringSlice("preferred_ranges", []string{})
  185. // First, check if 'preferred_ranges' is set and fallback to 'local_range'
  186. if len(rawPreferredRanges) > 0 {
  187. for _, rawPreferredRange := range rawPreferredRanges {
  188. _, preferredRange, err := net.ParseCIDR(rawPreferredRange)
  189. if err != nil {
  190. return nil, NewContextualError("Failed to parse preferred ranges", nil, err)
  191. }
  192. preferredRanges = append(preferredRanges, preferredRange)
  193. }
  194. }
  195. // local_range was superseded by preferred_ranges. If it is still present,
  196. // merge the local_range setting into preferred_ranges. We will probably
  197. // deprecate local_range and remove in the future.
  198. rawLocalRange := c.GetString("local_range", "")
  199. if rawLocalRange != "" {
  200. _, localRange, err := net.ParseCIDR(rawLocalRange)
  201. if err != nil {
  202. return nil, NewContextualError("Failed to parse local_range", nil, err)
  203. }
  204. // Check if the entry for local_range was already specified in
  205. // preferred_ranges. Don't put it into the slice twice if so.
  206. var found bool
  207. for _, r := range preferredRanges {
  208. if r.String() == localRange.String() {
  209. found = true
  210. break
  211. }
  212. }
  213. if !found {
  214. preferredRanges = append(preferredRanges, localRange)
  215. }
  216. }
  217. hostMap := NewHostMap(l, "main", tunCidr, preferredRanges)
  218. hostMap.addUnsafeRoutes(&unsafeRoutes)
  219. hostMap.metricsEnabled = c.GetBool("stats.message_metrics", false)
  220. l.WithField("network", hostMap.vpnCIDR).WithField("preferredRanges", hostMap.preferredRanges).Info("Main HostMap created")
  221. /*
  222. config.SetDefault("promoter.interval", 10)
  223. go hostMap.Promoter(config.GetInt("promoter.interval"))
  224. */
  225. punchy := NewPunchyFromConfig(c)
  226. if punchy.Punch && !configTest {
  227. l.Info("UDP hole punching enabled")
  228. go hostMap.Punchy(ctx, udpConns[0])
  229. }
  230. amLighthouse := c.GetBool("lighthouse.am_lighthouse", false)
  231. // fatal if am_lighthouse is enabled but we are using an ephemeral port
  232. if amLighthouse && (c.GetInt("listen.port", 0) == 0) {
  233. return nil, NewContextualError("lighthouse.am_lighthouse enabled on node but no port number is set in config", nil, nil)
  234. }
  235. // warn if am_lighthouse is enabled but upstream lighthouses exists
  236. rawLighthouseHosts := c.GetStringSlice("lighthouse.hosts", []string{})
  237. if amLighthouse && len(rawLighthouseHosts) != 0 {
  238. l.Warn("lighthouse.am_lighthouse enabled on node but upstream lighthouses exist in config")
  239. }
  240. lighthouseHosts := make([]iputil.VpnIp, len(rawLighthouseHosts))
  241. for i, host := range rawLighthouseHosts {
  242. ip := net.ParseIP(host)
  243. if ip == nil {
  244. return nil, NewContextualError("Unable to parse lighthouse host entry", m{"host": host, "entry": i + 1}, nil)
  245. }
  246. if !tunCidr.Contains(ip) {
  247. return nil, NewContextualError("lighthouse host is not in our subnet, invalid", m{"vpnIp": ip, "network": tunCidr.String()}, nil)
  248. }
  249. lighthouseHosts[i] = iputil.Ip2VpnIp(ip)
  250. }
  251. lightHouse := NewLightHouse(
  252. l,
  253. amLighthouse,
  254. tunCidr,
  255. lighthouseHosts,
  256. //TODO: change to a duration
  257. c.GetInt("lighthouse.interval", 10),
  258. uint32(port),
  259. udpConns[0],
  260. punchy.Respond,
  261. punchy.Delay,
  262. c.GetBool("stats.lighthouse_metrics", false),
  263. )
  264. remoteAllowList, err := NewRemoteAllowListFromConfig(c, "lighthouse.remote_allow_list", "lighthouse.remote_allow_ranges")
  265. if err != nil {
  266. return nil, NewContextualError("Invalid lighthouse.remote_allow_list", nil, err)
  267. }
  268. lightHouse.SetRemoteAllowList(remoteAllowList)
  269. localAllowList, err := NewLocalAllowListFromConfig(c, "lighthouse.local_allow_list")
  270. if err != nil {
  271. return nil, NewContextualError("Invalid lighthouse.local_allow_list", nil, err)
  272. }
  273. lightHouse.SetLocalAllowList(localAllowList)
  274. //TODO: Move all of this inside functions in lighthouse.go
  275. for k, v := range c.GetMap("static_host_map", map[interface{}]interface{}{}) {
  276. ip := net.ParseIP(fmt.Sprintf("%v", k))
  277. vpnIp := iputil.Ip2VpnIp(ip)
  278. if !tunCidr.Contains(ip) {
  279. return nil, NewContextualError("static_host_map key is not in our subnet, invalid", m{"vpnIp": vpnIp, "network": tunCidr.String()}, nil)
  280. }
  281. vals, ok := v.([]interface{})
  282. if ok {
  283. for _, v := range vals {
  284. ip, port, err := udp.ParseIPAndPort(fmt.Sprintf("%v", v))
  285. if err != nil {
  286. return nil, NewContextualError("Static host address could not be parsed", m{"vpnIp": vpnIp}, err)
  287. }
  288. lightHouse.AddStaticRemote(vpnIp, udp.NewAddr(ip, port))
  289. }
  290. } else {
  291. ip, port, err := udp.ParseIPAndPort(fmt.Sprintf("%v", v))
  292. if err != nil {
  293. return nil, NewContextualError("Static host address could not be parsed", m{"vpnIp": vpnIp}, err)
  294. }
  295. lightHouse.AddStaticRemote(vpnIp, udp.NewAddr(ip, port))
  296. }
  297. }
  298. err = lightHouse.ValidateLHStaticEntries()
  299. if err != nil {
  300. l.WithError(err).Error("Lighthouse unreachable")
  301. }
  302. var messageMetrics *MessageMetrics
  303. if c.GetBool("stats.message_metrics", false) {
  304. messageMetrics = newMessageMetrics()
  305. } else {
  306. messageMetrics = newMessageMetricsOnlyRecvError()
  307. }
  308. handshakeConfig := HandshakeConfig{
  309. tryInterval: c.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
  310. retries: c.GetInt("handshakes.retries", DefaultHandshakeRetries),
  311. triggerBuffer: c.GetInt("handshakes.trigger_buffer", DefaultHandshakeTriggerBuffer),
  312. messageMetrics: messageMetrics,
  313. }
  314. handshakeManager := NewHandshakeManager(l, tunCidr, preferredRanges, hostMap, lightHouse, udpConns[0], handshakeConfig)
  315. lightHouse.handshakeTrigger = handshakeManager.trigger
  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. psk: psk,
  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, 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. }