netclientutils.go 14 KB

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