main.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. var sshStart func()
  66. if config.GetBool("sshd.enabled", false) {
  67. sshStart, 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.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. tunCidr,
  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. return nil, NewContextualError("Static host address could not be parsed", m{"vpnIp": vpnIp}, err)
  266. }
  267. lightHouse.AddStaticRemote(ip2int(vpnIp), NewUDPAddr(ip, port))
  268. }
  269. } else {
  270. ip, port, err := parseIPAndPort(fmt.Sprintf("%v", v))
  271. if err != nil {
  272. return nil, NewContextualError("Static host address could not be parsed", m{"vpnIp": vpnIp}, err)
  273. }
  274. lightHouse.AddStaticRemote(ip2int(vpnIp), NewUDPAddr(ip, port))
  275. }
  276. }
  277. err = lightHouse.ValidateLHStaticEntries()
  278. if err != nil {
  279. l.WithError(err).Error("Lighthouse unreachable")
  280. }
  281. var messageMetrics *MessageMetrics
  282. if config.GetBool("stats.message_metrics", false) {
  283. messageMetrics = newMessageMetrics()
  284. } else {
  285. messageMetrics = newMessageMetricsOnlyRecvError()
  286. }
  287. handshakeConfig := HandshakeConfig{
  288. tryInterval: config.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
  289. retries: config.GetInt("handshakes.retries", DefaultHandshakeRetries),
  290. triggerBuffer: config.GetInt("handshakes.trigger_buffer", DefaultHandshakeTriggerBuffer),
  291. messageMetrics: messageMetrics,
  292. }
  293. handshakeManager := NewHandshakeManager(l, tunCidr, preferredRanges, hostMap, lightHouse, udpConns[0], handshakeConfig)
  294. lightHouse.handshakeTrigger = handshakeManager.trigger
  295. //TODO: These will be reused for psk
  296. //handshakeMACKey := config.GetString("handshake_mac.key", "")
  297. //handshakeAcceptedMACKeys := config.GetStringSlice("handshake_mac.accepted_keys", []string{})
  298. serveDns := config.GetBool("lighthouse.serve_dns", false)
  299. checkInterval := config.GetInt("timers.connection_alive_interval", 5)
  300. pendingDeletionInterval := config.GetInt("timers.pending_deletion_interval", 10)
  301. ifConfig := &InterfaceConfig{
  302. HostMap: hostMap,
  303. Inside: tun,
  304. Outside: udpConns[0],
  305. certState: cs,
  306. Cipher: config.GetString("cipher", "aes"),
  307. Firewall: fw,
  308. ServeDns: serveDns,
  309. HandshakeManager: handshakeManager,
  310. lightHouse: lightHouse,
  311. checkInterval: checkInterval,
  312. pendingDeletionInterval: pendingDeletionInterval,
  313. DropLocalBroadcast: config.GetBool("tun.drop_local_broadcast", false),
  314. DropMulticast: config.GetBool("tun.drop_multicast", false),
  315. UDPBatchSize: config.GetInt("listen.batch", 64),
  316. routines: routines,
  317. MessageMetrics: messageMetrics,
  318. version: buildVersion,
  319. caPool: caPool,
  320. ConntrackCacheTimeout: conntrackCacheTimeout,
  321. l: l,
  322. }
  323. switch ifConfig.Cipher {
  324. case "aes":
  325. noiseEndianness = binary.BigEndian
  326. case "chachapoly":
  327. noiseEndianness = binary.LittleEndian
  328. default:
  329. return nil, fmt.Errorf("unknown cipher: %v", ifConfig.Cipher)
  330. }
  331. var ifce *Interface
  332. if !configTest {
  333. ifce, err = NewInterface(ifConfig)
  334. if err != nil {
  335. return nil, fmt.Errorf("failed to initialize interface: %s", err)
  336. }
  337. // TODO: Better way to attach these, probably want a new interface in InterfaceConfig
  338. // I don't want to make this initial commit too far-reaching though
  339. ifce.writers = udpConns
  340. ifce.RegisterConfigChangeCallbacks(config)
  341. go handshakeManager.Run(ifce)
  342. go lightHouse.LhUpdateWorker(ifce)
  343. }
  344. statsStart, err := startStats(l, config, buildVersion, configTest)
  345. if err != nil {
  346. return nil, NewContextualError("Failed to start stats emitter", nil, err)
  347. }
  348. if configTest {
  349. return nil, nil
  350. }
  351. //TODO: check if we _should_ be emitting stats
  352. go ifce.emitStats(config.GetDuration("stats.interval", time.Second*10))
  353. attachCommands(l, ssh, hostMap, handshakeManager.pendingHostMap, lightHouse, ifce)
  354. // Start DNS server last to allow using the nebula IP as lighthouse.dns.host
  355. var dnsStart func()
  356. if amLighthouse && serveDns {
  357. l.Debugln("Starting dns server")
  358. dnsStart = dnsMain(l, hostMap, config)
  359. }
  360. return &Control{ifce, l, sshStart, statsStart, dnsStart}, nil
  361. }