netclientutils.go 15 KB

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