main.go 14 KB

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