netclientutils.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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. // GetNetclientPathSpecific - gets specific netclient config path
  285. func GetNetclientPathSpecific() string {
  286. if IsWindows() {
  287. return WINDOWS_APP_DATA_PATH + "\\"
  288. } else if IsMac() {
  289. return "/etc/netclient/config/"
  290. } else {
  291. return LINUX_APP_DATA_PATH + "/config/"
  292. }
  293. }
  294. // GetNewIface - Gets the name of the real interface created on Mac
  295. func GetNewIface(dir string) (string, error) {
  296. files, _ := os.ReadDir(dir)
  297. var newestFile string
  298. var newestTime int64 = 0
  299. var err error
  300. for _, f := range files {
  301. fi, err := os.Stat(dir + f.Name())
  302. if err != nil {
  303. return "", err
  304. }
  305. currTime := fi.ModTime().Unix()
  306. if currTime > newestTime && strings.Contains(f.Name(), ".sock") {
  307. newestTime = currTime
  308. newestFile = f.Name()
  309. }
  310. }
  311. resultArr := strings.Split(newestFile, ".")
  312. if resultArr[0] == "" {
  313. err = errors.New("sock file does not exist")
  314. }
  315. return resultArr[0], err
  316. }
  317. // GetFileAsString - returns the string contents of a given file
  318. func GetFileAsString(path string) (string, error) {
  319. content, err := os.ReadFile(path)
  320. if err != nil {
  321. return "", err
  322. }
  323. return string(content), err
  324. }
  325. // GetNetclientPathSpecific - gets specific netclient config path
  326. func GetWGPathSpecific() string {
  327. if IsWindows() {
  328. return WINDOWS_APP_DATA_PATH + "\\"
  329. } else {
  330. return "/etc/wireguard/"
  331. }
  332. }
  333. // GRPCRequestOpts - gets grps request opts
  334. func GRPCRequestOpts(isSecure string) grpc.DialOption {
  335. var requestOpts grpc.DialOption
  336. requestOpts = grpc.WithInsecure()
  337. if isSecure == "on" {
  338. h2creds := credentials.NewTLS(&tls.Config{NextProtos: []string{"h2"}})
  339. requestOpts = grpc.WithTransportCredentials(h2creds)
  340. }
  341. return requestOpts
  342. }
  343. // Copy - copies a src file to dest
  344. func Copy(src, dst string) error {
  345. sourceFileStat, err := os.Stat(src)
  346. if err != nil {
  347. return err
  348. }
  349. if !sourceFileStat.Mode().IsRegular() {
  350. return errors.New(src + " is not a regular file")
  351. }
  352. source, err := os.Open(src)
  353. if err != nil {
  354. return err
  355. }
  356. defer source.Close()
  357. destination, err := os.Create(dst)
  358. if err != nil {
  359. return err
  360. }
  361. defer destination.Close()
  362. _, err = io.Copy(destination, source)
  363. if err != nil {
  364. return err
  365. }
  366. err = os.Chmod(dst, 0755)
  367. return err
  368. }
  369. // RunsCmds - runs cmds
  370. func RunCmds(commands []string, printerr bool) error {
  371. var err error
  372. for _, command := range commands {
  373. args := strings.Fields(command)
  374. out, err := exec.Command(args[0], args[1:]...).CombinedOutput()
  375. if err != nil && printerr {
  376. log.Println("error running command:", command)
  377. log.Println(strings.TrimSuffix(string(out), "\n"))
  378. }
  379. }
  380. return err
  381. }
  382. // FileExists - checks if file exists locally
  383. func FileExists(f string) bool {
  384. info, err := os.Stat(f)
  385. if os.IsNotExist(err) {
  386. return false
  387. }
  388. if err != nil && strings.Contains(err.Error(), "not a directory") {
  389. return false
  390. }
  391. if err != nil {
  392. Log("error reading file: " + f + ", " + err.Error())
  393. }
  394. return !info.IsDir()
  395. }
  396. // PrintLog - prints log
  397. func PrintLog(message string, loglevel int) {
  398. log.SetFlags(log.Flags() &^ (log.Llongfile | log.Lshortfile))
  399. if loglevel < 2 {
  400. log.Println("[netclient]", message)
  401. }
  402. }
  403. // GetSystemNetworks - get networks locally
  404. func GetSystemNetworks() ([]string, error) {
  405. var networks []string
  406. files, err := filepath.Glob(GetNetclientPathSpecific() + "netconfig-*")
  407. if err != nil {
  408. return nil, err
  409. }
  410. for _, file := range files {
  411. //don't want files such as *.bak, *.swp
  412. if filepath.Ext(file) != "" {
  413. continue
  414. }
  415. file := filepath.Base(file)
  416. temp := strings.Split(file, "-")
  417. networks = append(networks, strings.Join(temp[1:], "-"))
  418. }
  419. return networks, nil
  420. }
  421. func stringAfter(original string, substring string) string {
  422. position := strings.LastIndex(original, substring)
  423. if position == -1 {
  424. return ""
  425. }
  426. adjustedPosition := position + len(substring)
  427. if adjustedPosition >= len(original) {
  428. return ""
  429. }
  430. return original[adjustedPosition:]
  431. }
  432. // ShortenString - Brings string down to specified length. Stops names from being too long
  433. func ShortenString(input string, length int) string {
  434. output := input
  435. if len(input) > length {
  436. output = input[0:length]
  437. }
  438. return output
  439. }
  440. // DNSFormatString - Formats a string with correct usage for DNS
  441. func DNSFormatString(input string) string {
  442. reg, err := regexp.Compile("[^a-zA-Z0-9-]+")
  443. if err != nil {
  444. Log("error with regex: " + err.Error())
  445. return ""
  446. }
  447. return reg.ReplaceAllString(input, "")
  448. }
  449. // GetHostname - Gets hostname of machine
  450. func GetHostname() string {
  451. hostname, err := os.Hostname()
  452. if err != nil {
  453. return ""
  454. }
  455. if len(hostname) > MAX_NAME_LENGTH {
  456. hostname = hostname[0:MAX_NAME_LENGTH]
  457. }
  458. return hostname
  459. }
  460. // CheckUID - Checks to make sure user has root privileges
  461. func CheckUID() {
  462. // start our application
  463. out, err := RunCmd("id -u", true)
  464. if err != nil {
  465. log.Fatal(out, err)
  466. }
  467. id, err := strconv.Atoi(string(out[:len(out)-1]))
  468. if err != nil {
  469. log.Fatal(err)
  470. }
  471. if id != 0 {
  472. 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.")
  473. }
  474. }
  475. // CheckWG - Checks if WireGuard is installed. If not, exit
  476. func CheckWG() {
  477. var _, err = exec.LookPath("wg")
  478. uspace := GetWireGuard()
  479. if err != nil {
  480. if uspace == "wg" {
  481. PrintLog(err.Error(), 0)
  482. log.Fatal("WireGuard not installed. Please install WireGuard (wireguard-tools) and try again.")
  483. }
  484. PrintLog("Running with userspace wireguard: "+uspace, 0)
  485. } else if uspace != "wg" {
  486. log.Println("running userspace WireGuard with " + uspace)
  487. }
  488. }
  489. // ConvertKeyToBytes - util to convert a key to bytes to use elsewhere
  490. func ConvertKeyToBytes(key *[32]byte) ([]byte, error) {
  491. var buffer bytes.Buffer
  492. var enc = gob.NewEncoder(&buffer)
  493. if err := enc.Encode(key); err != nil {
  494. return nil, err
  495. }
  496. return buffer.Bytes(), nil
  497. }
  498. // ConvertBytesToKey - util to convert bytes to a key to use elsewhere
  499. func ConvertBytesToKey(data []byte) (*[32]byte, error) {
  500. var buffer = bytes.NewBuffer(data)
  501. var dec = gob.NewDecoder(buffer)
  502. var result = new([32]byte)
  503. var err = dec.Decode(result)
  504. if err != nil {
  505. return nil, err
  506. }
  507. return result, err
  508. }
  509. // ServerAddrSliceContains - sees if a string slice contains a string element
  510. func ServerAddrSliceContains(slice []models.ServerAddr, item models.ServerAddr) bool {
  511. for _, s := range slice {
  512. if s.Address == item.Address && s.IsLeader == item.IsLeader {
  513. return true
  514. }
  515. }
  516. return false
  517. }
  518. // BoxEncrypt - encrypts traffic box
  519. func BoxEncrypt(message []byte, recipientPubKey *[32]byte, senderPrivateKey *[32]byte) ([]byte, error) {
  520. var nonce [24]byte // 192 bits of randomization
  521. if _, err := io.ReadFull(crand.Reader, nonce[:]); err != nil {
  522. return nil, err
  523. }
  524. encrypted := box.Seal(nonce[:], message, &nonce, recipientPubKey, senderPrivateKey)
  525. return encrypted, nil
  526. }
  527. // BoxDecrypt - decrypts traffic box
  528. func BoxDecrypt(encrypted []byte, senderPublicKey *[32]byte, recipientPrivateKey *[32]byte) ([]byte, error) {
  529. var decryptNonce [24]byte
  530. copy(decryptNonce[:], encrypted[:24])
  531. decrypted, ok := box.Open(nil, encrypted[24:], &decryptNonce, senderPublicKey, recipientPrivateKey)
  532. if !ok {
  533. return nil, fmt.Errorf("could not decrypt message")
  534. }
  535. return decrypted, nil
  536. }