netclientutils.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. mask := ipnet.Mask
  217. maskstring := fmt.Sprintf("%d.%d.%d.%d", mask[0], mask[1], mask[2], mask[3])
  218. //maskstring := ipnet.Mask.String()
  219. return ipstring, maskstring, err
  220. }
  221. // GetFreePort - gets free port of machine
  222. func GetFreePort(rangestart int32) (int32, error) {
  223. if rangestart == 0 {
  224. rangestart = NETCLIENT_DEFAULT_PORT
  225. }
  226. wgclient, err := wgctrl.New()
  227. if err != nil {
  228. return 0, err
  229. }
  230. devices, err := wgclient.Devices()
  231. if err != nil {
  232. return 0, err
  233. }
  234. for x := rangestart; x <= 65535; x++ {
  235. conflict := false
  236. for _, i := range devices {
  237. if int32(i.ListenPort) == x {
  238. conflict = true
  239. break
  240. }
  241. }
  242. if conflict {
  243. continue
  244. }
  245. return int32(x), nil
  246. }
  247. return rangestart, err
  248. }
  249. // == OS PATH FUNCTIONS ==
  250. // GetHomeDirWindows - gets home directory in windows
  251. func GetHomeDirWindows() string {
  252. if IsWindows() {
  253. home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
  254. if home == "" {
  255. home = os.Getenv("USERPROFILE")
  256. }
  257. return home
  258. }
  259. return os.Getenv("HOME")
  260. }
  261. // GetNetclientPath - gets netclient path locally
  262. func GetNetclientPath() string {
  263. if IsWindows() {
  264. return WINDOWS_APP_DATA_PATH
  265. } else if IsMac() {
  266. return "/etc/netclient/"
  267. } else {
  268. return LINUX_APP_DATA_PATH
  269. }
  270. }
  271. // GetNetclientPathSpecific - gets specific netclient config path
  272. func GetNetclientPathSpecific() string {
  273. if IsWindows() {
  274. return WINDOWS_APP_DATA_PATH + "\\"
  275. } else if IsMac() {
  276. return "/etc/netclient/config/"
  277. } else {
  278. return LINUX_APP_DATA_PATH + "/config/"
  279. }
  280. }
  281. // GetNetclientPathSpecific - gets specific netclient config path
  282. func GetWGPathSpecific() string {
  283. if IsWindows() {
  284. return WINDOWS_WG_DATA_PATH + "\\"
  285. } else {
  286. return "/etc/wireguard/"
  287. }
  288. }
  289. // GRPCRequestOpts - gets grps request opts
  290. func GRPCRequestOpts(isSecure string) grpc.DialOption {
  291. var requestOpts grpc.DialOption
  292. requestOpts = grpc.WithInsecure()
  293. if isSecure == "on" {
  294. h2creds := credentials.NewTLS(&tls.Config{NextProtos: []string{"h2"}})
  295. requestOpts = grpc.WithTransportCredentials(h2creds)
  296. }
  297. return requestOpts
  298. }
  299. // Copy - copies a src file to dest
  300. func Copy(src, dst string) error {
  301. sourceFileStat, err := os.Stat(src)
  302. if err != nil {
  303. return err
  304. }
  305. if !sourceFileStat.Mode().IsRegular() {
  306. return errors.New(src + " is not a regular file")
  307. }
  308. source, err := os.Open(src)
  309. if err != nil {
  310. return err
  311. }
  312. defer source.Close()
  313. destination, err := os.Create(dst)
  314. if err != nil {
  315. return err
  316. }
  317. defer destination.Close()
  318. _, err = io.Copy(destination, source)
  319. if err != nil {
  320. return err
  321. }
  322. err = os.Chmod(dst, 0755)
  323. return err
  324. }
  325. // RunsCmds - runs cmds
  326. func RunCmds(commands []string, printerr bool) error {
  327. var err error
  328. for _, command := range commands {
  329. args := strings.Fields(command)
  330. out, err := exec.Command(args[0], args[1:]...).CombinedOutput()
  331. if err != nil && printerr {
  332. log.Println("error running command:", command)
  333. log.Println(strings.TrimSuffix(string(out), "\n"))
  334. }
  335. }
  336. return err
  337. }
  338. // FileExists - checks if file exists locally
  339. func FileExists(f string) bool {
  340. info, err := os.Stat(f)
  341. if os.IsNotExist(err) {
  342. return false
  343. }
  344. if err != nil && strings.Contains(err.Error(), "not a directory") {
  345. return false
  346. }
  347. if err != nil {
  348. Log("error reading file: " + f + ", " + err.Error())
  349. }
  350. return !info.IsDir()
  351. }
  352. // PrintLog - prints log
  353. func PrintLog(message string, loglevel int) {
  354. log.SetFlags(log.Flags() &^ (log.Llongfile | log.Lshortfile))
  355. if loglevel < 2 {
  356. log.Println("[netclient]", message)
  357. }
  358. }
  359. // GetSystemNetworks - get networks locally
  360. func GetSystemNetworks() ([]string, error) {
  361. var networks []string
  362. files, err := ioutil.ReadDir(GetNetclientPathSpecific())
  363. if err != nil {
  364. return networks, err
  365. }
  366. for _, f := range files {
  367. if strings.Contains(f.Name(), "netconfig-") {
  368. networkname := stringAfter(f.Name(), "netconfig-")
  369. networks = append(networks, networkname)
  370. }
  371. }
  372. return networks, err
  373. }
  374. func stringAfter(original string, substring string) string {
  375. position := strings.LastIndex(original, substring)
  376. if position == -1 {
  377. return ""
  378. }
  379. adjustedPosition := position + len(substring)
  380. if adjustedPosition >= len(original) {
  381. return ""
  382. }
  383. return original[adjustedPosition:]
  384. }
  385. func ShortenString(input string, length int) string {
  386. output := input
  387. if len(input) > length {
  388. output = input[0:length]
  389. }
  390. return output
  391. }
  392. func DNSFormatString(input string) string {
  393. reg, err := regexp.Compile("[^a-zA-Z0-9-]+")
  394. if err != nil {
  395. Log("error with regex: " + err.Error())
  396. return ""
  397. }
  398. return reg.ReplaceAllString(input, "")
  399. }