netclientutils.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. package ncutils
  2. import (
  3. "crypto/tls"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "log"
  8. "math/rand"
  9. "net"
  10. "net/http"
  11. "os"
  12. "os/exec"
  13. "regexp"
  14. "runtime"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "github.com/gravitl/netmaker/models"
  19. "golang.zx2c4.com/wireguard/wgctrl"
  20. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  21. "google.golang.org/grpc"
  22. "google.golang.org/grpc/credentials"
  23. )
  24. // MAX_NAME_LENGTH - maximum node name length
  25. const MAX_NAME_LENGTH = 62
  26. // NO_DB_RECORD - error message result
  27. const NO_DB_RECORD = "no result found"
  28. // NO_DB_RECORDS - error record result
  29. const NO_DB_RECORDS = "could not find any records"
  30. // LINUX_APP_DATA_PATH - linux path
  31. const LINUX_APP_DATA_PATH = "/etc/netclient"
  32. // WINDOWS_APP_DATA_PATH - windows path
  33. const WINDOWS_APP_DATA_PATH = "C:\\ProgramData\\Netclient"
  34. // WINDOWS_APP_DATA_PATH - windows path
  35. const WINDOWS_WG_DPAPI_PATH = "C:\\Program Files\\WireGuard\\Data\\Configurations"
  36. // WINDOWS_SVC_NAME - service name
  37. const WINDOWS_SVC_NAME = "netclient"
  38. // NETCLIENT_DEFAULT_PORT - default port
  39. const NETCLIENT_DEFAULT_PORT = 51821
  40. // DEFAULT_GC_PERCENT - garbage collection percent
  41. const DEFAULT_GC_PERCENT = 10
  42. // Log - logs a message
  43. func Log(message string) {
  44. log.SetFlags(log.Flags() &^ (log.Llongfile | log.Lshortfile))
  45. log.Println("[netclient]", message)
  46. }
  47. // IsWindows - checks if is windows
  48. func IsWindows() bool {
  49. return runtime.GOOS == "windows"
  50. }
  51. // IsMac - checks if is a mac
  52. func IsMac() bool {
  53. return runtime.GOOS == "darwin"
  54. }
  55. // IsLinux - checks if is linux
  56. func IsLinux() bool {
  57. return runtime.GOOS == "linux"
  58. }
  59. // IsLinux - checks if is linux
  60. func IsFreeBSD() bool {
  61. return runtime.GOOS == "freebsd"
  62. }
  63. // GetWireGuard - checks if wg is installed
  64. func GetWireGuard() string {
  65. userspace := os.Getenv("WG_QUICK_USERSPACE_IMPLEMENTATION")
  66. if userspace != "" && (userspace == "boringtun" || userspace == "wireguard-go") {
  67. return userspace
  68. }
  69. return "wg"
  70. }
  71. // IsKernel - checks if running kernel WireGuard
  72. func IsKernel() bool {
  73. //TODO
  74. //Replace && true with some config file value
  75. //This value should be something like kernelmode, which should be 'on' by default.
  76. return IsLinux() && os.Getenv("WG_QUICK_USERSPACE_IMPLEMENTATION") == ""
  77. }
  78. // IsEmptyRecord - repeat from database
  79. func IsEmptyRecord(err error) bool {
  80. if err == nil {
  81. return false
  82. }
  83. return strings.Contains(err.Error(), NO_DB_RECORD) || strings.Contains(err.Error(), NO_DB_RECORDS)
  84. }
  85. //generate an access key value
  86. // GenPass - generates a pass
  87. func GenPass() string {
  88. var seededRand *rand.Rand = rand.New(
  89. rand.NewSource(time.Now().UnixNano()))
  90. length := 16
  91. charset := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  92. b := make([]byte, length)
  93. for i := range b {
  94. b[i] = charset[seededRand.Intn(len(charset))]
  95. }
  96. return string(b)
  97. }
  98. // GetPublicIP - gets public ip
  99. func GetPublicIP() (string, error) {
  100. iplist := []string{"https://ip.client.gravitl.com", "https://ifconfig.me", "https://api.ipify.org", "https://ipinfo.io/ip"}
  101. endpoint := ""
  102. var err error
  103. for _, ipserver := range iplist {
  104. resp, err := http.Get(ipserver)
  105. if err != nil {
  106. continue
  107. }
  108. defer resp.Body.Close()
  109. if resp.StatusCode == http.StatusOK {
  110. bodyBytes, err := io.ReadAll(resp.Body)
  111. if err != nil {
  112. continue
  113. }
  114. endpoint = string(bodyBytes)
  115. break
  116. }
  117. }
  118. if err == nil && endpoint == "" {
  119. err = errors.New("public address not found")
  120. }
  121. return endpoint, err
  122. }
  123. // GetMacAddr - get's mac address
  124. func GetMacAddr() ([]string, error) {
  125. ifas, err := net.Interfaces()
  126. if err != nil {
  127. return nil, err
  128. }
  129. var as []string
  130. for _, ifa := range ifas {
  131. a := ifa.HardwareAddr.String()
  132. if a != "" {
  133. as = append(as, a)
  134. }
  135. }
  136. return as, nil
  137. }
  138. func parsePeers(keepalive int32, peers []wgtypes.PeerConfig) (string, error) {
  139. peersString := ""
  140. if keepalive <= 0 {
  141. keepalive = 0
  142. }
  143. for _, peer := range peers {
  144. endpointString := ""
  145. if peer.Endpoint != nil && peer.Endpoint.String() != "" {
  146. endpointString += "Endpoint = " + peer.Endpoint.String()
  147. }
  148. newAllowedIps := []string{}
  149. for _, allowedIP := range peer.AllowedIPs {
  150. newAllowedIps = append(newAllowedIps, allowedIP.String())
  151. }
  152. peersString += fmt.Sprintf(`[Peer]
  153. PublicKey = %s
  154. AllowedIps = %s
  155. PersistentKeepAlive = %s
  156. %s
  157. `,
  158. peer.PublicKey.String(),
  159. strings.Join(newAllowedIps, ","),
  160. strconv.Itoa(int(keepalive)),
  161. endpointString,
  162. )
  163. }
  164. return peersString, nil
  165. }
  166. // GetLocalIP - gets local ip of machine
  167. func GetLocalIP(localrange string) (string, error) {
  168. _, localRange, err := net.ParseCIDR(localrange)
  169. if err != nil {
  170. return "", err
  171. }
  172. ifaces, err := net.Interfaces()
  173. if err != nil {
  174. return "", err
  175. }
  176. var local string
  177. found := false
  178. for _, i := range ifaces {
  179. if i.Flags&net.FlagUp == 0 {
  180. continue // interface down
  181. }
  182. if i.Flags&net.FlagLoopback != 0 {
  183. continue // loopback interface
  184. }
  185. addrs, err := i.Addrs()
  186. if err != nil {
  187. return "", err
  188. }
  189. for _, addr := range addrs {
  190. var ip net.IP
  191. switch v := addr.(type) {
  192. case *net.IPNet:
  193. if !found {
  194. ip = v.IP
  195. local = ip.String()
  196. found = localRange.Contains(ip)
  197. }
  198. case *net.IPAddr:
  199. if !found {
  200. ip = v.IP
  201. local = ip.String()
  202. found = localRange.Contains(ip)
  203. }
  204. }
  205. }
  206. }
  207. if !found || local == "" {
  208. return "", errors.New("Failed to find local IP in range " + localrange)
  209. }
  210. return local, nil
  211. }
  212. //GetNetworkIPMask - Pulls the netmask out of the network
  213. func GetNetworkIPMask(networkstring string) (string, string, error) {
  214. ip, ipnet, err := net.ParseCIDR(networkstring)
  215. if err != nil {
  216. return "", "", err
  217. }
  218. ipstring := ip.String()
  219. mask := ipnet.Mask
  220. maskstring := fmt.Sprintf("%d.%d.%d.%d", mask[0], mask[1], mask[2], mask[3])
  221. //maskstring := ipnet.Mask.String()
  222. return ipstring, maskstring, err
  223. }
  224. // GetFreePort - gets free port of machine
  225. func GetFreePort(rangestart int32) (int32, error) {
  226. if rangestart == 0 {
  227. rangestart = NETCLIENT_DEFAULT_PORT
  228. }
  229. wgclient, err := wgctrl.New()
  230. if err != nil {
  231. return 0, err
  232. }
  233. defer wgclient.Close()
  234. devices, err := wgclient.Devices()
  235. if err != nil {
  236. return 0, err
  237. }
  238. for x := rangestart; x <= 65535; x++ {
  239. conflict := false
  240. for _, i := range devices {
  241. if int32(i.ListenPort) == x {
  242. conflict = true
  243. break
  244. }
  245. }
  246. if conflict {
  247. continue
  248. }
  249. return int32(x), nil
  250. }
  251. return rangestart, err
  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 "/etc/netclient/"
  271. } else {
  272. return LINUX_APP_DATA_PATH
  273. }
  274. }
  275. // GetNetclientPathSpecific - gets specific netclient config path
  276. func GetNetclientPathSpecific() string {
  277. if IsWindows() {
  278. return WINDOWS_APP_DATA_PATH + "\\"
  279. } else if IsMac() {
  280. return "/etc/netclient/config/"
  281. } else {
  282. return LINUX_APP_DATA_PATH + "/config/"
  283. }
  284. }
  285. // GetNewIface - Gets the name of the real interface created on Mac
  286. func GetNewIface(dir string) (string, error) {
  287. files, _ := os.ReadDir(dir)
  288. var newestFile string
  289. var newestTime int64 = 0
  290. var err error
  291. for _, f := range files {
  292. fi, err := os.Stat(dir + f.Name())
  293. if err != nil {
  294. return "", err
  295. }
  296. currTime := fi.ModTime().Unix()
  297. if currTime > newestTime && strings.Contains(f.Name(), ".sock") {
  298. newestTime = currTime
  299. newestFile = f.Name()
  300. }
  301. }
  302. resultArr := strings.Split(newestFile, ".")
  303. if resultArr[0] == "" {
  304. err = errors.New("sock file does not exist")
  305. }
  306. return resultArr[0], err
  307. }
  308. // GetFileAsString - returns the string contents of a given file
  309. func GetFileAsString(path string) (string, error) {
  310. content, err := os.ReadFile(path)
  311. if err != nil {
  312. return "", err
  313. }
  314. return string(content), err
  315. }
  316. // GetNetclientPathSpecific - gets specific netclient config path
  317. func GetWGPathSpecific() string {
  318. if IsWindows() {
  319. return WINDOWS_APP_DATA_PATH + "\\"
  320. } else {
  321. return "/etc/wireguard/"
  322. }
  323. }
  324. // GRPCRequestOpts - gets grps request opts
  325. func GRPCRequestOpts(isSecure string) grpc.DialOption {
  326. var requestOpts grpc.DialOption
  327. requestOpts = grpc.WithInsecure()
  328. if isSecure == "on" {
  329. h2creds := credentials.NewTLS(&tls.Config{NextProtos: []string{"h2"}})
  330. requestOpts = grpc.WithTransportCredentials(h2creds)
  331. }
  332. return requestOpts
  333. }
  334. // Copy - copies a src file to dest
  335. func Copy(src, dst string) error {
  336. sourceFileStat, err := os.Stat(src)
  337. if err != nil {
  338. return err
  339. }
  340. if !sourceFileStat.Mode().IsRegular() {
  341. return errors.New(src + " is not a regular file")
  342. }
  343. source, err := os.Open(src)
  344. if err != nil {
  345. return err
  346. }
  347. defer source.Close()
  348. destination, err := os.Create(dst)
  349. if err != nil {
  350. return err
  351. }
  352. defer destination.Close()
  353. _, err = io.Copy(destination, source)
  354. if err != nil {
  355. return err
  356. }
  357. err = os.Chmod(dst, 0755)
  358. return err
  359. }
  360. // RunsCmds - runs cmds
  361. func RunCmds(commands []string, printerr bool) error {
  362. var err error
  363. for _, command := range commands {
  364. args := strings.Fields(command)
  365. out, err := exec.Command(args[0], args[1:]...).CombinedOutput()
  366. if err != nil && printerr {
  367. log.Println("error running command:", command)
  368. log.Println(strings.TrimSuffix(string(out), "\n"))
  369. }
  370. }
  371. return err
  372. }
  373. // FileExists - checks if file exists locally
  374. func FileExists(f string) bool {
  375. info, err := os.Stat(f)
  376. if os.IsNotExist(err) {
  377. return false
  378. }
  379. if err != nil && strings.Contains(err.Error(), "not a directory") {
  380. return false
  381. }
  382. if err != nil {
  383. Log("error reading file: " + f + ", " + err.Error())
  384. }
  385. return !info.IsDir()
  386. }
  387. // PrintLog - prints log
  388. func PrintLog(message string, loglevel int) {
  389. log.SetFlags(log.Flags() &^ (log.Llongfile | log.Lshortfile))
  390. if loglevel < 2 {
  391. log.Println("[netclient]", message)
  392. }
  393. }
  394. // GetSystemNetworks - get networks locally
  395. func GetSystemNetworks() ([]string, error) {
  396. var networks []string
  397. files, err := os.ReadDir(GetNetclientPathSpecific())
  398. if err != nil {
  399. return networks, err
  400. }
  401. for _, f := range files {
  402. if strings.Contains(f.Name(), "netconfig-") && !strings.Contains(f.Name(), "backup") {
  403. networkname := stringAfter(f.Name(), "netconfig-")
  404. networks = append(networks, networkname)
  405. }
  406. }
  407. return networks, err
  408. }
  409. func stringAfter(original string, substring string) string {
  410. position := strings.LastIndex(original, substring)
  411. if position == -1 {
  412. return ""
  413. }
  414. adjustedPosition := position + len(substring)
  415. if adjustedPosition >= len(original) {
  416. return ""
  417. }
  418. return original[adjustedPosition:]
  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. Log("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. // CheckWG - Checks if WireGuard is installed. If not, exit
  464. func CheckWG() {
  465. var _, err = exec.LookPath("wg")
  466. uspace := GetWireGuard()
  467. if err != nil {
  468. if uspace == "wg" {
  469. PrintLog(err.Error(), 0)
  470. log.Fatal("WireGuard not installed. Please install WireGuard (wireguard-tools) and try again.")
  471. }
  472. PrintLog("Running with userspace wireguard: "+uspace, 0)
  473. } else if uspace != "wg" {
  474. log.Println("running userspace WireGuard with " + uspace)
  475. }
  476. }
  477. // ServerAddrSliceContains - sees if a string slice contains a string element
  478. func ServerAddrSliceContains(slice []models.ServerAddr, item models.ServerAddr) bool {
  479. for _, s := range slice {
  480. if s.Address == item.Address && s.IsLeader == item.IsLeader {
  481. return true
  482. }
  483. }
  484. return false
  485. }