netclientutils.go 15 KB

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