netclientutils.go 15 KB

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