main.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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.addUnsafeRoutes(&unsafeRoutes)
  198. hostMap.metricsEnabled = config.GetBool("stats.message_metrics", false)
  199. l.WithField("network", hostMap.vpnCIDR).WithField("preferredRanges", hostMap.preferredRanges).Info("Main HostMap created")
  200. /*
  201. config.SetDefault("promoter.interval", 10)
  202. go hostMap.Promoter(config.GetInt("promoter.interval"))
  203. */
  204. punchy := NewPunchyFromConfig(config)
  205. if punchy.Punch && !configTest {
  206. l.Info("UDP hole punching enabled")
  207. go hostMap.Punchy(udpConns[0])
  208. }
  209. amLighthouse := config.GetBool("lighthouse.am_lighthouse", false)
  210. // fatal if am_lighthouse is enabled but we are using an ephemeral port
  211. if amLighthouse && (config.GetInt("listen.port", 0) == 0) {
  212. return nil, NewContextualError("lighthouse.am_lighthouse enabled on node but no port number is set in config", nil, nil)
  213. }
  214. // warn if am_lighthouse is enabled but upstream lighthouses exists
  215. rawLighthouseHosts := config.GetStringSlice("lighthouse.hosts", []string{})
  216. if amLighthouse && len(rawLighthouseHosts) != 0 {
  217. l.Warn("lighthouse.am_lighthouse enabled on node but upstream lighthouses exist in config")
  218. }
  219. lighthouseHosts := make([]uint32, len(rawLighthouseHosts))
  220. for i, host := range rawLighthouseHosts {
  221. ip := net.ParseIP(host)
  222. if ip == nil {
  223. return nil, NewContextualError("Unable to parse lighthouse host entry", m{"host": host, "entry": i + 1}, nil)
  224. }
  225. if !tunCidr.Contains(ip) {
  226. return nil, NewContextualError("lighthouse host is not in our subnet, invalid", m{"vpnIp": ip, "network": tunCidr.String()}, nil)
  227. }
  228. lighthouseHosts[i] = ip2int(ip)
  229. }
  230. lightHouse := NewLightHouse(
  231. l,
  232. amLighthouse,
  233. tunCidr,
  234. lighthouseHosts,
  235. //TODO: change to a duration
  236. config.GetInt("lighthouse.interval", 10),
  237. uint32(port),
  238. udpConns[0],
  239. punchy.Respond,
  240. punchy.Delay,
  241. config.GetBool("stats.lighthouse_metrics", false),
  242. )
  243. remoteAllowList, err := config.GetAllowList("lighthouse.remote_allow_list", false)
  244. if err != nil {
  245. return nil, NewContextualError("Invalid lighthouse.remote_allow_list", nil, err)
  246. }
  247. lightHouse.SetRemoteAllowList(remoteAllowList)
  248. localAllowList, err := config.GetAllowList("lighthouse.local_allow_list", true)
  249. if err != nil {
  250. return nil, NewContextualError("Invalid lighthouse.local_allow_list", nil, err)
  251. }
  252. lightHouse.SetLocalAllowList(localAllowList)
  253. //TODO: Move all of this inside functions in lighthouse.go
  254. for k, v := range config.GetMap("static_host_map", map[interface{}]interface{}{}) {
  255. vpnIp := net.ParseIP(fmt.Sprintf("%v", k))
  256. if !tunCidr.Contains(vpnIp) {
  257. return nil, NewContextualError("static_host_map key is not in our subnet, invalid", m{"vpnIp": vpnIp, "network": tunCidr.String()}, nil)
  258. }
  259. vals, ok := v.([]interface{})
  260. if ok {
  261. for _, v := range vals {
  262. ip, port, err := parseIPAndPort(fmt.Sprintf("%v", v))
  263. if err != nil {
  264. return nil, NewContextualError("Static host address could not be parsed", m{"vpnIp": vpnIp}, err)
  265. }
  266. lightHouse.AddStaticRemote(ip2int(vpnIp), NewUDPAddr(ip, port))
  267. }
  268. } else {
  269. ip, port, err := parseIPAndPort(fmt.Sprintf("%v", v))
  270. if err != nil {
  271. return nil, NewContextualError("Static host address could not be parsed", m{"vpnIp": vpnIp}, err)
  272. }
  273. lightHouse.AddStaticRemote(ip2int(vpnIp), NewUDPAddr(ip, port))
  274. }
  275. }
  276. err = lightHouse.ValidateLHStaticEntries()
  277. if err != nil {
  278. l.WithError(err).Error("Lighthouse unreachable")
  279. }
  280. var messageMetrics *MessageMetrics
  281. if config.GetBool("stats.message_metrics", false) {
  282. messageMetrics = newMessageMetrics()
  283. } else {
  284. messageMetrics = newMessageMetricsOnlyRecvError()
  285. }
  286. handshakeConfig := HandshakeConfig{
  287. tryInterval: config.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
  288. retries: config.GetInt("handshakes.retries", DefaultHandshakeRetries),
  289. triggerBuffer: config.GetInt("handshakes.trigger_buffer", DefaultHandshakeTriggerBuffer),
  290. messageMetrics: messageMetrics,
  291. }
  292. handshakeManager := NewHandshakeManager(l, 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. caPool: caPool,
  319. ConntrackCacheTimeout: conntrackCacheTimeout,
  320. l: l,
  321. }
  322. switch ifConfig.Cipher {
  323. case "aes":
  324. noiseEndianness = binary.BigEndian
  325. case "chachapoly":
  326. noiseEndianness = binary.LittleEndian
  327. default:
  328. return nil, fmt.Errorf("unknown cipher: %v", ifConfig.Cipher)
  329. }
  330. var ifce *Interface
  331. if !configTest {
  332. ifce, err = NewInterface(ifConfig)
  333. if err != nil {
  334. return nil, fmt.Errorf("failed to initialize interface: %s", err)
  335. }
  336. // TODO: Better way to attach these, probably want a new interface in InterfaceConfig
  337. // I don't want to make this initial commit too far-reaching though
  338. ifce.writers = udpConns
  339. ifce.RegisterConfigChangeCallbacks(config)
  340. go handshakeManager.Run(ifce)
  341. go lightHouse.LhUpdateWorker(ifce)
  342. }
  343. err = startStats(l, config, buildVersion, configTest)
  344. if err != nil {
  345. return nil, NewContextualError("Failed to start stats emitter", nil, err)
  346. }
  347. if configTest {
  348. return nil, nil
  349. }
  350. //TODO: check if we _should_ be emitting stats
  351. go ifce.emitStats(config.GetDuration("stats.interval", time.Second*10))
  352. attachCommands(l, ssh, hostMap, handshakeManager.pendingHostMap, lightHouse, ifce)
  353. // Start DNS server last to allow using the nebula IP as lighthouse.dns.host
  354. if amLighthouse && serveDns {
  355. l.Debugln("Starting dns server")
  356. go dnsMain(l, hostMap, config)
  357. }
  358. return &Control{ifce, l}, nil
  359. }