netclientutils.go 15 KB

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