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