netclientutils.go 14 KB

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