netclientutils.go 15 KB

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