netclientutils.go 14 KB

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