main.go 12 KB

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