netclientutils.go 15 KB

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