netclientutils.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. package ncutils
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "encoding/gob"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "log"
  10. "net"
  11. "net/http"
  12. "os"
  13. "os/exec"
  14. "path/filepath"
  15. "regexp"
  16. "runtime"
  17. "strconv"
  18. "strings"
  19. "time"
  20. "github.com/gravitl/netmaker/logger"
  21. "github.com/gravitl/netmaker/models"
  22. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  23. )
  24. // Version - version of the netclient
  25. var Version = "dev"
  26. // MAX_NAME_LENGTH - maximum node name length
  27. const MAX_NAME_LENGTH = 62
  28. // NO_DB_RECORD - error message result
  29. const NO_DB_RECORD = "no result found"
  30. // NO_DB_RECORDS - error record result
  31. const NO_DB_RECORDS = "could not find any records"
  32. // LINUX_APP_DATA_PATH - linux path
  33. const LINUX_APP_DATA_PATH = "/etc/netclient"
  34. // WINDOWS_APP_DATA_PATH - windows path
  35. const WINDOWS_APP_DATA_PATH = "C:\\ProgramData\\Netclient"
  36. // WINDOWS_APP_DATA_PATH - windows path
  37. //const WINDOWS_WG_DPAPI_PATH = "C:\\Program Files\\WireGuard\\Data\\Configurations"
  38. // WINDOWS_SVC_NAME - service name
  39. const WINDOWS_SVC_NAME = "netclient"
  40. // NETCLIENT_DEFAULT_PORT - default port
  41. const NETCLIENT_DEFAULT_PORT = 51821
  42. // DEFAULT_GC_PERCENT - garbage collection percent
  43. const DEFAULT_GC_PERCENT = 10
  44. // KEY_SIZE = ideal length for keys
  45. const KEY_SIZE = 2048
  46. // constants for random strings
  47. const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  48. const (
  49. letterIdxBits = 6 // 6 bits to represent a letter index
  50. letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
  51. letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
  52. )
  53. // SetVersion -- set netclient version for use by other packages
  54. func SetVersion(ver string) {
  55. Version = ver
  56. }
  57. // IsWindows - checks if is windows
  58. func IsWindows() bool {
  59. return runtime.GOOS == "windows"
  60. }
  61. // IsMac - checks if is a mac
  62. func IsMac() bool {
  63. return runtime.GOOS == "darwin"
  64. }
  65. // IsLinux - checks if is linux
  66. func IsLinux() bool {
  67. return runtime.GOOS == "linux"
  68. }
  69. // IsLinux - checks if is linux
  70. func IsFreeBSD() bool {
  71. return runtime.GOOS == "freebsd"
  72. }
  73. // HasWGQuick - checks if WGQuick command is present
  74. func HasWgQuick() bool {
  75. cmd, err := exec.LookPath("wg-quick")
  76. return err == nil && cmd != ""
  77. }
  78. // GetWireGuard - checks if wg is installed
  79. func GetWireGuard() string {
  80. userspace := os.Getenv("WG_QUICK_USERSPACE_IMPLEMENTATION")
  81. if userspace != "" && (userspace == "boringtun" || userspace == "wireguard-go") {
  82. return userspace
  83. }
  84. return "wg"
  85. }
  86. // IsKernel - checks if running kernel WireGuard
  87. func IsKernel() bool {
  88. //TODO
  89. //Replace && true with some config file value
  90. //This value should be something like kernelmode, which should be 'on' by default.
  91. return IsLinux() && os.Getenv("WG_QUICK_USERSPACE_IMPLEMENTATION") == ""
  92. }
  93. // IsEmptyRecord - repeat from database
  94. func IsEmptyRecord(err error) bool {
  95. if err == nil {
  96. return false
  97. }
  98. return strings.Contains(err.Error(), NO_DB_RECORD) || strings.Contains(err.Error(), NO_DB_RECORDS)
  99. }
  100. // GetPublicIP - gets public ip
  101. func GetPublicIP() (string, error) {
  102. iplist := []string{"https://ip.client.gravitl.com", "https://ifconfig.me", "https://api.ipify.org", "https://ipinfo.io/ip"}
  103. endpoint := ""
  104. var err error
  105. for _, ipserver := range iplist {
  106. resp, err := http.Get(ipserver)
  107. if err != nil {
  108. continue
  109. }
  110. defer resp.Body.Close()
  111. if resp.StatusCode == http.StatusOK {
  112. bodyBytes, err := io.ReadAll(resp.Body)
  113. if err != nil {
  114. continue
  115. }
  116. endpoint = string(bodyBytes)
  117. break
  118. }
  119. }
  120. if err == nil && endpoint == "" {
  121. err = errors.New("public address not found")
  122. }
  123. return endpoint, err
  124. }
  125. // GetMacAddr - get's mac address
  126. func GetMacAddr() ([]string, error) {
  127. ifas, err := net.Interfaces()
  128. if err != nil {
  129. return nil, err
  130. }
  131. var as []string
  132. for _, ifa := range ifas {
  133. a := ifa.HardwareAddr.String()
  134. if a != "" {
  135. as = append(as, a)
  136. }
  137. }
  138. return as, nil
  139. }
  140. func parsePeers(keepalive int32, peers []wgtypes.PeerConfig) (string, error) {
  141. peersString := ""
  142. if keepalive <= 0 {
  143. keepalive = 0
  144. }
  145. for _, peer := range peers {
  146. endpointString := ""
  147. if peer.Endpoint != nil && peer.Endpoint.String() != "" {
  148. endpointString += "Endpoint = " + peer.Endpoint.String()
  149. }
  150. newAllowedIps := []string{}
  151. for _, allowedIP := range peer.AllowedIPs {
  152. newAllowedIps = append(newAllowedIps, allowedIP.String())
  153. }
  154. peersString += fmt.Sprintf(`[Peer]
  155. PublicKey = %s
  156. AllowedIps = %s
  157. PersistentKeepAlive = %s
  158. %s
  159. `,
  160. peer.PublicKey.String(),
  161. strings.Join(newAllowedIps, ","),
  162. strconv.Itoa(int(keepalive)),
  163. endpointString,
  164. )
  165. }
  166. return peersString, nil
  167. }
  168. // GetLocalIP - gets local ip of machine
  169. func GetLocalIP(localrange string) (string, error) {
  170. _, localRange, err := net.ParseCIDR(localrange)
  171. if err != nil {
  172. return "", err
  173. }
  174. ifaces, err := net.Interfaces()
  175. if err != nil {
  176. return "", err
  177. }
  178. var local string
  179. found := false
  180. for _, i := range ifaces {
  181. if i.Flags&net.FlagUp == 0 {
  182. continue // interface down
  183. }
  184. if i.Flags&net.FlagLoopback != 0 {
  185. continue // loopback interface
  186. }
  187. addrs, err := i.Addrs()
  188. if err != nil {
  189. return "", err
  190. }
  191. for _, addr := range addrs {
  192. var ip net.IP
  193. switch v := addr.(type) {
  194. case *net.IPNet:
  195. if !found {
  196. ip = v.IP
  197. local = ip.String()
  198. found = localRange.Contains(ip)
  199. }
  200. case *net.IPAddr:
  201. if !found {
  202. ip = v.IP
  203. local = ip.String()
  204. found = localRange.Contains(ip)
  205. }
  206. }
  207. }
  208. }
  209. if !found || local == "" {
  210. return "", errors.New("Failed to find local IP in range " + localrange)
  211. }
  212. return local, nil
  213. }
  214. //GetNetworkIPMask - Pulls the netmask out of the network
  215. func GetNetworkIPMask(networkstring string) (string, string, error) {
  216. ip, ipnet, err := net.ParseCIDR(networkstring)
  217. if err != nil {
  218. return "", "", err
  219. }
  220. ipstring := ip.String()
  221. mask := ipnet.Mask
  222. maskstring := fmt.Sprintf("%d.%d.%d.%d", mask[0], mask[1], mask[2], mask[3])
  223. //maskstring := ipnet.Mask.String()
  224. return ipstring, maskstring, err
  225. }
  226. // GetFreePort - gets free port of machine
  227. func GetFreePort(rangestart int32) (int32, error) {
  228. addr := net.UDPAddr{}
  229. if rangestart == 0 {
  230. rangestart = NETCLIENT_DEFAULT_PORT
  231. }
  232. for x := rangestart; x <= 65535; x++ {
  233. addr.Port = int(x)
  234. conn, err := net.ListenUDP("udp", &addr)
  235. if err != nil {
  236. continue
  237. }
  238. defer conn.Close()
  239. return x, nil
  240. }
  241. return rangestart, errors.New("no free ports")
  242. }
  243. // == OS PATH FUNCTIONS ==
  244. // GetHomeDirWindows - gets home directory in windows
  245. func GetHomeDirWindows() string {
  246. if IsWindows() {
  247. home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
  248. if home == "" {
  249. home = os.Getenv("USERPROFILE")
  250. }
  251. return home
  252. }
  253. return os.Getenv("HOME")
  254. }
  255. // GetNetclientPath - gets netclient path locally
  256. func GetNetclientPath() string {
  257. if IsWindows() {
  258. return WINDOWS_APP_DATA_PATH
  259. } else if IsMac() {
  260. return "/etc/netclient/"
  261. } else {
  262. return LINUX_APP_DATA_PATH
  263. }
  264. }
  265. // GetSeparator - gets the separator for OS
  266. func GetSeparator() string {
  267. if IsWindows() {
  268. return "\\"
  269. } else {
  270. return "/"
  271. }
  272. }
  273. // GetFileWithRetry - retry getting file X number of times before failing
  274. func GetFileWithRetry(path string, retryCount int) ([]byte, error) {
  275. var data []byte
  276. var err error
  277. for count := 0; count < retryCount; count++ {
  278. data, err = os.ReadFile(path)
  279. if err == nil {
  280. return data, err
  281. } else {
  282. logger.Log(1, "failed to retrieve file ", path, ", retrying...")
  283. time.Sleep(time.Second >> 2)
  284. }
  285. }
  286. return data, err
  287. }
  288. // GetNetclientServerPath - gets netclient server path
  289. func GetNetclientServerPath(server string) string {
  290. if IsWindows() {
  291. return WINDOWS_APP_DATA_PATH + "\\" + server + "\\"
  292. } else if IsMac() {
  293. return "/etc/netclient/" + server + "/"
  294. } else {
  295. return LINUX_APP_DATA_PATH + "/" + server
  296. }
  297. }
  298. // GetNetclientPathSpecific - gets specific netclient config path
  299. func GetNetclientPathSpecific() string {
  300. if IsWindows() {
  301. return WINDOWS_APP_DATA_PATH + "\\"
  302. } else if IsMac() {
  303. return "/etc/netclient/config/"
  304. } else {
  305. return LINUX_APP_DATA_PATH + "/config/"
  306. }
  307. }
  308. // GetNewIface - Gets the name of the real interface created on Mac
  309. func GetNewIface(dir string) (string, error) {
  310. files, _ := os.ReadDir(dir)
  311. var newestFile string
  312. var newestTime int64 = 0
  313. var err error
  314. for _, f := range files {
  315. fi, err := os.Stat(dir + f.Name())
  316. if err != nil {
  317. return "", err
  318. }
  319. currTime := fi.ModTime().Unix()
  320. if currTime > newestTime && strings.Contains(f.Name(), ".sock") {
  321. newestTime = currTime
  322. newestFile = f.Name()
  323. }
  324. }
  325. resultArr := strings.Split(newestFile, ".")
  326. if resultArr[0] == "" {
  327. err = errors.New("sock file does not exist")
  328. }
  329. return resultArr[0], err
  330. }
  331. // GetFileAsString - returns the string contents of a given file
  332. func GetFileAsString(path string) (string, error) {
  333. content, err := os.ReadFile(path)
  334. if err != nil {
  335. return "", err
  336. }
  337. return string(content), err
  338. }
  339. // GetNetclientPathSpecific - gets specific netclient config path
  340. func GetWGPathSpecific() string {
  341. if IsWindows() {
  342. return WINDOWS_APP_DATA_PATH + "\\"
  343. } else {
  344. return "/etc/wireguard/"
  345. }
  346. }
  347. // Copy - copies a src file to dest
  348. func Copy(src, dst string) error {
  349. sourceFileStat, err := os.Stat(src)
  350. if err != nil {
  351. return err
  352. }
  353. if !sourceFileStat.Mode().IsRegular() {
  354. return errors.New(src + " is not a regular file")
  355. }
  356. source, err := os.Open(src)
  357. if err != nil {
  358. return err
  359. }
  360. defer source.Close()
  361. destination, err := os.Create(dst)
  362. if err != nil {
  363. return err
  364. }
  365. defer destination.Close()
  366. _, err = io.Copy(destination, source)
  367. if err != nil {
  368. return err
  369. }
  370. err = os.Chmod(dst, 0755)
  371. return err
  372. }
  373. // RunsCmds - runs cmds
  374. func RunCmds(commands []string, printerr bool) error {
  375. var err error
  376. for _, command := range commands {
  377. args := strings.Fields(command)
  378. out, err := exec.Command(args[0], args[1:]...).CombinedOutput()
  379. if err != nil && printerr {
  380. logger.Log(0, "error running command:", command)
  381. logger.Log(0, strings.TrimSuffix(string(out), "\n"))
  382. }
  383. }
  384. return err
  385. }
  386. // FileExists - checks if file exists locally
  387. func FileExists(f string) bool {
  388. info, err := os.Stat(f)
  389. if os.IsNotExist(err) {
  390. return false
  391. }
  392. if err != nil && strings.Contains(err.Error(), "not a directory") {
  393. return false
  394. }
  395. if err != nil {
  396. logger.Log(0, "error reading file: "+f+", "+err.Error())
  397. }
  398. return !info.IsDir()
  399. }
  400. // GetSystemNetworks - get networks locally
  401. func GetSystemNetworks() ([]string, error) {
  402. var networks []string
  403. files, err := filepath.Glob(GetNetclientPathSpecific() + "netconfig-*")
  404. if err != nil {
  405. return nil, err
  406. }
  407. for _, file := range files {
  408. //don't want files such as *.bak, *.swp
  409. if filepath.Ext(file) != "" {
  410. continue
  411. }
  412. file := filepath.Base(file)
  413. temp := strings.Split(file, "-")
  414. networks = append(networks, strings.Join(temp[1:], "-"))
  415. }
  416. return networks, nil
  417. }
  418. func stringAfter(original string, substring string) string {
  419. position := strings.LastIndex(original, substring)
  420. if position == -1 {
  421. return ""
  422. }
  423. adjustedPosition := position + len(substring)
  424. if adjustedPosition >= len(original) {
  425. return ""
  426. }
  427. return original[adjustedPosition:]
  428. }
  429. // ShortenString - Brings string down to specified length. Stops names from being too long
  430. func ShortenString(input string, length int) string {
  431. output := input
  432. if len(input) > length {
  433. output = input[0:length]
  434. }
  435. return output
  436. }
  437. // DNSFormatString - Formats a string with correct usage for DNS
  438. func DNSFormatString(input string) string {
  439. reg, err := regexp.Compile("[^a-zA-Z0-9-]+")
  440. if err != nil {
  441. logger.Log(0, "error with regex: "+err.Error())
  442. return ""
  443. }
  444. return reg.ReplaceAllString(input, "")
  445. }
  446. // GetHostname - Gets hostname of machine
  447. func GetHostname() string {
  448. hostname, err := os.Hostname()
  449. if err != nil {
  450. return ""
  451. }
  452. if len(hostname) > MAX_NAME_LENGTH {
  453. hostname = hostname[0:MAX_NAME_LENGTH]
  454. }
  455. return hostname
  456. }
  457. // CheckUID - Checks to make sure user has root privileges
  458. func CheckUID() {
  459. // start our application
  460. out, err := RunCmd("id -u", true)
  461. if err != nil {
  462. log.Fatal(out, err)
  463. }
  464. id, err := strconv.Atoi(string(out[:len(out)-1]))
  465. if err != nil {
  466. log.Fatal(err)
  467. }
  468. if id != 0 {
  469. log.Fatal("This program must be run with elevated privileges (sudo). This program installs a SystemD service and configures WireGuard and networking rules. Please re-run with sudo/root.")
  470. }
  471. }
  472. // CheckWG - Checks if WireGuard is installed. If not, exit
  473. func CheckWG() {
  474. var _, err = exec.LookPath("wg")
  475. uspace := GetWireGuard()
  476. if err != nil {
  477. if uspace == "wg" {
  478. logger.Log(0, err.Error())
  479. log.Fatal("WireGuard not installed. Please install WireGuard (wireguard-tools) and try again.")
  480. }
  481. logger.Log(0, "running with userspace wireguard: ", uspace)
  482. } else if uspace != "wg" {
  483. logger.Log(0, "running userspace WireGuard with ", uspace)
  484. }
  485. }
  486. // ConvertKeyToBytes - util to convert a key to bytes to use elsewhere
  487. func ConvertKeyToBytes(key *[32]byte) ([]byte, error) {
  488. var buffer bytes.Buffer
  489. var enc = gob.NewEncoder(&buffer)
  490. if err := enc.Encode(key); err != nil {
  491. return nil, err
  492. }
  493. return buffer.Bytes(), nil
  494. }
  495. // ConvertBytesToKey - util to convert bytes to a key to use elsewhere
  496. func ConvertBytesToKey(data []byte) (*[32]byte, error) {
  497. var buffer = bytes.NewBuffer(data)
  498. var dec = gob.NewDecoder(buffer)
  499. var result = new([32]byte)
  500. var err = dec.Decode(result)
  501. if err != nil {
  502. return nil, err
  503. }
  504. return result, err
  505. }
  506. // ServerAddrSliceContains - sees if a string slice contains a string element
  507. func ServerAddrSliceContains(slice []models.ServerAddr, item models.ServerAddr) bool {
  508. for _, s := range slice {
  509. if s.Address == item.Address && s.IsLeader == item.IsLeader {
  510. return true
  511. }
  512. }
  513. return false
  514. }
  515. // MakeRandomString - generates a random string of len n
  516. func MakeRandomString(n int) string {
  517. const validChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  518. result := make([]byte, n)
  519. if _, err := rand.Reader.Read(result); err != nil {
  520. return ""
  521. }
  522. for i, b := range result {
  523. result[i] = validChars[b%byte(len(validChars))]
  524. }
  525. return string(result)
  526. }