main.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. package nebula
  2. import (
  3. "context"
  4. "encoding/binary"
  5. "fmt"
  6. "net"
  7. "net/netip"
  8. "time"
  9. "github.com/sirupsen/logrus"
  10. "github.com/slackhq/nebula/config"
  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, deviceFactory overlay.DeviceFactory) (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.ContextualizeIfNeeded("Failed to configure the logger", 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. pki, err := NewPKIFromConfig(l, c)
  50. if err != nil {
  51. return nil, util.ContextualizeIfNeeded("Failed to load PKI from config", err)
  52. }
  53. certificate := pki.GetCertState().Certificate
  54. fw, err := NewFirewallFromConfig(l, certificate, c)
  55. if err != nil {
  56. return nil, util.ContextualizeIfNeeded("Error while loading firewall rules", err)
  57. }
  58. l.WithField("firewallHashes", fw.GetRuleHashes()).Info("Firewall started")
  59. ones, _ := certificate.Details.Ips[0].Mask.Size()
  60. addr, ok := netip.AddrFromSlice(certificate.Details.Ips[0].IP)
  61. if !ok {
  62. err = util.NewContextualError(
  63. "Invalid ip address in certificate",
  64. m{"vpnIp": certificate.Details.Ips[0].IP},
  65. nil,
  66. )
  67. return nil, err
  68. }
  69. tunCidr := netip.PrefixFrom(addr, ones)
  70. ssh, err := sshd.NewSSHServer(l.WithField("subsystem", "sshd"))
  71. if err != nil {
  72. return nil, util.ContextualizeIfNeeded("Error while creating SSH server", err)
  73. }
  74. wireSSHReload(l, ssh, c)
  75. var sshStart func()
  76. if c.GetBool("sshd.enabled", false) {
  77. sshStart, err = configSSH(l, ssh, c)
  78. if err != nil {
  79. return nil, util.ContextualizeIfNeeded("Error while configuring the sshd", err)
  80. }
  81. }
  82. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  83. // All non system modifying configuration consumption should live above this line
  84. // tun config, listeners, anything modifying the computer should be below
  85. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  86. var routines int
  87. // If `routines` is set, use that and ignore the specific values
  88. if routines = c.GetInt("routines", 0); routines != 0 {
  89. if routines < 1 {
  90. routines = 1
  91. }
  92. if routines > 1 {
  93. l.WithField("routines", routines).Info("Using multiple routines")
  94. }
  95. } else {
  96. // deprecated and undocumented
  97. tunQueues := c.GetInt("tun.routines", 1)
  98. udpQueues := c.GetInt("listen.routines", 1)
  99. if tunQueues > udpQueues {
  100. routines = tunQueues
  101. } else {
  102. routines = udpQueues
  103. }
  104. if routines != 1 {
  105. l.WithField("routines", routines).Warn("Setting tun.routines and listen.routines is deprecated. Use `routines` instead")
  106. }
  107. }
  108. // EXPERIMENTAL
  109. // Intentionally not documented yet while we do more testing and determine
  110. // a good default value.
  111. conntrackCacheTimeout := c.GetDuration("firewall.conntrack.routine_cache_timeout", 0)
  112. if routines > 1 && !c.IsSet("firewall.conntrack.routine_cache_timeout") {
  113. // Use a different default if we are running with multiple routines
  114. conntrackCacheTimeout = 1 * time.Second
  115. }
  116. if conntrackCacheTimeout > 0 {
  117. l.WithField("duration", conntrackCacheTimeout).Info("Using routine-local conntrack cache")
  118. }
  119. var tun overlay.Device
  120. if !configTest {
  121. c.CatchHUP(ctx)
  122. if deviceFactory == nil {
  123. deviceFactory = overlay.NewDeviceFromConfig
  124. }
  125. tun, err = deviceFactory(c, l, tunCidr, routines)
  126. if err != nil {
  127. return nil, util.ContextualizeIfNeeded("Failed to get a tun/tap device", err)
  128. }
  129. defer func() {
  130. if reterr != nil {
  131. tun.Close()
  132. }
  133. }()
  134. }
  135. // set up our UDP listener
  136. udpConns := make([]udp.Conn, routines)
  137. port := c.GetInt("listen.port", 0)
  138. if !configTest {
  139. rawListenHost := c.GetString("listen.host", "0.0.0.0")
  140. var listenHost netip.Addr
  141. if rawListenHost == "[::]" {
  142. // Old guidance was to provide the literal `[::]` in `listen.host` but that won't resolve.
  143. listenHost = netip.IPv6Unspecified()
  144. } else {
  145. ips, err := net.DefaultResolver.LookupNetIP(context.Background(), "ip", rawListenHost)
  146. if err != nil {
  147. return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
  148. }
  149. if len(ips) == 0 {
  150. return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
  151. }
  152. listenHost = ips[0].Unmap()
  153. }
  154. for i := 0; i < routines; i++ {
  155. l.Infof("listening on %v", netip.AddrPortFrom(listenHost, uint16(port)))
  156. udpServer, err := udp.NewListener(l, listenHost, port, routines > 1, c.GetInt("listen.batch", 64))
  157. if err != nil {
  158. return nil, util.NewContextualError("Failed to open udp listener", m{"queue": i}, err)
  159. }
  160. udpServer.ReloadConfig(c)
  161. udpConns[i] = udpServer
  162. // If port is dynamic, discover it before the next pass through the for loop
  163. // This way all routines will use the same port correctly
  164. if port == 0 {
  165. uPort, err := udpServer.LocalAddr()
  166. if err != nil {
  167. return nil, util.NewContextualError("Failed to get listening port", nil, err)
  168. }
  169. port = int(uPort.Port())
  170. }
  171. }
  172. }
  173. hostMap := NewHostMapFromConfig(l, tunCidr, c)
  174. punchy := NewPunchyFromConfig(l, c)
  175. lightHouse, err := NewLightHouseFromConfig(ctx, l, c, tunCidr, udpConns[0], punchy)
  176. if err != nil {
  177. return nil, util.ContextualizeIfNeeded("Failed to initialize lighthouse handler", err)
  178. }
  179. var messageMetrics *MessageMetrics
  180. if c.GetBool("stats.message_metrics", false) {
  181. messageMetrics = newMessageMetrics()
  182. } else {
  183. messageMetrics = newMessageMetricsOnlyRecvError()
  184. }
  185. useRelays := c.GetBool("relay.use_relays", DefaultUseRelays) && !c.GetBool("relay.am_relay", false)
  186. handshakeConfig := HandshakeConfig{
  187. tryInterval: c.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
  188. retries: int64(c.GetInt("handshakes.retries", DefaultHandshakeRetries)),
  189. triggerBuffer: c.GetInt("handshakes.trigger_buffer", DefaultHandshakeTriggerBuffer),
  190. useRelays: useRelays,
  191. messageMetrics: messageMetrics,
  192. }
  193. handshakeManager := NewHandshakeManager(l, hostMap, lightHouse, udpConns[0], handshakeConfig)
  194. lightHouse.handshakeTrigger = handshakeManager.trigger
  195. serveDns := false
  196. if c.GetBool("lighthouse.serve_dns", false) {
  197. if c.GetBool("lighthouse.am_lighthouse", false) {
  198. serveDns = true
  199. } else {
  200. l.Warn("DNS server refusing to run because this host is not a lighthouse.")
  201. }
  202. }
  203. checkInterval := c.GetInt("timers.connection_alive_interval", 5)
  204. pendingDeletionInterval := c.GetInt("timers.pending_deletion_interval", 10)
  205. ifConfig := &InterfaceConfig{
  206. HostMap: hostMap,
  207. Inside: tun,
  208. Outside: udpConns[0],
  209. pki: pki,
  210. Cipher: c.GetString("cipher", "aes"),
  211. Firewall: fw,
  212. ServeDns: serveDns,
  213. HandshakeManager: handshakeManager,
  214. lightHouse: lightHouse,
  215. checkInterval: time.Second * time.Duration(checkInterval),
  216. pendingDeletionInterval: time.Second * time.Duration(pendingDeletionInterval),
  217. tryPromoteEvery: c.GetUint32("counters.try_promote", defaultPromoteEvery),
  218. reQueryEvery: c.GetUint32("counters.requery_every_packets", defaultReQueryEvery),
  219. reQueryWait: c.GetDuration("timers.requery_wait_duration", defaultReQueryWait),
  220. DropLocalBroadcast: c.GetBool("tun.drop_local_broadcast", false),
  221. DropMulticast: c.GetBool("tun.drop_multicast", false),
  222. routines: routines,
  223. MessageMetrics: messageMetrics,
  224. version: buildVersion,
  225. relayManager: NewRelayManager(ctx, l, hostMap, c),
  226. punchy: punchy,
  227. ConntrackCacheTimeout: conntrackCacheTimeout,
  228. l: l,
  229. }
  230. switch ifConfig.Cipher {
  231. case "aes":
  232. noiseEndianness = binary.BigEndian
  233. case "chachapoly":
  234. noiseEndianness = binary.LittleEndian
  235. default:
  236. return nil, fmt.Errorf("unknown cipher: %v", ifConfig.Cipher)
  237. }
  238. var ifce *Interface
  239. if !configTest {
  240. ifce, err = NewInterface(ctx, ifConfig)
  241. if err != nil {
  242. return nil, fmt.Errorf("failed to initialize interface: %s", err)
  243. }
  244. // TODO: Better way to attach these, probably want a new interface in InterfaceConfig
  245. // I don't want to make this initial commit too far-reaching though
  246. ifce.writers = udpConns
  247. lightHouse.ifce = ifce
  248. ifce.RegisterConfigChangeCallbacks(c)
  249. ifce.reloadDisconnectInvalid(c)
  250. ifce.reloadSendRecvError(c)
  251. handshakeManager.f = ifce
  252. go handshakeManager.Run(ctx)
  253. }
  254. // TODO - stats third-party modules start uncancellable goroutines. Update those libs to accept
  255. // a context so that they can exit when the context is Done.
  256. statsStart, err := startStats(l, c, buildVersion, configTest)
  257. if err != nil {
  258. return nil, util.ContextualizeIfNeeded("Failed to start stats emitter", err)
  259. }
  260. if configTest {
  261. return nil, nil
  262. }
  263. //TODO: check if we _should_ be emitting stats
  264. go ifce.emitStats(ctx, c.GetDuration("stats.interval", time.Second*10))
  265. attachCommands(l, c, ssh, ifce)
  266. // Start DNS server last to allow using the nebula IP as lighthouse.dns.host
  267. var dnsStart func()
  268. if lightHouse.amLighthouse && serveDns {
  269. l.Debugln("Starting dns server")
  270. dnsStart = dnsMain(l, hostMap, c)
  271. }
  272. return &Control{
  273. ifce,
  274. l,
  275. ctx,
  276. cancel,
  277. sshStart,
  278. statsStart,
  279. dnsStart,
  280. lightHouse.StartUpdateWorker,
  281. }, nil
  282. }