main.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. package nebula
  2. import (
  3. "encoding/binary"
  4. "fmt"
  5. "net"
  6. "os"
  7. "os/signal"
  8. "strconv"
  9. "strings"
  10. "syscall"
  11. "time"
  12. "github.com/sirupsen/logrus"
  13. "github.com/slackhq/nebula/sshd"
  14. "gopkg.in/yaml.v2"
  15. )
  16. var l = logrus.New()
  17. type m map[string]interface{}
  18. func Main(configPath string, configTest bool, buildVersion string) {
  19. l.Out = os.Stdout
  20. l.Formatter = &logrus.TextFormatter{
  21. FullTimestamp: true,
  22. }
  23. config := NewConfig()
  24. err := config.Load(configPath)
  25. if err != nil {
  26. l.WithError(err).Error("Failed to load config")
  27. os.Exit(1)
  28. }
  29. // Print the config if in test, the exit comes later
  30. if configTest {
  31. b, err := yaml.Marshal(config.Settings)
  32. if err != nil {
  33. l.Println(err)
  34. os.Exit(1)
  35. }
  36. l.Println(string(b))
  37. }
  38. err = configLogger(config)
  39. if err != nil {
  40. l.WithError(err).Error("Failed to configure the logger")
  41. }
  42. config.RegisterReloadCallback(func(c *Config) {
  43. err := configLogger(c)
  44. if err != nil {
  45. l.WithError(err).Error("Failed to configure the logger")
  46. }
  47. })
  48. // trustedCAs is currently a global, so loadCA operates on that global directly
  49. trustedCAs, err = loadCAFromConfig(config)
  50. if err != nil {
  51. //The errors coming out of loadCA are already nicely formatted
  52. l.WithError(err).Fatal("Failed to load ca from config")
  53. }
  54. l.WithField("fingerprints", trustedCAs.GetFingerprints()).Debug("Trusted CA fingerprints")
  55. cs, err := NewCertStateFromConfig(config)
  56. if err != nil {
  57. //The errors coming out of NewCertStateFromConfig are already nicely formatted
  58. l.WithError(err).Fatal("Failed to load certificate from config")
  59. }
  60. l.WithField("cert", cs.certificate).Debug("Client nebula certificate")
  61. fw, err := NewFirewallFromConfig(cs.certificate, config)
  62. if err != nil {
  63. l.WithError(err).Fatal("Error while loading firewall rules")
  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 := parseRoutes(config, tunCidr)
  69. if err != nil {
  70. l.WithError(err).Fatal("Could not parse tun.routes")
  71. }
  72. unsafeRoutes, err := parseUnsafeRoutes(config, tunCidr)
  73. if err != nil {
  74. l.WithError(err).Fatal("Could not parse tun.unsafe_routes")
  75. }
  76. ssh, err := sshd.NewSSHServer(l.WithField("subsystem", "sshd"))
  77. wireSSHReload(ssh, config)
  78. if config.GetBool("sshd.enabled", false) {
  79. err = configSSH(ssh, config)
  80. if err != nil {
  81. l.WithError(err).Fatal("Error while configuring the sshd")
  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 tun *Tun
  89. if !configTest {
  90. config.CatchHUP()
  91. // set up our tun dev
  92. tun, err = newTun(
  93. config.GetString("tun.dev", ""),
  94. tunCidr,
  95. config.GetInt("tun.mtu", DEFAULT_MTU),
  96. routes,
  97. unsafeRoutes,
  98. config.GetInt("tun.tx_queue", 500),
  99. )
  100. if err != nil {
  101. l.WithError(err).Fatal("Failed to get a tun/tap device")
  102. }
  103. }
  104. // set up our UDP listener
  105. udpQueues := config.GetInt("listen.routines", 1)
  106. var udpServer *udpConn
  107. if !configTest {
  108. udpServer, err = NewListener(config.GetString("listen.host", "0.0.0.0"), config.GetInt("listen.port", 0), udpQueues > 1)
  109. if err != nil {
  110. l.WithError(err).Fatal("Failed to open udp listener")
  111. }
  112. udpServer.reloadConfig(config)
  113. }
  114. // Set up my internal host map
  115. var preferredRanges []*net.IPNet
  116. rawPreferredRanges := config.GetStringSlice("preferred_ranges", []string{})
  117. // First, check if 'preferred_ranges' is set and fallback to 'local_range'
  118. if len(rawPreferredRanges) > 0 {
  119. for _, rawPreferredRange := range rawPreferredRanges {
  120. _, preferredRange, err := net.ParseCIDR(rawPreferredRange)
  121. if err != nil {
  122. l.WithError(err).Fatal("Failed to parse preferred ranges")
  123. }
  124. preferredRanges = append(preferredRanges, preferredRange)
  125. }
  126. }
  127. // local_range was superseded by preferred_ranges. If it is still present,
  128. // merge the local_range setting into preferred_ranges. We will probably
  129. // deprecate local_range and remove in the future.
  130. rawLocalRange := config.GetString("local_range", "")
  131. if rawLocalRange != "" {
  132. _, localRange, err := net.ParseCIDR(rawLocalRange)
  133. if err != nil {
  134. l.WithError(err).Fatal("Failed to parse local range")
  135. }
  136. // Check if the entry for local_range was already specified in
  137. // preferred_ranges. Don't put it into the slice twice if so.
  138. var found bool
  139. for _, r := range preferredRanges {
  140. if r.String() == localRange.String() {
  141. found = true
  142. break
  143. }
  144. }
  145. if !found {
  146. preferredRanges = append(preferredRanges, localRange)
  147. }
  148. }
  149. hostMap := NewHostMap("main", tunCidr, preferredRanges)
  150. hostMap.SetDefaultRoute(ip2int(net.ParseIP(config.GetString("default_route", "0.0.0.0"))))
  151. hostMap.addUnsafeRoutes(&unsafeRoutes)
  152. hostMap.metricsEnabled = config.GetBool("stats.message_metrics", false)
  153. l.WithField("network", hostMap.vpnCIDR).WithField("preferredRanges", hostMap.preferredRanges).Info("Main HostMap created")
  154. /*
  155. config.SetDefault("promoter.interval", 10)
  156. go hostMap.Promoter(config.GetInt("promoter.interval"))
  157. */
  158. punchy := NewPunchyFromConfig(config)
  159. if punchy.Punch && !configTest {
  160. l.Info("UDP hole punching enabled")
  161. go hostMap.Punchy(udpServer)
  162. }
  163. port := config.GetInt("listen.port", 0)
  164. // If port is dynamic, discover it
  165. if port == 0 && !configTest {
  166. uPort, err := udpServer.LocalAddr()
  167. if err != nil {
  168. l.WithError(err).Fatal("Failed to get listening port")
  169. }
  170. port = int(uPort.Port)
  171. }
  172. amLighthouse := config.GetBool("lighthouse.am_lighthouse", false)
  173. // warn if am_lighthouse is enabled but upstream lighthouses exists
  174. rawLighthouseHosts := config.GetStringSlice("lighthouse.hosts", []string{})
  175. if amLighthouse && len(rawLighthouseHosts) != 0 {
  176. l.Warn("lighthouse.am_lighthouse enabled on node but upstream lighthouses exist in config")
  177. }
  178. lighthouseHosts := make([]uint32, len(rawLighthouseHosts))
  179. for i, host := range rawLighthouseHosts {
  180. ip := net.ParseIP(host)
  181. if ip == nil {
  182. l.WithField("host", host).Fatalf("Unable to parse lighthouse host entry %v", i+1)
  183. }
  184. if !tunCidr.Contains(ip) {
  185. l.WithField("vpnIp", ip).WithField("network", tunCidr.String()).Fatalf("lighthouse host is not in our subnet, invalid")
  186. }
  187. lighthouseHosts[i] = ip2int(ip)
  188. }
  189. lightHouse := NewLightHouse(
  190. amLighthouse,
  191. ip2int(tunCidr.IP),
  192. lighthouseHosts,
  193. //TODO: change to a duration
  194. config.GetInt("lighthouse.interval", 10),
  195. port,
  196. udpServer,
  197. punchy.Respond,
  198. punchy.Delay,
  199. config.GetBool("stats.lighthouse_metrics", false),
  200. )
  201. remoteAllowList, err := config.GetAllowList("lighthouse.remote_allow_list", false)
  202. if err != nil {
  203. l.WithError(err).Fatal("Invalid lighthouse.remote_allow_list")
  204. }
  205. lightHouse.SetRemoteAllowList(remoteAllowList)
  206. localAllowList, err := config.GetAllowList("lighthouse.local_allow_list", true)
  207. if err != nil {
  208. l.WithError(err).Fatal("Invalid lighthouse.local_allow_list")
  209. }
  210. lightHouse.SetLocalAllowList(localAllowList)
  211. //TODO: Move all of this inside functions in lighthouse.go
  212. for k, v := range config.GetMap("static_host_map", map[interface{}]interface{}{}) {
  213. vpnIp := net.ParseIP(fmt.Sprintf("%v", k))
  214. if !tunCidr.Contains(vpnIp) {
  215. l.WithField("vpnIp", vpnIp).WithField("network", tunCidr.String()).Fatalf("static_host_map key is not in our subnet, invalid")
  216. }
  217. vals, ok := v.([]interface{})
  218. if ok {
  219. for _, v := range vals {
  220. parts := strings.Split(fmt.Sprintf("%v", v), ":")
  221. addr, err := net.ResolveIPAddr("ip", parts[0])
  222. if err == nil {
  223. ip := addr.IP
  224. port, err := strconv.Atoi(parts[1])
  225. if err != nil {
  226. l.Fatalf("Static host address for %s could not be parsed: %s", vpnIp, v)
  227. }
  228. lightHouse.AddRemote(ip2int(vpnIp), NewUDPAddr(ip2int(ip), uint16(port)), true)
  229. }
  230. }
  231. } else {
  232. //TODO: make this all a helper
  233. parts := strings.Split(fmt.Sprintf("%v", v), ":")
  234. addr, err := net.ResolveIPAddr("ip", parts[0])
  235. if err == nil {
  236. ip := addr.IP
  237. port, err := strconv.Atoi(parts[1])
  238. if err != nil {
  239. l.Fatalf("Static host address for %s could not be parsed: %s", vpnIp, v)
  240. }
  241. lightHouse.AddRemote(ip2int(vpnIp), NewUDPAddr(ip2int(ip), uint16(port)), true)
  242. }
  243. }
  244. }
  245. err = lightHouse.ValidateLHStaticEntries()
  246. if err != nil {
  247. l.WithError(err).Error("Lighthouse unreachable")
  248. }
  249. var messageMetrics *MessageMetrics
  250. if config.GetBool("stats.message_metrics", false) {
  251. messageMetrics = newMessageMetrics()
  252. } else {
  253. messageMetrics = newMessageMetricsOnlyRecvError()
  254. }
  255. handshakeConfig := HandshakeConfig{
  256. tryInterval: config.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
  257. retries: config.GetInt("handshakes.retries", DefaultHandshakeRetries),
  258. waitRotation: config.GetInt("handshakes.wait_rotation", DefaultHandshakeWaitRotation),
  259. messageMetrics: messageMetrics,
  260. }
  261. handshakeManager := NewHandshakeManager(tunCidr, preferredRanges, hostMap, lightHouse, udpServer, handshakeConfig)
  262. //TODO: These will be reused for psk
  263. //handshakeMACKey := config.GetString("handshake_mac.key", "")
  264. //handshakeAcceptedMACKeys := config.GetStringSlice("handshake_mac.accepted_keys", []string{})
  265. serveDns := config.GetBool("lighthouse.serve_dns", false)
  266. checkInterval := config.GetInt("timers.connection_alive_interval", 5)
  267. pendingDeletionInterval := config.GetInt("timers.pending_deletion_interval", 10)
  268. ifConfig := &InterfaceConfig{
  269. HostMap: hostMap,
  270. Inside: tun,
  271. Outside: udpServer,
  272. certState: cs,
  273. Cipher: config.GetString("cipher", "aes"),
  274. Firewall: fw,
  275. ServeDns: serveDns,
  276. HandshakeManager: handshakeManager,
  277. lightHouse: lightHouse,
  278. checkInterval: checkInterval,
  279. pendingDeletionInterval: pendingDeletionInterval,
  280. DropLocalBroadcast: config.GetBool("tun.drop_local_broadcast", false),
  281. DropMulticast: config.GetBool("tun.drop_multicast", false),
  282. UDPBatchSize: config.GetInt("listen.batch", 64),
  283. MessageMetrics: messageMetrics,
  284. }
  285. switch ifConfig.Cipher {
  286. case "aes":
  287. noiseEndianness = binary.BigEndian
  288. case "chachapoly":
  289. noiseEndianness = binary.LittleEndian
  290. default:
  291. l.Fatalf("Unknown cipher: %v", ifConfig.Cipher)
  292. }
  293. var ifce *Interface
  294. if !configTest {
  295. ifce, err = NewInterface(ifConfig)
  296. if err != nil {
  297. l.WithError(err).Fatal("Failed to initialize interface")
  298. }
  299. ifce.RegisterConfigChangeCallbacks(config)
  300. go handshakeManager.Run(ifce)
  301. go lightHouse.LhUpdateWorker(ifce)
  302. }
  303. err = startStats(config, configTest)
  304. if err != nil {
  305. l.WithError(err).Fatal("Failed to start stats emitter")
  306. }
  307. if configTest {
  308. os.Exit(0)
  309. }
  310. //TODO: check if we _should_ be emitting stats
  311. go ifce.emitStats(config.GetDuration("stats.interval", time.Second*10))
  312. attachCommands(ssh, hostMap, handshakeManager.pendingHostMap, lightHouse, ifce)
  313. ifce.Run(config.GetInt("tun.routines", 1), udpQueues, buildVersion)
  314. // Start DNS server last to allow using the nebula IP as lighthouse.dns.host
  315. if amLighthouse && serveDns {
  316. l.Debugln("Starting dns server")
  317. go dnsMain(hostMap, config)
  318. }
  319. // Just sit here and be friendly, main thread.
  320. shutdownBlock(ifce)
  321. }
  322. func shutdownBlock(ifce *Interface) {
  323. var sigChan = make(chan os.Signal)
  324. signal.Notify(sigChan, syscall.SIGTERM)
  325. signal.Notify(sigChan, syscall.SIGINT)
  326. sig := <-sigChan
  327. l.WithField("signal", sig).Info("Caught signal, shutting down")
  328. //TODO: stop tun and udp routines, the lock on hostMap does effectively does that though
  329. //TODO: this is probably better as a function in ConnectionManager or HostMap directly
  330. ifce.hostMap.Lock()
  331. for _, h := range ifce.hostMap.Hosts {
  332. if h.ConnectionState.ready {
  333. ifce.send(closeTunnel, 0, h.ConnectionState, h, h.remote, []byte{}, make([]byte, 12, 12), make([]byte, mtu))
  334. l.WithField("vpnIp", IntIp(h.hostId)).WithField("udpAddr", h.remote).
  335. Debug("Sending close tunnel message")
  336. }
  337. }
  338. ifce.hostMap.Unlock()
  339. l.WithField("signal", sig).Info("Goodbye")
  340. os.Exit(0)
  341. }