main.go 13 KB

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