netclientutils.go 15 KB

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