netclientutils.go 14 KB

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