netclientutils.go 14 KB

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