netclientutils.go 14 KB

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