netclientutils.go 10.0 KB

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