netclientutils.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. package ncutils
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "log"
  10. "math/rand"
  11. "net"
  12. "net/http"
  13. "os"
  14. "os/exec"
  15. "runtime"
  16. "strconv"
  17. "strings"
  18. "syscall"
  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, fwmark int32, perskeepalive int32, peers []wgtypes.PeerConfig) (string, error) {
  165. peersString, err := parsePeers(perskeepalive, peers)
  166. var listenPortString string
  167. var fwmarkString string
  168. if mtu <= 0 {
  169. mtu = 1280
  170. }
  171. if listenPort != "" {
  172. listenPortString += "ListenPort = " + listenPort
  173. }
  174. if fwmark != 0 {
  175. fwmarkString += "FWMark = " + strconv.Itoa(int(fwmark))
  176. }
  177. if err != nil {
  178. return "", err
  179. }
  180. config := fmt.Sprintf(`[Interface]
  181. Address = %s
  182. PrivateKey = %s
  183. MTU = %s
  184. %s
  185. %s
  186. %s
  187. `,
  188. address+"/32",
  189. privatekey,
  190. strconv.Itoa(int(mtu)),
  191. listenPortString,
  192. fwmarkString,
  193. peersString)
  194. return config, nil
  195. }
  196. // GetLocalIP - gets local ip of machine
  197. func GetLocalIP(localrange string) (string, error) {
  198. _, localRange, err := net.ParseCIDR(localrange)
  199. if err != nil {
  200. return "", err
  201. }
  202. ifaces, err := net.Interfaces()
  203. if err != nil {
  204. return "", err
  205. }
  206. var local string
  207. found := false
  208. for _, i := range ifaces {
  209. if i.Flags&net.FlagUp == 0 {
  210. continue // interface down
  211. }
  212. if i.Flags&net.FlagLoopback != 0 {
  213. continue // loopback interface
  214. }
  215. addrs, err := i.Addrs()
  216. if err != nil {
  217. return "", err
  218. }
  219. for _, addr := range addrs {
  220. var ip net.IP
  221. switch v := addr.(type) {
  222. case *net.IPNet:
  223. if !found {
  224. ip = v.IP
  225. local = ip.String()
  226. found = localRange.Contains(ip)
  227. }
  228. case *net.IPAddr:
  229. if !found {
  230. ip = v.IP
  231. local = ip.String()
  232. found = localRange.Contains(ip)
  233. }
  234. }
  235. }
  236. }
  237. if !found || local == "" {
  238. return "", errors.New("Failed to find local IP in range " + localrange)
  239. }
  240. return local, nil
  241. }
  242. // GetFreePort - gets free port of machine
  243. func GetFreePort(rangestart int32) (int32, error) {
  244. if rangestart == 0 {
  245. rangestart = NETCLIENT_DEFAULT_PORT
  246. }
  247. wgclient, err := wgctrl.New()
  248. if err != nil {
  249. return 0, err
  250. }
  251. devices, err := wgclient.Devices()
  252. if err != nil {
  253. return 0, err
  254. }
  255. for x := rangestart; x <= 65535; x++ {
  256. conflict := false
  257. for _, i := range devices {
  258. if int32(i.ListenPort) == x {
  259. conflict = true
  260. break
  261. }
  262. }
  263. if conflict {
  264. continue
  265. }
  266. return int32(x), nil
  267. }
  268. return rangestart, err
  269. }
  270. // == OS PATH FUNCTIONS ==
  271. // GetHomeDirWindows - gets home directory in windows
  272. func GetHomeDirWindows() string {
  273. if IsWindows() {
  274. home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
  275. if home == "" {
  276. home = os.Getenv("USERPROFILE")
  277. }
  278. return home
  279. }
  280. return os.Getenv("HOME")
  281. }
  282. // GetNetclientPath - gets netclient path locally
  283. func GetNetclientPath() string {
  284. if IsWindows() {
  285. return WINDOWS_APP_DATA_PATH
  286. } else if IsMac() {
  287. return "/etc/netclient/"
  288. } else {
  289. return LINUX_APP_DATA_PATH
  290. }
  291. }
  292. // GetNetclientPathSpecific - gets specific netclient config path
  293. func GetNetclientPathSpecific() string {
  294. if IsWindows() {
  295. return WINDOWS_APP_DATA_PATH + "\\"
  296. } else if IsMac() {
  297. return "/etc/netclient/config/"
  298. } else {
  299. return LINUX_APP_DATA_PATH + "/config/"
  300. }
  301. }
  302. // GRPCRequestOpts - gets grps request opts
  303. func GRPCRequestOpts(isSecure string) grpc.DialOption {
  304. var requestOpts grpc.DialOption
  305. requestOpts = grpc.WithInsecure()
  306. if isSecure == "on" {
  307. h2creds := credentials.NewTLS(&tls.Config{NextProtos: []string{"h2"}})
  308. requestOpts = grpc.WithTransportCredentials(h2creds)
  309. }
  310. return requestOpts
  311. }
  312. // Copy - copies a src file to dest
  313. func Copy(src, dst string) error {
  314. sourceFileStat, err := os.Stat(src)
  315. if err != nil {
  316. return err
  317. }
  318. if !sourceFileStat.Mode().IsRegular() {
  319. return errors.New(src + " is not a regular file")
  320. }
  321. source, err := os.Open(src)
  322. if err != nil {
  323. return err
  324. }
  325. defer source.Close()
  326. destination, err := os.Create(dst)
  327. if err != nil {
  328. return err
  329. }
  330. defer destination.Close()
  331. _, err = io.Copy(destination, source)
  332. if err != nil {
  333. return err
  334. }
  335. err = os.Chmod(dst, 0755)
  336. return err
  337. }
  338. // RunCmd - runs a local command
  339. func RunCmd(command string, printerr bool) (string, error) {
  340. args := strings.Fields(command)
  341. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  342. defer cancel()
  343. cmd := exec.Command(args[0], args[1:]...)
  344. cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
  345. go func() {
  346. <-ctx.Done()
  347. _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
  348. }()
  349. out, err := cmd.CombinedOutput()
  350. if err != nil && printerr {
  351. log.Println("error running command:", command)
  352. log.Println(strings.TrimSuffix(string(out), "\n"))
  353. }
  354. return string(out), err
  355. }
  356. // RunsCmds - runs cmds
  357. func RunCmds(commands []string, printerr bool) error {
  358. var err error
  359. for _, command := range commands {
  360. args := strings.Fields(command)
  361. out, err := exec.Command(args[0], args[1:]...).CombinedOutput()
  362. if err != nil && printerr {
  363. log.Println("error running command:", command)
  364. log.Println(strings.TrimSuffix(string(out), "\n"))
  365. }
  366. }
  367. return err
  368. }
  369. // FileExists - checks if file exists locally
  370. func FileExists(f string) bool {
  371. info, err := os.Stat(f)
  372. if os.IsNotExist(err) {
  373. return false
  374. }
  375. if err != nil && strings.Contains(err.Error(), "not a directory") {
  376. return false
  377. }
  378. if err != nil {
  379. Log("error reading file: " + f + ", " + err.Error())
  380. }
  381. return !info.IsDir()
  382. }
  383. // PrintLog - prints log
  384. func PrintLog(message string, loglevel int) {
  385. log.SetFlags(log.Flags() &^ (log.Llongfile | log.Lshortfile))
  386. if loglevel < 2 {
  387. log.Println("[netclient]", message)
  388. }
  389. }
  390. // GetSystemNetworks - get networks locally
  391. func GetSystemNetworks() ([]string, error) {
  392. var networks []string
  393. files, err := ioutil.ReadDir(GetNetclientPathSpecific())
  394. if err != nil {
  395. return networks, err
  396. }
  397. for _, f := range files {
  398. if strings.Contains(f.Name(), "netconfig-") {
  399. networkname := stringAfter(f.Name(), "netconfig-")
  400. networks = append(networks, networkname)
  401. }
  402. }
  403. return networks, err
  404. }
  405. func stringAfter(original string, substring string) string {
  406. position := strings.LastIndex(original, substring)
  407. if position == -1 {
  408. return ""
  409. }
  410. adjustedPosition := position + len(substring)
  411. if adjustedPosition >= len(original) {
  412. return ""
  413. }
  414. return original[adjustedPosition:]
  415. }