main.go 14 KB

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