netclientutils.go 9.7 KB

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