netclientutils.go 15 KB

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