netclientutils.go 14 KB

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