netclientutils.go 15 KB

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