netclientutils.go 14 KB

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