main.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. package main
  2. import (
  3. "context"
  4. "crypto/ed25519"
  5. "crypto/rand"
  6. "errors"
  7. "flag"
  8. "fmt"
  9. "os"
  10. "os/signal"
  11. "runtime/debug"
  12. "strconv"
  13. "sync"
  14. "syscall"
  15. "time"
  16. "github.com/gravitl/netmaker/auth"
  17. "github.com/gravitl/netmaker/config"
  18. controller "github.com/gravitl/netmaker/controllers"
  19. "github.com/gravitl/netmaker/database"
  20. "github.com/gravitl/netmaker/functions"
  21. "github.com/gravitl/netmaker/logger"
  22. "github.com/gravitl/netmaker/logic"
  23. "github.com/gravitl/netmaker/models"
  24. "github.com/gravitl/netmaker/mq"
  25. "github.com/gravitl/netmaker/netclient/ncutils"
  26. "github.com/gravitl/netmaker/servercfg"
  27. "github.com/gravitl/netmaker/serverctl"
  28. "github.com/gravitl/netmaker/tls"
  29. )
  30. var version = "dev"
  31. // Start DB Connection and start API Request Handler
  32. func main() {
  33. absoluteConfigPath := flag.String("c", "", "absolute path to configuration file")
  34. flag.Parse()
  35. setupConfig(*absoluteConfigPath)
  36. servercfg.SetVersion(version)
  37. fmt.Println(models.RetrieveLogo()) // print the logo
  38. initialize() // initial db and acls; gen cert if required
  39. setGarbageCollection()
  40. defer database.CloseDB()
  41. startControllers() // start the api endpoint and mq
  42. }
  43. func setupConfig(absoluteConfigPath string) {
  44. if len(absoluteConfigPath) > 0 {
  45. cfg, err := config.ReadConfig(absoluteConfigPath)
  46. if err != nil {
  47. logger.Log(0, fmt.Sprintf("failed parsing config at: %s", absoluteConfigPath))
  48. return
  49. }
  50. config.Config = cfg
  51. }
  52. }
  53. func initialize() { // Client Mode Prereq Check
  54. var err error
  55. if servercfg.GetMasterKey() == "" {
  56. logger.Log(0, "warning: MASTER_KEY not set, this could make account recovery difficult")
  57. }
  58. if servercfg.GetNodeID() == "" {
  59. logger.FatalLog("error: must set NODE_ID, currently blank")
  60. }
  61. if err = database.InitializeDatabase(); err != nil {
  62. logger.FatalLog("Error connecting to database")
  63. }
  64. logger.Log(0, "database successfully connected")
  65. logic.SetJWTSecret()
  66. err = logic.TimerCheckpoint()
  67. if err != nil {
  68. logger.Log(1, "Timer error occurred: ", err.Error())
  69. }
  70. var authProvider = auth.InitializeAuthProvider()
  71. if authProvider != "" {
  72. logger.Log(0, "OAuth provider,", authProvider+",", "initialized")
  73. } else {
  74. logger.Log(0, "no OAuth provider found or not configured, continuing without OAuth")
  75. }
  76. err = serverctl.SetDefaultACLS()
  77. if err != nil {
  78. logger.FatalLog("error setting default acls: ", err.Error())
  79. }
  80. if servercfg.IsClientMode() != "off" {
  81. output, err := ncutils.RunCmd("id -u", true)
  82. if err != nil {
  83. logger.FatalLog("Error running 'id -u' for prereq check. Please investigate or disable client mode.", output, err.Error())
  84. }
  85. uid, err := strconv.Atoi(string(output[:len(output)-1]))
  86. if err != nil {
  87. logger.FatalLog("Error retrieving uid from 'id -u' for prereq check. Please investigate or disable client mode.", err.Error())
  88. }
  89. if uid != 0 {
  90. logger.FatalLog("To run in client mode requires root privileges. Either disable client mode or run with sudo.")
  91. }
  92. if err := serverctl.InitServerNetclient(); err != nil {
  93. logger.FatalLog("Did not find netclient to use CLIENT_MODE")
  94. }
  95. }
  96. // initialize iptables to ensure gateways work correctly and mq is forwarded if containerized
  97. if servercfg.ManageIPTables() != "off" {
  98. if err = serverctl.InitIPTables(true); err != nil {
  99. logger.FatalLog("Unable to initialize iptables on host:", err.Error())
  100. }
  101. }
  102. if servercfg.IsDNSMode() {
  103. err := functions.SetDNSDir()
  104. if err != nil {
  105. logger.FatalLog(err.Error())
  106. }
  107. }
  108. if err = genCerts(); err != nil {
  109. logger.Log(0, "something went wrong when generating broker certs", err.Error())
  110. }
  111. if servercfg.IsMessageQueueBackend() {
  112. if err = mq.ServerStartNotify(); err != nil {
  113. logger.Log(0, "error occurred when notifying nodes of startup", err.Error())
  114. }
  115. }
  116. logic.InitalizeZombies()
  117. }
  118. func startControllers() {
  119. var waitnetwork sync.WaitGroup
  120. if servercfg.IsDNSMode() {
  121. err := logic.SetDNS()
  122. if err != nil {
  123. logger.Log(0, "error occurred initializing DNS: ", err.Error())
  124. }
  125. }
  126. //Run Rest Server
  127. if servercfg.IsRestBackend() {
  128. if !servercfg.DisableRemoteIPCheck() && servercfg.GetAPIHost() == "127.0.0.1" {
  129. err := servercfg.SetHost()
  130. if err != nil {
  131. logger.FatalLog("Unable to Set host. Exiting...", err.Error())
  132. }
  133. }
  134. waitnetwork.Add(1)
  135. go controller.HandleRESTRequests(&waitnetwork)
  136. }
  137. //Run MessageQueue
  138. if servercfg.IsMessageQueueBackend() {
  139. waitnetwork.Add(1)
  140. go runMessageQueue(&waitnetwork)
  141. }
  142. if !servercfg.IsAgentBackend() && !servercfg.IsRestBackend() && !servercfg.IsMessageQueueBackend() {
  143. logger.Log(0, "No Server Mode selected, so nothing is being served! Set Agent mode (AGENT_BACKEND) or Rest mode (REST_BACKEND) or MessageQueue (MESSAGEQUEUE_BACKEND) to 'true'.")
  144. }
  145. waitnetwork.Wait()
  146. }
  147. // Should we be using a context vice a waitgroup????????????
  148. func runMessageQueue(wg *sync.WaitGroup) {
  149. defer wg.Done()
  150. logger.Log(0, "connecting to mq broker at", servercfg.GetMessageQueueEndpoint())
  151. var client = mq.SetupMQTT(false) // Set up the subscription listener
  152. ctx, cancel := context.WithCancel(context.Background())
  153. go mq.Keepalive(ctx)
  154. go logic.ManageZombies(ctx)
  155. quit := make(chan os.Signal, 1)
  156. signal.Notify(quit, syscall.SIGTERM, os.Interrupt)
  157. <-quit
  158. cancel()
  159. logger.Log(0, "Message Queue shutting down")
  160. client.Disconnect(250)
  161. }
  162. func setGarbageCollection() {
  163. _, gcset := os.LookupEnv("GOGC")
  164. if !gcset {
  165. debug.SetGCPercent(ncutils.DEFAULT_GC_PERCENT)
  166. }
  167. }
  168. func genCerts() error {
  169. logger.Log(0, "checking keys and certificates")
  170. var private *ed25519.PrivateKey
  171. var err error
  172. // == ROOT key handling ==
  173. private, err = serverctl.ReadKeyFromDB(tls.ROOT_KEY_NAME)
  174. if errors.Is(err, os.ErrNotExist) || database.IsEmptyRecord(err) {
  175. logger.Log(0, "generating new root key")
  176. _, newKey, err := ed25519.GenerateKey(rand.Reader)
  177. if err != nil {
  178. return err
  179. }
  180. private = &newKey
  181. } else if err != nil {
  182. return err
  183. }
  184. logger.Log(2, "saving root.key")
  185. if err := serverctl.SaveKey(functions.GetNetmakerPath()+ncutils.GetSeparator(), tls.ROOT_KEY_NAME, *private); err != nil {
  186. return err
  187. }
  188. // == ROOT cert handling ==
  189. ca, err := serverctl.ReadCertFromDB(tls.ROOT_PEM_NAME)
  190. //if cert doesn't exist or will expire within 10 days --- but can't do this as clients won't be able to connect
  191. //if errors.Is(err, os.ErrNotExist) || cert.NotAfter.Before(time.Now().Add(time.Hour*24*10)) {
  192. if errors.Is(err, os.ErrNotExist) || database.IsEmptyRecord(err) || ca.NotAfter.Before(time.Now().Add(time.Hour*24*10)) {
  193. logger.Log(0, "generating new root CA")
  194. caName := tls.NewName("CA Root", "US", "Gravitl")
  195. csr, err := tls.NewCSR(*private, caName)
  196. if err != nil {
  197. return err
  198. }
  199. rootCA, err := tls.SelfSignedCA(*private, csr, tls.CERTIFICATE_VALIDITY)
  200. if err != nil {
  201. return err
  202. }
  203. ca = rootCA
  204. } else if err != nil {
  205. return err
  206. }
  207. logger.Log(2, "saving root.pem")
  208. if err := serverctl.SaveCert(functions.GetNetmakerPath()+ncutils.GetSeparator(), tls.ROOT_PEM_NAME, ca); err != nil {
  209. return err
  210. }
  211. // == SERVER cert handling ==
  212. cert, err := serverctl.ReadCertFromDB(tls.SERVER_PEM_NAME)
  213. if errors.Is(err, os.ErrNotExist) || database.IsEmptyRecord(err) || cert.NotAfter.Before(time.Now().Add(time.Hour*24*10)) {
  214. //gen new key
  215. logger.Log(0, "generating new server key/certificate")
  216. _, key, err := ed25519.GenerateKey(rand.Reader)
  217. if err != nil {
  218. return err
  219. }
  220. serverName := tls.NewCName(servercfg.GetServer())
  221. csr, err := tls.NewCSR(key, serverName)
  222. if err != nil {
  223. return err
  224. }
  225. newCert, err := tls.NewEndEntityCert(*private, csr, ca, tls.CERTIFICATE_VALIDITY)
  226. if err != nil {
  227. return err
  228. }
  229. if err := serverctl.SaveKey(functions.GetNetmakerPath()+ncutils.GetSeparator(), tls.SERVER_KEY_NAME, key); err != nil {
  230. return err
  231. }
  232. cert = newCert
  233. } else if err != nil {
  234. return err
  235. } else if err == nil {
  236. if serverKey, err := serverctl.ReadKeyFromDB(tls.SERVER_KEY_NAME); err == nil {
  237. logger.Log(2, "saving server.key")
  238. if err := serverctl.SaveKey(functions.GetNetmakerPath()+ncutils.GetSeparator(), tls.SERVER_KEY_NAME, *serverKey); err != nil {
  239. return err
  240. }
  241. } else {
  242. return err
  243. }
  244. }
  245. logger.Log(2, "saving server.pem")
  246. if err := serverctl.SaveCert(functions.GetNetmakerPath()+ncutils.GetSeparator(), tls.SERVER_PEM_NAME, cert); err != nil {
  247. return err
  248. }
  249. // == SERVER-CLIENT connection cert handling ==
  250. serverClientCert, err := serverctl.ReadCertFromDB(tls.SERVER_CLIENT_PEM)
  251. if errors.Is(err, os.ErrNotExist) || database.IsEmptyRecord(err) || serverClientCert.NotAfter.Before(time.Now().Add(time.Hour*24*10)) {
  252. //gen new key
  253. logger.Log(0, "generating new server client key/certificate")
  254. _, key, err := ed25519.GenerateKey(rand.Reader)
  255. if err != nil {
  256. return err
  257. }
  258. serverName := tls.NewCName(servercfg.GetServer())
  259. csr, err := tls.NewCSR(key, serverName)
  260. if err != nil {
  261. return err
  262. }
  263. newServerClientCert, err := tls.NewEndEntityCert(*private, csr, ca, tls.CERTIFICATE_VALIDITY)
  264. if err != nil {
  265. return err
  266. }
  267. if err := serverctl.SaveKey(functions.GetNetmakerPath()+ncutils.GetSeparator(), tls.SERVER_CLIENT_KEY, key); err != nil {
  268. return err
  269. }
  270. serverClientCert = newServerClientCert
  271. } else if err != nil {
  272. return err
  273. } else if err == nil {
  274. logger.Log(2, "saving serverclient.key")
  275. if serverClientKey, err := serverctl.ReadKeyFromDB(tls.SERVER_CLIENT_KEY); err == nil {
  276. if err := serverctl.SaveKey(functions.GetNetmakerPath()+ncutils.GetSeparator(), tls.SERVER_CLIENT_KEY, *serverClientKey); err != nil {
  277. return err
  278. }
  279. } else {
  280. return err
  281. }
  282. }
  283. logger.Log(2, "saving serverclient.pem")
  284. if err := serverctl.SaveCert(functions.GetNetmakerPath()+ncutils.GetSeparator(), tls.SERVER_CLIENT_PEM, serverClientCert); err != nil {
  285. return err
  286. }
  287. logger.Log(1, "ensure the root.pem, root.key, server.pem, and server.key files are updated on your broker")
  288. return serverctl.SetClientTLSConf(
  289. functions.GetNetmakerPath()+ncutils.GetSeparator()+tls.SERVER_CLIENT_PEM,
  290. functions.GetNetmakerPath()+ncutils.GetSeparator()+tls.SERVER_CLIENT_KEY,
  291. ca,
  292. )
  293. }