main.go 14 KB

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