netclientutils.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. package ncutils
  2. import (
  3. "bytes"
  4. crand "crypto/rand"
  5. "crypto/tls"
  6. "encoding/gob"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "log"
  11. "math/rand"
  12. "net"
  13. "net/http"
  14. "os"
  15. "os/exec"
  16. "path/filepath"
  17. "regexp"
  18. "runtime"
  19. "strconv"
  20. "strings"
  21. "time"
  22. "github.com/gravitl/netmaker/models"
  23. "golang.org/x/crypto/nacl/box"
  24. "golang.zx2c4.com/wireguard/wgctrl"
  25. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  26. "google.golang.org/grpc"
  27. "google.golang.org/grpc/credentials"
  28. )
  29. // Version - version of the netclient
  30. var Version = "dev"
  31. // MAX_NAME_LENGTH - maximum node name length
  32. const MAX_NAME_LENGTH = 62
  33. // NO_DB_RECORD - error message result
  34. const NO_DB_RECORD = "no result found"
  35. // NO_DB_RECORDS - error record result
  36. const NO_DB_RECORDS = "could not find any records"
  37. // LINUX_APP_DATA_PATH - linux path
  38. const LINUX_APP_DATA_PATH = "/etc/netclient"
  39. // WINDOWS_APP_DATA_PATH - windows path
  40. const WINDOWS_APP_DATA_PATH = "C:\\ProgramData\\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. // Log - logs a message
  52. func Log(message string) {
  53. log.SetFlags(log.Flags() &^ (log.Llongfile | log.Lshortfile))
  54. log.Println("[netclient]", message)
  55. }
  56. // IsWindows - checks if is windows
  57. func IsWindows() bool {
  58. return runtime.GOOS == "windows"
  59. }
  60. // IsMac - checks if is a mac
  61. func IsMac() bool {
  62. return runtime.GOOS == "darwin"
  63. }
  64. // IsLinux - checks if is linux
  65. func IsLinux() bool {
  66. return runtime.GOOS == "linux"
  67. }
  68. // IsLinux - checks if is linux
  69. func IsFreeBSD() bool {
  70. return runtime.GOOS == "freebsd"
  71. }
  72. // GetWireGuard - checks if wg is installed
  73. func GetWireGuard() string {
  74. userspace := os.Getenv("WG_QUICK_USERSPACE_IMPLEMENTATION")
  75. if userspace != "" && (userspace == "boringtun" || userspace == "wireguard-go") {
  76. return userspace
  77. }
  78. return "wg"
  79. }
  80. // IsKernel - checks if running kernel WireGuard
  81. func IsKernel() bool {
  82. //TODO
  83. //Replace && true with some config file value
  84. //This value should be something like kernelmode, which should be 'on' by default.
  85. return IsLinux() && os.Getenv("WG_QUICK_USERSPACE_IMPLEMENTATION") == ""
  86. }
  87. // IsEmptyRecord - repeat from database
  88. func IsEmptyRecord(err error) bool {
  89. if err == nil {
  90. return false
  91. }
  92. return strings.Contains(err.Error(), NO_DB_RECORD) || strings.Contains(err.Error(), NO_DB_RECORDS)
  93. }
  94. //generate an access key value
  95. // GenPass - generates a pass
  96. func GenPass() string {
  97. var seededRand *rand.Rand = rand.New(
  98. rand.NewSource(time.Now().UnixNano()))
  99. length := 16
  100. charset := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  101. b := make([]byte, length)
  102. for i := range b {
  103. b[i] = charset[seededRand.Intn(len(charset))]
  104. }
  105. return string(b)
  106. }
  107. // GetPublicIP - gets public ip
  108. func GetPublicIP() (string, error) {
  109. iplist := []string{"https://ip.client.gravitl.com", "https://ifconfig.me", "https://api.ipify.org", "https://ipinfo.io/ip"}
  110. endpoint := ""
  111. var err error
  112. for _, ipserver := range iplist {
  113. resp, err := http.Get(ipserver)
  114. if err != nil {
  115. continue
  116. }
  117. defer resp.Body.Close()
  118. if resp.StatusCode == http.StatusOK {
  119. bodyBytes, err := io.ReadAll(resp.Body)
  120. if err != nil {
  121. continue
  122. }
  123. endpoint = string(bodyBytes)
  124. break
  125. }
  126. }
  127. if err == nil && endpoint == "" {
  128. err = errors.New("public address not found")
  129. }
  130. return endpoint, err
  131. }
  132. // GetMacAddr - get's mac address
  133. func GetMacAddr() ([]string, error) {
  134. ifas, err := net.Interfaces()
  135. if err != nil {
  136. return nil, err
  137. }
  138. var as []string
  139. for _, ifa := range ifas {
  140. a := ifa.HardwareAddr.String()
  141. if a != "" {
  142. as = append(as, a)
  143. }
  144. }
  145. return as, nil
  146. }
  147. func parsePeers(keepalive int32, peers []wgtypes.PeerConfig) (string, error) {
  148. peersString := ""
  149. if keepalive <= 0 {
  150. keepalive = 0
  151. }
  152. for _, peer := range peers {
  153. endpointString := ""
  154. if peer.Endpoint != nil && peer.Endpoint.String() != "" {
  155. endpointString += "Endpoint = " + peer.Endpoint.String()
  156. }
  157. newAllowedIps := []string{}
  158. for _, allowedIP := range peer.AllowedIPs {
  159. newAllowedIps = append(newAllowedIps, allowedIP.String())
  160. }
  161. peersString += fmt.Sprintf(`[Peer]
  162. PublicKey = %s
  163. AllowedIps = %s
  164. PersistentKeepAlive = %s
  165. %s
  166. `,
  167. peer.PublicKey.String(),
  168. strings.Join(newAllowedIps, ","),
  169. strconv.Itoa(int(keepalive)),
  170. endpointString,
  171. )
  172. }
  173. return peersString, nil
  174. }
  175. // GetLocalIP - gets local ip of machine
  176. func GetLocalIP(localrange string) (string, error) {
  177. _, localRange, err := net.ParseCIDR(localrange)
  178. if err != nil {
  179. return "", err
  180. }
  181. ifaces, err := net.Interfaces()
  182. if err != nil {
  183. return "", err
  184. }
  185. var local string
  186. found := false
  187. for _, i := range ifaces {
  188. if i.Flags&net.FlagUp == 0 {
  189. continue // interface down
  190. }
  191. if i.Flags&net.FlagLoopback != 0 {
  192. continue // loopback interface
  193. }
  194. addrs, err := i.Addrs()
  195. if err != nil {
  196. return "", err
  197. }
  198. for _, addr := range addrs {
  199. var ip net.IP
  200. switch v := addr.(type) {
  201. case *net.IPNet:
  202. if !found {
  203. ip = v.IP
  204. local = ip.String()
  205. found = localRange.Contains(ip)
  206. }
  207. case *net.IPAddr:
  208. if !found {
  209. ip = v.IP
  210. local = ip.String()
  211. found = localRange.Contains(ip)
  212. }
  213. }
  214. }
  215. }
  216. if !found || local == "" {
  217. return "", errors.New("Failed to find local IP in range " + localrange)
  218. }
  219. return local, nil
  220. }
  221. //GetNetworkIPMask - Pulls the netmask out of the network
  222. func GetNetworkIPMask(networkstring string) (string, string, error) {
  223. ip, ipnet, err := net.ParseCIDR(networkstring)
  224. if err != nil {
  225. return "", "", err
  226. }
  227. ipstring := ip.String()
  228. mask := ipnet.Mask
  229. maskstring := fmt.Sprintf("%d.%d.%d.%d", mask[0], mask[1], mask[2], mask[3])
  230. //maskstring := ipnet.Mask.String()
  231. return ipstring, maskstring, err
  232. }
  233. // GetFreePort - gets free port of machine
  234. func GetFreePort(rangestart int32) (int32, error) {
  235. if rangestart == 0 {
  236. rangestart = NETCLIENT_DEFAULT_PORT
  237. }
  238. wgclient, err := wgctrl.New()
  239. if err != nil {
  240. return 0, err
  241. }
  242. defer wgclient.Close()
  243. devices, err := wgclient.Devices()
  244. if err != nil {
  245. return 0, err
  246. }
  247. for x := rangestart; x <= 65535; x++ {
  248. conflict := false
  249. for _, i := range devices {
  250. if int32(i.ListenPort) == x {
  251. conflict = true
  252. break
  253. }
  254. }
  255. if conflict {
  256. continue
  257. }
  258. return int32(x), nil
  259. }
  260. return rangestart, err
  261. }
  262. // == OS PATH FUNCTIONS ==
  263. // GetHomeDirWindows - gets home directory in windows
  264. func GetHomeDirWindows() string {
  265. if IsWindows() {
  266. home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
  267. if home == "" {
  268. home = os.Getenv("USERPROFILE")
  269. }
  270. return home
  271. }
  272. return os.Getenv("HOME")
  273. }
  274. // GetNetclientPath - gets netclient path locally
  275. func GetNetclientPath() string {
  276. if IsWindows() {
  277. return WINDOWS_APP_DATA_PATH
  278. } else if IsMac() {
  279. return "/etc/netclient/"
  280. } else {
  281. return LINUX_APP_DATA_PATH
  282. }
  283. }
  284. // GetFileWithRetry - retry getting file X number of times before failing
  285. func GetFileWithRetry(path string, retryCount int) ([]byte, error) {
  286. var data []byte
  287. var err error
  288. for count := 0; count < retryCount; count++ {
  289. data, err = os.ReadFile(path)
  290. if err == nil {
  291. return data, err
  292. } else {
  293. PrintLog("failed to retrieve file "+path+", retrying...", 1)
  294. time.Sleep(time.Second >> 2)
  295. }
  296. }
  297. return data, err
  298. }
  299. // GetNetclientPathSpecific - gets specific netclient config path
  300. func GetNetclientPathSpecific() string {
  301. if IsWindows() {
  302. return WINDOWS_APP_DATA_PATH + "\\"
  303. } else if IsMac() {
  304. return "/etc/netclient/config/"
  305. } else {
  306. return LINUX_APP_DATA_PATH + "/config/"
  307. }
  308. }
  309. // GetNewIface - Gets the name of the real interface created on Mac
  310. func GetNewIface(dir string) (string, error) {
  311. files, _ := os.ReadDir(dir)
  312. var newestFile string
  313. var newestTime int64 = 0
  314. var err error
  315. for _, f := range files {
  316. fi, err := os.Stat(dir + f.Name())
  317. if err != nil {
  318. return "", err
  319. }
  320. currTime := fi.ModTime().Unix()
  321. if currTime > newestTime && strings.Contains(f.Name(), ".sock") {
  322. newestTime = currTime
  323. newestFile = f.Name()
  324. }
  325. }
  326. resultArr := strings.Split(newestFile, ".")
  327. if resultArr[0] == "" {
  328. err = errors.New("sock file does not exist")
  329. }
  330. return resultArr[0], err
  331. }
  332. // GetFileAsString - returns the string contents of a given file
  333. func GetFileAsString(path string) (string, error) {
  334. content, err := os.ReadFile(path)
  335. if err != nil {
  336. return "", err
  337. }
  338. return string(content), err
  339. }
  340. // GetNetclientPathSpecific - gets specific netclient config path
  341. func GetWGPathSpecific() string {
  342. if IsWindows() {
  343. return WINDOWS_APP_DATA_PATH + "\\"
  344. } else {
  345. return "/etc/wireguard/"
  346. }
  347. }
  348. // GRPCRequestOpts - gets grps request opts
  349. func GRPCRequestOpts(isSecure string) grpc.DialOption {
  350. var requestOpts grpc.DialOption
  351. requestOpts = grpc.WithInsecure()
  352. if isSecure == "on" {
  353. h2creds := credentials.NewTLS(&tls.Config{NextProtos: []string{"h2"}})
  354. requestOpts = grpc.WithTransportCredentials(h2creds)
  355. }
  356. return requestOpts
  357. }
  358. // Copy - copies a src file to dest
  359. func Copy(src, dst string) error {
  360. sourceFileStat, err := os.Stat(src)
  361. if err != nil {
  362. return err
  363. }
  364. if !sourceFileStat.Mode().IsRegular() {
  365. return errors.New(src + " is not a regular file")
  366. }
  367. source, err := os.Open(src)
  368. if err != nil {
  369. return err
  370. }
  371. defer source.Close()
  372. destination, err := os.Create(dst)
  373. if err != nil {
  374. return err
  375. }
  376. defer destination.Close()
  377. _, err = io.Copy(destination, source)
  378. if err != nil {
  379. return err
  380. }
  381. err = os.Chmod(dst, 0755)
  382. return err
  383. }
  384. // RunsCmds - runs cmds
  385. func RunCmds(commands []string, printerr bool) error {
  386. var err error
  387. for _, command := range commands {
  388. args := strings.Fields(command)
  389. out, err := exec.Command(args[0], args[1:]...).CombinedOutput()
  390. if err != nil && printerr {
  391. log.Println("error running command:", command)
  392. log.Println(strings.TrimSuffix(string(out), "\n"))
  393. }
  394. }
  395. return err
  396. }
  397. // FileExists - checks if file exists locally
  398. func FileExists(f string) bool {
  399. info, err := os.Stat(f)
  400. if os.IsNotExist(err) {
  401. return false
  402. }
  403. if err != nil && strings.Contains(err.Error(), "not a directory") {
  404. return false
  405. }
  406. if err != nil {
  407. Log("error reading file: " + f + ", " + err.Error())
  408. }
  409. return !info.IsDir()
  410. }
  411. // PrintLog - prints log
  412. func PrintLog(message string, loglevel int) {
  413. log.SetFlags(log.Flags() &^ (log.Llongfile | log.Lshortfile))
  414. if loglevel < 2 {
  415. log.Println("[netclient]", message)
  416. }
  417. }
  418. // GetSystemNetworks - get networks locally
  419. func GetSystemNetworks() ([]string, error) {
  420. var networks []string
  421. files, err := filepath.Glob(GetNetclientPathSpecific() + "netconfig-*")
  422. if err != nil {
  423. return nil, err
  424. }
  425. for _, file := range files {
  426. //don't want files such as *.bak, *.swp
  427. if filepath.Ext(file) != "" {
  428. continue
  429. }
  430. file := filepath.Base(file)
  431. temp := strings.Split(file, "-")
  432. networks = append(networks, strings.Join(temp[1:], "-"))
  433. }
  434. return networks, nil
  435. }
  436. func stringAfter(original string, substring string) string {
  437. position := strings.LastIndex(original, substring)
  438. if position == -1 {
  439. return ""
  440. }
  441. adjustedPosition := position + len(substring)
  442. if adjustedPosition >= len(original) {
  443. return ""
  444. }
  445. return original[adjustedPosition:]
  446. }
  447. // ShortenString - Brings string down to specified length. Stops names from being too long
  448. func ShortenString(input string, length int) string {
  449. output := input
  450. if len(input) > length {
  451. output = input[0:length]
  452. }
  453. return output
  454. }
  455. // DNSFormatString - Formats a string with correct usage for DNS
  456. func DNSFormatString(input string) string {
  457. reg, err := regexp.Compile("[^a-zA-Z0-9-]+")
  458. if err != nil {
  459. Log("error with regex: " + err.Error())
  460. return ""
  461. }
  462. return reg.ReplaceAllString(input, "")
  463. }
  464. // GetHostname - Gets hostname of machine
  465. func GetHostname() string {
  466. hostname, err := os.Hostname()
  467. if err != nil {
  468. return ""
  469. }
  470. if len(hostname) > MAX_NAME_LENGTH {
  471. hostname = hostname[0:MAX_NAME_LENGTH]
  472. }
  473. return hostname
  474. }
  475. // CheckUID - Checks to make sure user has root privileges
  476. func CheckUID() {
  477. // start our application
  478. out, err := RunCmd("id -u", true)
  479. if err != nil {
  480. log.Fatal(out, err)
  481. }
  482. id, err := strconv.Atoi(string(out[:len(out)-1]))
  483. if err != nil {
  484. log.Fatal(err)
  485. }
  486. if id != 0 {
  487. 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.")
  488. }
  489. }
  490. // CheckWG - Checks if WireGuard is installed. If not, exit
  491. func CheckWG() {
  492. var _, err = exec.LookPath("wg")
  493. uspace := GetWireGuard()
  494. if err != nil {
  495. if uspace == "wg" {
  496. PrintLog(err.Error(), 0)
  497. log.Fatal("WireGuard not installed. Please install WireGuard (wireguard-tools) and try again.")
  498. }
  499. PrintLog("Running with userspace wireguard: "+uspace, 0)
  500. } else if uspace != "wg" {
  501. log.Println("running userspace WireGuard with " + uspace)
  502. }
  503. }
  504. // ConvertKeyToBytes - util to convert a key to bytes to use elsewhere
  505. func ConvertKeyToBytes(key *[32]byte) ([]byte, error) {
  506. var buffer bytes.Buffer
  507. var enc = gob.NewEncoder(&buffer)
  508. if err := enc.Encode(key); err != nil {
  509. return nil, err
  510. }
  511. return buffer.Bytes(), nil
  512. }
  513. // ConvertBytesToKey - util to convert bytes to a key to use elsewhere
  514. func ConvertBytesToKey(data []byte) (*[32]byte, error) {
  515. var buffer = bytes.NewBuffer(data)
  516. var dec = gob.NewDecoder(buffer)
  517. var result = new([32]byte)
  518. var err = dec.Decode(result)
  519. if err != nil {
  520. return nil, err
  521. }
  522. return result, err
  523. }
  524. // ServerAddrSliceContains - sees if a string slice contains a string element
  525. func ServerAddrSliceContains(slice []models.ServerAddr, item models.ServerAddr) bool {
  526. for _, s := range slice {
  527. if s.Address == item.Address && s.IsLeader == item.IsLeader {
  528. return true
  529. }
  530. }
  531. return false
  532. }
  533. // BoxEncrypt - encrypts traffic box
  534. func BoxEncrypt(message []byte, recipientPubKey *[32]byte, senderPrivateKey *[32]byte) ([]byte, error) {
  535. var nonce [24]byte // 192 bits of randomization
  536. if _, err := io.ReadFull(crand.Reader, nonce[:]); err != nil {
  537. return nil, err
  538. }
  539. encrypted := box.Seal(nonce[:], message, &nonce, recipientPubKey, senderPrivateKey)
  540. return encrypted, nil
  541. }
  542. // BoxDecrypt - decrypts traffic box
  543. func BoxDecrypt(encrypted []byte, senderPublicKey *[32]byte, recipientPrivateKey *[32]byte) ([]byte, error) {
  544. var decryptNonce [24]byte
  545. copy(decryptNonce[:], encrypted[:24])
  546. decrypted, ok := box.Open(nil, encrypted[24:], &decryptNonce, senderPublicKey, recipientPrivateKey)
  547. if !ok {
  548. return nil, fmt.Errorf("could not decrypt message")
  549. }
  550. return decrypted, nil
  551. }