netclientutils.go 15 KB

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