netclientutils.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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. found := false
  94. _, err := exec.LookPath("nft")
  95. if err == nil {
  96. found = true
  97. }
  98. return found
  99. }
  100. // IsIPTablesPresent - returns true if iptables is present, false otherwise
  101. // Does not consider OS, up to the caller to determine if the OS supports iptables/whether this check is valid.
  102. func IsIPTablesPresent() bool {
  103. found := false
  104. _, err := exec.LookPath("iptables")
  105. if err == nil {
  106. found = true
  107. }
  108. return found
  109. }
  110. // IsKernel - checks if running kernel WireGuard
  111. func IsKernel() bool {
  112. //TODO
  113. //Replace && true with some config file value
  114. //This value should be something like kernelmode, which should be 'on' by default.
  115. return IsLinux() && os.Getenv("WG_QUICK_USERSPACE_IMPLEMENTATION") == ""
  116. }
  117. // IsEmptyRecord - repeat from database
  118. func IsEmptyRecord(err error) bool {
  119. if err == nil {
  120. return false
  121. }
  122. return strings.Contains(err.Error(), NO_DB_RECORD) || strings.Contains(err.Error(), NO_DB_RECORDS)
  123. }
  124. // GetPublicIP - gets public ip
  125. func GetPublicIP(api string) (string, error) {
  126. iplist := []string{"https://ip.client.gravitl.com", "https://ifconfig.me", "https://api.ipify.org", "https://ipinfo.io/ip"}
  127. for network, ipService := range global_settings.PublicIPServices {
  128. logger.Log(3, "User provided public IP service defined for network", network, "is", ipService)
  129. // prepend the user-specified service so it's checked first
  130. iplist = append([]string{ipService}, iplist...)
  131. }
  132. if api != "" {
  133. api = "https://" + api + "/api/getip"
  134. iplist = append([]string{api}, iplist...)
  135. }
  136. endpoint := ""
  137. var err error
  138. for _, ipserver := range iplist {
  139. logger.Log(3, "Running public IP check with service", ipserver)
  140. client := &http.Client{
  141. Timeout: time.Second * 10,
  142. }
  143. resp, err := client.Get(ipserver)
  144. if err != nil {
  145. continue
  146. }
  147. defer resp.Body.Close()
  148. if resp.StatusCode == http.StatusOK {
  149. bodyBytes, err := io.ReadAll(resp.Body)
  150. if err != nil {
  151. continue
  152. }
  153. endpoint = string(bodyBytes)
  154. logger.Log(3, "Public IP address is", endpoint)
  155. break
  156. }
  157. }
  158. if err == nil && endpoint == "" {
  159. err = errors.New("public address not found")
  160. }
  161. return endpoint, err
  162. }
  163. // GetMacAddr - get's mac address
  164. func GetMacAddr() ([]string, error) {
  165. ifas, err := net.Interfaces()
  166. if err != nil {
  167. return nil, err
  168. }
  169. var as []string
  170. for _, ifa := range ifas {
  171. a := ifa.HardwareAddr.String()
  172. if a != "" {
  173. as = append(as, a)
  174. }
  175. }
  176. return as, nil
  177. }
  178. // GetLocalIP - gets local ip of machine
  179. func GetLocalIP(localrange string) (string, error) {
  180. _, localRange, err := net.ParseCIDR(localrange)
  181. if err != nil {
  182. return "", err
  183. }
  184. ifaces, err := net.Interfaces()
  185. if err != nil {
  186. return "", err
  187. }
  188. var local string
  189. found := false
  190. for _, i := range ifaces {
  191. if i.Flags&net.FlagUp == 0 {
  192. continue // interface down
  193. }
  194. if i.Flags&net.FlagLoopback != 0 {
  195. continue // loopback interface
  196. }
  197. addrs, err := i.Addrs()
  198. if err != nil {
  199. return "", err
  200. }
  201. for _, addr := range addrs {
  202. var ip net.IP
  203. switch v := addr.(type) {
  204. case *net.IPNet:
  205. if !found {
  206. ip = v.IP
  207. local = ip.String()
  208. found = localRange.Contains(ip)
  209. }
  210. case *net.IPAddr:
  211. if !found {
  212. ip = v.IP
  213. local = ip.String()
  214. found = localRange.Contains(ip)
  215. }
  216. }
  217. }
  218. }
  219. if !found || local == "" {
  220. return "", errors.New("Failed to find local IP in range " + localrange)
  221. }
  222. return local, nil
  223. }
  224. // GetNetworkIPMask - Pulls the netmask out of the network
  225. func GetNetworkIPMask(networkstring string) (string, string, error) {
  226. ip, ipnet, err := net.ParseCIDR(networkstring)
  227. if err != nil {
  228. return "", "", err
  229. }
  230. ipstring := ip.String()
  231. mask := ipnet.Mask
  232. maskstring := fmt.Sprintf("%d.%d.%d.%d", mask[0], mask[1], mask[2], mask[3])
  233. //maskstring := ipnet.Mask.String()
  234. return ipstring, maskstring, err
  235. }
  236. // GetFreePort - gets free port of machine
  237. func GetFreePort(rangestart int32) (int32, error) {
  238. addr := net.UDPAddr{}
  239. if rangestart == 0 {
  240. rangestart = NETCLIENT_DEFAULT_PORT
  241. }
  242. for x := rangestart; x <= 65535; x++ {
  243. addr.Port = int(x)
  244. conn, err := net.ListenUDP("udp", &addr)
  245. if err != nil {
  246. continue
  247. }
  248. defer conn.Close()
  249. return x, nil
  250. }
  251. return rangestart, errors.New("no free ports")
  252. }
  253. // == OS PATH FUNCTIONS ==
  254. // GetHomeDirWindows - gets home directory in windows
  255. func GetHomeDirWindows() string {
  256. if IsWindows() {
  257. home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
  258. if home == "" {
  259. home = os.Getenv("USERPROFILE")
  260. }
  261. return home
  262. }
  263. return os.Getenv("HOME")
  264. }
  265. // GetNetclientPath - gets netclient path locally
  266. func GetNetclientPath() string {
  267. if IsWindows() {
  268. return WINDOWS_APP_DATA_PATH
  269. } else if IsMac() {
  270. return MAC_APP_DATA_PATH
  271. } else {
  272. return LINUX_APP_DATA_PATH
  273. }
  274. }
  275. // GetSeparator - gets the separator for OS
  276. func GetSeparator() string {
  277. if IsWindows() {
  278. return "\\"
  279. } else {
  280. return "/"
  281. }
  282. }
  283. // GetFileWithRetry - retry getting file X number of times before failing
  284. func GetFileWithRetry(path string, retryCount int) ([]byte, error) {
  285. var data []byte
  286. var err error
  287. for count := 0; count < retryCount; count++ {
  288. data, err = os.ReadFile(path)
  289. if err == nil {
  290. return data, err
  291. } else {
  292. logger.Log(1, "failed to retrieve file ", path, ", retrying...")
  293. time.Sleep(time.Second >> 2)
  294. }
  295. }
  296. return data, err
  297. }
  298. // GetNetclientServerPath - gets netclient server path
  299. func GetNetclientServerPath(server string) string {
  300. if IsWindows() {
  301. return WINDOWS_APP_DATA_PATH + "\\" + server + "\\"
  302. } else if IsMac() {
  303. return MAC_APP_DATA_PATH + "/" + server + "/"
  304. } else {
  305. return LINUX_APP_DATA_PATH + "/" + server
  306. }
  307. }
  308. // GetNetclientPathSpecific - gets specific netclient config path
  309. func GetNetclientPathSpecific() string {
  310. if IsWindows() {
  311. return WINDOWS_APP_DATA_PATH + "\\"
  312. } else if IsMac() {
  313. return MAC_APP_DATA_PATH + "/config/"
  314. } else {
  315. return LINUX_APP_DATA_PATH + "/config/"
  316. }
  317. }
  318. func CheckIPAddress(ip string) error {
  319. if net.ParseIP(ip) == nil {
  320. return fmt.Errorf("ip address %s is invalid", ip)
  321. }
  322. return nil
  323. }
  324. // GetNewIface - Gets the name of the real interface created on Mac
  325. func GetNewIface(dir string) (string, error) {
  326. files, _ := os.ReadDir(dir)
  327. var newestFile string
  328. var newestTime int64 = 0
  329. var err error
  330. for _, f := range files {
  331. fi, err := os.Stat(dir + f.Name())
  332. if err != nil {
  333. return "", err
  334. }
  335. currTime := fi.ModTime().Unix()
  336. if currTime > newestTime && strings.Contains(f.Name(), ".sock") {
  337. newestTime = currTime
  338. newestFile = f.Name()
  339. }
  340. }
  341. resultArr := strings.Split(newestFile, ".")
  342. if resultArr[0] == "" {
  343. err = errors.New("sock file does not exist")
  344. }
  345. return resultArr[0], err
  346. }
  347. // GetFileAsString - returns the string contents of a given file
  348. func GetFileAsString(path string) (string, error) {
  349. content, err := os.ReadFile(path)
  350. if err != nil {
  351. return "", err
  352. }
  353. return string(content), err
  354. }
  355. // GetNetclientPathSpecific - gets specific netclient config path
  356. func GetWGPathSpecific() string {
  357. if IsWindows() {
  358. return WINDOWS_APP_DATA_PATH + "\\"
  359. } else {
  360. return "/etc/wireguard/"
  361. }
  362. }
  363. // Copy - copies a src file to dest
  364. func Copy(src, dst string) error {
  365. sourceFileStat, err := os.Stat(src)
  366. if err != nil {
  367. return err
  368. }
  369. if !sourceFileStat.Mode().IsRegular() {
  370. return errors.New(src + " is not a regular file")
  371. }
  372. source, err := os.Open(src)
  373. if err != nil {
  374. return err
  375. }
  376. defer source.Close()
  377. destination, err := os.Create(dst)
  378. if err != nil {
  379. return err
  380. }
  381. defer destination.Close()
  382. _, err = io.Copy(destination, source)
  383. if err != nil {
  384. return err
  385. }
  386. err = os.Chmod(dst, 0755)
  387. return err
  388. }
  389. // RunsCmds - runs cmds
  390. func RunCmds(commands []string, printerr bool) error {
  391. var err error
  392. for _, command := range commands {
  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.Node) 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. }