netclientutils.go 15 KB

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