main.go 14 KB

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