netclientutils.go 14 KB

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