main.go 13 KB

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