netclientutils.go 14 KB

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