netclientutils.go 15 KB

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