netclientutils.go 15 KB

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