main.go 14 KB

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