serverconf.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. package servercfg
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "math/rand"
  7. "net"
  8. "net/http"
  9. "os"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/gravitl/netmaker/config"
  14. "github.com/gravitl/netmaker/logger"
  15. )
  16. var (
  17. Version = "dev"
  18. commsID = ""
  19. )
  20. // SetHost - sets the host ip
  21. func SetHost() error {
  22. remoteip, err := GetPublicIP()
  23. if err != nil {
  24. return err
  25. }
  26. os.Setenv("SERVER_HOST", remoteip)
  27. return nil
  28. }
  29. // GetServerConfig - gets the server config into memory from file or env
  30. func GetServerConfig() config.ServerConfig {
  31. var cfg config.ServerConfig
  32. cfg.APIConnString = GetAPIConnString()
  33. cfg.CoreDNSAddr = GetCoreDNSAddr()
  34. cfg.APIHost = GetAPIHost()
  35. cfg.APIPort = GetAPIPort()
  36. cfg.APIPort = GetAPIPort()
  37. cfg.MQPort = GetMQPort()
  38. cfg.GRPCHost = GetGRPCHost()
  39. cfg.GRPCPort = GetGRPCPort()
  40. cfg.GRPCConnString = GetGRPCConnString()
  41. cfg.MasterKey = "(hidden)"
  42. cfg.DNSKey = "(hidden)"
  43. cfg.AllowedOrigin = GetAllowedOrigin()
  44. cfg.RestBackend = "off"
  45. cfg.NodeID = GetNodeID()
  46. cfg.MQPort = GetMQPort()
  47. if IsRestBackend() {
  48. cfg.RestBackend = "on"
  49. }
  50. cfg.AgentBackend = "off"
  51. if IsAgentBackend() {
  52. cfg.AgentBackend = "on"
  53. }
  54. cfg.ClientMode = "off"
  55. if IsClientMode() != "off" {
  56. cfg.ClientMode = IsClientMode()
  57. }
  58. cfg.DNSMode = "off"
  59. if IsDNSMode() {
  60. cfg.DNSMode = "on"
  61. }
  62. cfg.DisplayKeys = "off"
  63. if IsDisplayKeys() {
  64. cfg.DisplayKeys = "on"
  65. }
  66. cfg.GRPCSSL = "off"
  67. if IsGRPCSSL() {
  68. cfg.GRPCSSL = "on"
  69. }
  70. cfg.DisableRemoteIPCheck = "off"
  71. if DisableRemoteIPCheck() {
  72. cfg.DisableRemoteIPCheck = "on"
  73. }
  74. cfg.Database = GetDB()
  75. cfg.Platform = GetPlatform()
  76. cfg.Version = GetVersion()
  77. // == auth config ==
  78. var authInfo = GetAuthProviderInfo()
  79. cfg.AuthProvider = authInfo[0]
  80. cfg.ClientID = authInfo[1]
  81. cfg.ClientSecret = authInfo[2]
  82. cfg.FrontendURL = GetFrontendURL()
  83. if GetRce() {
  84. cfg.RCE = "on"
  85. } else {
  86. cfg.RCE = "off"
  87. }
  88. cfg.Debug = GetDebug()
  89. cfg.Telemetry = Telemetry()
  90. cfg.ManageIPTables = ManageIPTables()
  91. services := strings.Join(GetPortForwardServiceList(), ",")
  92. cfg.PortForwardServices = services
  93. cfg.CommsID = GetCommsID()
  94. return cfg
  95. }
  96. // GetFrontendURL - gets the frontend url
  97. func GetFrontendURL() string {
  98. var frontend = ""
  99. if os.Getenv("FRONTEND_URL") != "" {
  100. frontend = os.Getenv("FRONTEND_URL")
  101. } else if config.Config.Server.FrontendURL != "" {
  102. frontend = config.Config.Server.FrontendURL
  103. }
  104. return frontend
  105. }
  106. // GetAPIConnString - gets the api connections string
  107. func GetAPIConnString() string {
  108. conn := ""
  109. if os.Getenv("SERVER_API_CONN_STRING") != "" {
  110. conn = os.Getenv("SERVER_API_CONN_STRING")
  111. } else if config.Config.Server.APIConnString != "" {
  112. conn = config.Config.Server.APIConnString
  113. }
  114. return conn
  115. }
  116. // SetVersion - set version of netmaker
  117. func SetVersion(v string) {
  118. Version = v
  119. }
  120. // GetVersion - version of netmaker
  121. func GetVersion() string {
  122. return Version
  123. }
  124. // GetDB - gets the database type
  125. func GetDB() string {
  126. database := "sqlite"
  127. if os.Getenv("DATABASE") != "" {
  128. database = os.Getenv("DATABASE")
  129. } else if config.Config.Server.Database != "" {
  130. database = config.Config.Server.Database
  131. }
  132. return database
  133. }
  134. // GetAPIHost - gets the api host
  135. func GetAPIHost() string {
  136. serverhost := "127.0.0.1"
  137. remoteip, _ := GetPublicIP()
  138. if os.Getenv("SERVER_HTTP_HOST") != "" {
  139. serverhost = os.Getenv("SERVER_HTTP_HOST")
  140. } else if config.Config.Server.APIHost != "" {
  141. serverhost = config.Config.Server.APIHost
  142. } else if os.Getenv("SERVER_HOST") != "" {
  143. serverhost = os.Getenv("SERVER_HOST")
  144. } else {
  145. if remoteip != "" {
  146. serverhost = remoteip
  147. }
  148. }
  149. return serverhost
  150. }
  151. // GetPodIP - get the pod's ip
  152. func GetPodIP() string {
  153. podip := "127.0.0.1"
  154. if os.Getenv("POD_IP") != "" {
  155. podip = os.Getenv("POD_IP")
  156. }
  157. return podip
  158. }
  159. // GetAPIPort - gets the api port
  160. func GetAPIPort() string {
  161. apiport := "8081"
  162. if os.Getenv("API_PORT") != "" {
  163. apiport = os.Getenv("API_PORT")
  164. } else if config.Config.Server.APIPort != "" {
  165. apiport = config.Config.Server.APIPort
  166. }
  167. return apiport
  168. }
  169. // GetDefaultNodeLimit - get node limit if one is set
  170. func GetDefaultNodeLimit() int32 {
  171. var limit int32
  172. limit = 999999999
  173. envlimit, err := strconv.Atoi(os.Getenv("DEFAULT_NODE_LIMIT"))
  174. if err == nil && envlimit != 0 {
  175. limit = int32(envlimit)
  176. } else if config.Config.Server.DefaultNodeLimit != 0 {
  177. limit = config.Config.Server.DefaultNodeLimit
  178. }
  179. return limit
  180. }
  181. // GetGRPCConnString - get grpc conn string
  182. func GetGRPCConnString() string {
  183. conn := ""
  184. if os.Getenv("SERVER_GRPC_CONN_STRING") != "" {
  185. conn = os.Getenv("SERVER_GRPC_CONN_STRING")
  186. } else if config.Config.Server.GRPCConnString != "" {
  187. conn = config.Config.Server.GRPCConnString
  188. } else {
  189. conn = GetGRPCHost() + ":" + GetGRPCPort()
  190. }
  191. return conn
  192. }
  193. // GetCoreDNSAddr - gets the core dns address
  194. func GetCoreDNSAddr() string {
  195. addr, _ := GetPublicIP()
  196. if os.Getenv("COREDNS_ADDR") != "" {
  197. addr = os.Getenv("COREDNS_ADDR")
  198. } else if config.Config.Server.CoreDNSAddr != "" {
  199. addr = config.Config.Server.GRPCConnString
  200. }
  201. return addr
  202. }
  203. // GetGRPCHost - get the grpc host url
  204. func GetGRPCHost() string {
  205. serverhost := "127.0.0.1"
  206. remoteip, _ := GetPublicIP()
  207. if os.Getenv("SERVER_GRPC_HOST") != "" {
  208. serverhost = os.Getenv("SERVER_GRPC_HOST")
  209. } else if config.Config.Server.GRPCHost != "" {
  210. serverhost = config.Config.Server.GRPCHost
  211. } else if os.Getenv("SERVER_HOST") != "" {
  212. serverhost = os.Getenv("SERVER_HOST")
  213. } else {
  214. if remoteip != "" {
  215. serverhost = remoteip
  216. }
  217. }
  218. return serverhost
  219. }
  220. // GetGRPCPort - gets the grpc port
  221. func GetGRPCPort() string {
  222. grpcport := "50051"
  223. if os.Getenv("GRPC_PORT") != "" {
  224. grpcport = os.Getenv("GRPC_PORT")
  225. } else if config.Config.Server.GRPCPort != "" {
  226. grpcport = config.Config.Server.GRPCPort
  227. }
  228. return grpcport
  229. }
  230. // GetMQPort - gets the mq port
  231. func GetMQPort() string {
  232. mqport := "1883"
  233. if os.Getenv("MQ_PORT") != "" {
  234. mqport = os.Getenv("MQ_PORT")
  235. } else if config.Config.Server.MQPort != "" {
  236. mqport = config.Config.Server.MQPort
  237. }
  238. return mqport
  239. }
  240. // GetGRPCPort - gets the grpc port
  241. func GetCommsCIDR() string {
  242. netrange := "172.16.0.0/16"
  243. if os.Getenv("COMMS_CIDR") != "" {
  244. netrange = os.Getenv("COMMS_CIDR")
  245. } else if config.Config.Server.CommsCIDR != "" {
  246. netrange = config.Config.Server.CommsCIDR
  247. } else { // make a random one, which should only affect initialize first time, unless db is removed
  248. netrange = genNewCommsCIDR()
  249. }
  250. _, _, err := net.ParseCIDR(netrange)
  251. if err == nil {
  252. return netrange
  253. }
  254. return "172.16.0.0/16"
  255. }
  256. // GetCommsID - gets the grpc port
  257. func GetCommsID() string {
  258. return commsID
  259. }
  260. // SetCommsID - sets the commsID
  261. func SetCommsID(newCommsID string) {
  262. commsID = newCommsID
  263. }
  264. // GetMessageQueueEndpoint - gets the message queue endpoint
  265. func GetMessageQueueEndpoint() string {
  266. host, _ := GetPublicIP()
  267. if os.Getenv("MQ_HOST") != "" {
  268. host = os.Getenv("MQ_HOST")
  269. } else if config.Config.Server.MQHOST != "" {
  270. host = config.Config.Server.MQHOST
  271. }
  272. //Do we want MQ port configurable???
  273. return host + ":1883"
  274. }
  275. // GetMasterKey - gets the configured master key of server
  276. func GetMasterKey() string {
  277. key := ""
  278. if os.Getenv("MASTER_KEY") != "" {
  279. key = os.Getenv("MASTER_KEY")
  280. } else if config.Config.Server.MasterKey != "" {
  281. key = config.Config.Server.MasterKey
  282. }
  283. return key
  284. }
  285. // GetDNSKey - gets the configured dns key of server
  286. func GetDNSKey() string {
  287. key := "secretkey"
  288. if os.Getenv("DNS_KEY") != "" {
  289. key = os.Getenv("DNS_KEY")
  290. } else if config.Config.Server.DNSKey != "" {
  291. key = config.Config.Server.DNSKey
  292. }
  293. return key
  294. }
  295. // GetAllowedOrigin - get the allowed origin
  296. func GetAllowedOrigin() string {
  297. allowedorigin := "*"
  298. if os.Getenv("CORS_ALLOWED_ORIGIN") != "" {
  299. allowedorigin = os.Getenv("CORS_ALLOWED_ORIGIN")
  300. } else if config.Config.Server.AllowedOrigin != "" {
  301. allowedorigin = config.Config.Server.AllowedOrigin
  302. }
  303. return allowedorigin
  304. }
  305. // IsRestBackend - checks if rest is on or off
  306. func IsRestBackend() bool {
  307. isrest := true
  308. if os.Getenv("REST_BACKEND") != "" {
  309. if os.Getenv("REST_BACKEND") == "off" {
  310. isrest = false
  311. }
  312. } else if config.Config.Server.RestBackend != "" {
  313. if config.Config.Server.RestBackend == "off" {
  314. isrest = false
  315. }
  316. }
  317. return isrest
  318. }
  319. // IsAgentBackend - checks if agent backed is on or off
  320. func IsAgentBackend() bool {
  321. isagent := true
  322. if os.Getenv("AGENT_BACKEND") != "" {
  323. if os.Getenv("AGENT_BACKEND") == "off" {
  324. isagent = false
  325. }
  326. } else if config.Config.Server.AgentBackend != "" {
  327. if config.Config.Server.AgentBackend == "off" {
  328. isagent = false
  329. }
  330. }
  331. return isagent
  332. }
  333. // IsMessageQueueBackend - checks if message queue is on or off
  334. func IsMessageQueueBackend() bool {
  335. ismessagequeue := true
  336. if os.Getenv("MESSAGEQUEUE_BACKEND") != "" {
  337. if os.Getenv("MESSAGEQUEUE_BACKEND") == "off" {
  338. ismessagequeue = false
  339. }
  340. } else if config.Config.Server.MessageQueueBackend != "" {
  341. if config.Config.Server.MessageQueueBackend == "off" {
  342. ismessagequeue = false
  343. }
  344. }
  345. return ismessagequeue
  346. }
  347. // IsClientMode - checks if it should run in client mode
  348. func IsClientMode() string {
  349. isclient := "on"
  350. if os.Getenv("CLIENT_MODE") == "off" {
  351. isclient = "off"
  352. }
  353. if config.Config.Server.ClientMode == "off" {
  354. isclient = "off"
  355. }
  356. return isclient
  357. }
  358. // Telemetry - checks if telemetry data should be sent
  359. func Telemetry() string {
  360. telemetry := "on"
  361. if os.Getenv("TELEMETRY") == "off" {
  362. telemetry = "off"
  363. }
  364. if config.Config.Server.Telemetry == "off" {
  365. telemetry = "off"
  366. }
  367. return telemetry
  368. }
  369. // ManageIPTables - checks if iptables should be manipulated on host
  370. func ManageIPTables() string {
  371. manage := "on"
  372. if os.Getenv("MANAGE_IPTABLES") == "off" {
  373. manage = "off"
  374. }
  375. if config.Config.Server.ManageIPTables == "off" {
  376. manage = "off"
  377. }
  378. return manage
  379. }
  380. // IsDNSMode - should it run with DNS
  381. func IsDNSMode() bool {
  382. isdns := true
  383. if os.Getenv("DNS_MODE") != "" {
  384. if os.Getenv("DNS_MODE") == "off" {
  385. isdns = false
  386. }
  387. } else if config.Config.Server.DNSMode != "" {
  388. if config.Config.Server.DNSMode == "off" {
  389. isdns = false
  390. }
  391. }
  392. return isdns
  393. }
  394. // IsDisplayKeys - should server be able to display keys?
  395. func IsDisplayKeys() bool {
  396. isdisplay := true
  397. if os.Getenv("DISPLAY_KEYS") != "" {
  398. if os.Getenv("DISPLAY_KEYS") == "off" {
  399. isdisplay = false
  400. }
  401. } else if config.Config.Server.DisplayKeys != "" {
  402. if config.Config.Server.DisplayKeys == "off" {
  403. isdisplay = false
  404. }
  405. }
  406. return isdisplay
  407. }
  408. // IsGRPCSSL - ssl grpc on or off
  409. func IsGRPCSSL() bool {
  410. isssl := false
  411. if os.Getenv("GRPC_SSL") != "" {
  412. if os.Getenv("GRPC_SSL") == "on" {
  413. isssl = true
  414. }
  415. } else if config.Config.Server.GRPCSSL != "" {
  416. if config.Config.Server.GRPCSSL == "on" {
  417. isssl = true
  418. }
  419. }
  420. return isssl
  421. }
  422. // DisableRemoteIPCheck - disable the remote ip check
  423. func DisableRemoteIPCheck() bool {
  424. disabled := false
  425. if os.Getenv("DISABLE_REMOTE_IP_CHECK") != "" {
  426. if os.Getenv("DISABLE_REMOTE_IP_CHECK") == "on" {
  427. disabled = true
  428. }
  429. } else if config.Config.Server.DisableRemoteIPCheck != "" {
  430. if config.Config.Server.DisableRemoteIPCheck == "on" {
  431. disabled = true
  432. }
  433. }
  434. return disabled
  435. }
  436. // GetPublicIP - gets public ip
  437. func GetPublicIP() (string, error) {
  438. endpoint := ""
  439. var err error
  440. iplist := []string{"https://ip.server.gravitl.com", "https://ifconfig.me", "https://api.ipify.org", "https://ipinfo.io/ip"}
  441. for _, ipserver := range iplist {
  442. resp, err := http.Get(ipserver)
  443. if err != nil {
  444. continue
  445. }
  446. defer resp.Body.Close()
  447. if resp.StatusCode == http.StatusOK {
  448. bodyBytes, err := io.ReadAll(resp.Body)
  449. if err != nil {
  450. continue
  451. }
  452. endpoint = string(bodyBytes)
  453. break
  454. }
  455. }
  456. if err == nil && endpoint == "" {
  457. err = errors.New("public address not found")
  458. }
  459. return endpoint, err
  460. }
  461. // GetPlatform - get the system type of server
  462. func GetPlatform() string {
  463. platform := "linux"
  464. if os.Getenv("PLATFORM") != "" {
  465. platform = os.Getenv("PLATFORM")
  466. } else if config.Config.Server.Platform != "" {
  467. platform = config.Config.Server.SQLConn
  468. }
  469. return platform
  470. }
  471. // GetIPForwardServiceList - get the list of services that the server should be forwarding
  472. func GetPortForwardServiceList() []string {
  473. //services := "mq,dns,ssh"
  474. services := ""
  475. if os.Getenv("PORT_FORWARD_SERVICES") != "" {
  476. services = os.Getenv("PORT_FORWARD_SERVICES")
  477. } else if config.Config.Server.PortForwardServices != "" {
  478. services = config.Config.Server.PortForwardServices
  479. }
  480. serviceSlice := strings.Split(services, ",")
  481. return serviceSlice
  482. }
  483. // GetSQLConn - get the sql connection string
  484. func GetSQLConn() string {
  485. sqlconn := "http://"
  486. if os.Getenv("SQL_CONN") != "" {
  487. sqlconn = os.Getenv("SQL_CONN")
  488. } else if config.Config.Server.SQLConn != "" {
  489. sqlconn = config.Config.Server.SQLConn
  490. }
  491. return sqlconn
  492. }
  493. // IsHostNetwork - checks if running on host network
  494. func IsHostNetwork() bool {
  495. ishost := false
  496. if os.Getenv("HOST_NETWORK") == "on" {
  497. ishost = true
  498. } else if config.Config.Server.HostNetwork == "on" {
  499. ishost = true
  500. }
  501. return ishost
  502. }
  503. // GetNodeID - gets the node id
  504. func GetNodeID() string {
  505. var id string
  506. var err error
  507. // id = getMacAddr()
  508. if os.Getenv("NODE_ID") != "" {
  509. id = os.Getenv("NODE_ID")
  510. } else if config.Config.Server.NodeID != "" {
  511. id = config.Config.Server.NodeID
  512. } else {
  513. id, err = os.Hostname()
  514. if err != nil {
  515. return ""
  516. }
  517. }
  518. return id
  519. }
  520. func SetNodeID(id string) {
  521. config.Config.Server.NodeID = id
  522. }
  523. // GetServerCheckinInterval - gets the server check-in time
  524. func GetServerCheckinInterval() int64 {
  525. var t = int64(5)
  526. var envt, _ = strconv.Atoi(os.Getenv("SERVER_CHECKIN_INTERVAL"))
  527. if envt > 0 {
  528. t = int64(envt)
  529. } else if config.Config.Server.ServerCheckinInterval > 0 {
  530. t = config.Config.Server.ServerCheckinInterval
  531. }
  532. return t
  533. }
  534. // GetAuthProviderInfo = gets the oauth provider info
  535. func GetAuthProviderInfo() []string {
  536. var authProvider = ""
  537. if os.Getenv("AUTH_PROVIDER") != "" && os.Getenv("CLIENT_ID") != "" && os.Getenv("CLIENT_SECRET") != "" {
  538. authProvider = strings.ToLower(os.Getenv("AUTH_PROVIDER"))
  539. if authProvider == "google" || authProvider == "azure-ad" || authProvider == "github" {
  540. return []string{authProvider, os.Getenv("CLIENT_ID"), os.Getenv("CLIENT_SECRET")}
  541. } else {
  542. authProvider = ""
  543. }
  544. } else if config.Config.Server.AuthProvider != "" && config.Config.Server.ClientID != "" && config.Config.Server.ClientSecret != "" {
  545. authProvider = strings.ToLower(config.Config.Server.AuthProvider)
  546. if authProvider == "google" || authProvider == "azure-ad" || authProvider == "github" {
  547. return []string{authProvider, config.Config.Server.ClientID, config.Config.Server.ClientSecret}
  548. }
  549. }
  550. return []string{"", "", ""}
  551. }
  552. // GetAzureTenant - retrieve the azure tenant ID from env variable or config file
  553. func GetAzureTenant() string {
  554. var azureTenant = ""
  555. if os.Getenv("AZURE_TENANT") != "" {
  556. azureTenant = os.Getenv("AZURE_TENANT")
  557. } else if config.Config.Server.AzureTenant != "" {
  558. azureTenant = config.Config.Server.AzureTenant
  559. }
  560. return azureTenant
  561. }
  562. // GetRce - sees if Rce is enabled, off by default
  563. func GetRce() bool {
  564. return os.Getenv("RCE") == "on" || config.Config.Server.RCE == "on"
  565. }
  566. // GetDebug -- checks if debugging is enabled, off by default
  567. func GetDebug() bool {
  568. return os.Getenv("DEBUG") == "on" || config.Config.Server.Debug == true
  569. }
  570. func genNewCommsCIDR() string {
  571. currIfaces, err := net.Interfaces()
  572. netrange := fmt.Sprintf("172.%d.0.0/16", genCommsByte())
  573. if err == nil { // make sure chosen CIDR doesn't overlap with any local iface CIDRs
  574. iter := 0
  575. for i := 0; i < len(currIfaces); i++ {
  576. if currentAddrs, err := currIfaces[i].Addrs(); err == nil {
  577. for j := range currentAddrs {
  578. if strings.Contains(currentAddrs[j].String(), netrange[0:7]) {
  579. if iter > 20 { // if this hits, then the cidr should be specified
  580. logger.FatalLog("could not find a suitable comms network on this server, please manually enter one")
  581. }
  582. netrange = fmt.Sprintf("172.%d.0.0/16", genCommsByte())
  583. i = -1 // reset to loop back through
  584. iter++ // track how many times you've iterated and not found one
  585. break
  586. }
  587. }
  588. }
  589. }
  590. }
  591. return netrange
  592. }
  593. func genCommsByte() int {
  594. const min = 1 << 4 // 16
  595. const max = 1 << 5 // 32
  596. rand.Seed(time.Now().UnixNano())
  597. return rand.Intn(max-min) + min
  598. }