netclientutils.go 15 KB

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