netclientutils.go 15 KB

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