netclientutils.go 12 KB

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