netclientutils.go 10 KB

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