netclientutils.go 9.5 KB

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