netclientutils.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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. endpointString := ""
  136. if peer.Endpoint != nil && peer.Endpoint.String() != "" {
  137. endpointString += "Endpoint = " + peer.Endpoint.String()
  138. }
  139. newAllowedIps := []string{}
  140. for _, allowedIP := range peer.AllowedIPs {
  141. newAllowedIps = append(newAllowedIps, allowedIP.String())
  142. }
  143. peersString += fmt.Sprintf(`[Peer]
  144. PublicKey = %s
  145. AllowedIps = %s
  146. PersistentKeepAlive = %s
  147. %s
  148. `,
  149. peer.PublicKey.String(),
  150. strings.Join(newAllowedIps, ","),
  151. strconv.Itoa(int(keepalive)),
  152. endpointString,
  153. )
  154. }
  155. return peersString, nil
  156. }
  157. // CreateUserSpaceConf - creates a user space WireGuard conf
  158. func CreateUserSpaceConf(address string, privatekey string, listenPort string, mtu int32, perskeepalive int32, peers []wgtypes.PeerConfig) (string, error) {
  159. peersString, err := parsePeers(perskeepalive, peers)
  160. listenPortString := ""
  161. if mtu <= 0 {
  162. mtu = 1280
  163. }
  164. if listenPort != "" {
  165. listenPortString += "ListenPort = " + listenPort
  166. }
  167. if err != nil {
  168. return "", err
  169. }
  170. config := fmt.Sprintf(`[Interface]
  171. Address = %s
  172. PrivateKey = %s
  173. MTU = %s
  174. %s
  175. %s
  176. `,
  177. address+"/32",
  178. privatekey,
  179. strconv.Itoa(int(mtu)),
  180. listenPortString,
  181. peersString)
  182. return config, nil
  183. }
  184. // GetLocalIP - gets local ip of machine
  185. func GetLocalIP(localrange string) (string, error) {
  186. _, localRange, err := net.ParseCIDR(localrange)
  187. if err != nil {
  188. return "", err
  189. }
  190. ifaces, err := net.Interfaces()
  191. if err != nil {
  192. return "", err
  193. }
  194. var local string
  195. found := false
  196. for _, i := range ifaces {
  197. if i.Flags&net.FlagUp == 0 {
  198. continue // interface down
  199. }
  200. if i.Flags&net.FlagLoopback != 0 {
  201. continue // loopback interface
  202. }
  203. addrs, err := i.Addrs()
  204. if err != nil {
  205. return "", err
  206. }
  207. for _, addr := range addrs {
  208. var ip net.IP
  209. switch v := addr.(type) {
  210. case *net.IPNet:
  211. if !found {
  212. ip = v.IP
  213. local = ip.String()
  214. found = localRange.Contains(ip)
  215. }
  216. case *net.IPAddr:
  217. if !found {
  218. ip = v.IP
  219. local = ip.String()
  220. found = localRange.Contains(ip)
  221. }
  222. }
  223. }
  224. }
  225. if !found || local == "" {
  226. return "", errors.New("Failed to find local IP in range " + localrange)
  227. }
  228. return local, nil
  229. }
  230. // GetFreePort - gets free port of machine
  231. func GetFreePort(rangestart int32) (int32, error) {
  232. if rangestart == 0 {
  233. rangestart = NETCLIENT_DEFAULT_PORT
  234. }
  235. wgclient, err := wgctrl.New()
  236. if err != nil {
  237. return 0, err
  238. }
  239. devices, err := wgclient.Devices()
  240. if err != nil {
  241. return 0, err
  242. }
  243. for x := rangestart; x <= 65535; x++ {
  244. conflict := false
  245. for _, i := range devices {
  246. if int32(i.ListenPort) == x {
  247. conflict = true
  248. break
  249. }
  250. }
  251. if conflict {
  252. continue
  253. }
  254. return int32(x), nil
  255. }
  256. return rangestart, err
  257. }
  258. // == OS PATH FUNCTIONS ==
  259. // GetHomeDirWindows - gets home directory in windows
  260. func GetHomeDirWindows() string {
  261. if IsWindows() {
  262. home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
  263. if home == "" {
  264. home = os.Getenv("USERPROFILE")
  265. }
  266. return home
  267. }
  268. return os.Getenv("HOME")
  269. }
  270. // GetNetclientPath - gets netclient path locally
  271. func GetNetclientPath() string {
  272. if IsWindows() {
  273. return WINDOWS_APP_DATA_PATH
  274. } else if IsMac() {
  275. return "/etc/netclient/"
  276. } else {
  277. return LINUX_APP_DATA_PATH
  278. }
  279. }
  280. // GetNetclientPathSpecific - gets specific netclient config path
  281. func GetNetclientPathSpecific() string {
  282. if IsWindows() {
  283. return WINDOWS_APP_DATA_PATH + "\\"
  284. } else if IsMac() {
  285. return "/etc/netclient/config/"
  286. } else {
  287. return LINUX_APP_DATA_PATH + "/config/"
  288. }
  289. }
  290. // GRPCRequestOpts - gets grps request opts
  291. func GRPCRequestOpts(isSecure string) grpc.DialOption {
  292. var requestOpts grpc.DialOption
  293. requestOpts = grpc.WithInsecure()
  294. if isSecure == "on" {
  295. h2creds := credentials.NewTLS(&tls.Config{NextProtos: []string{"h2"}})
  296. requestOpts = grpc.WithTransportCredentials(h2creds)
  297. }
  298. return requestOpts
  299. }
  300. // Copy - copies a src file to dest
  301. func Copy(src, dst string) (int64, error) {
  302. sourceFileStat, err := os.Stat(src)
  303. if err != nil {
  304. return 0, err
  305. }
  306. if !sourceFileStat.Mode().IsRegular() {
  307. return 0, errors.New(src + " is not a regular file")
  308. }
  309. source, err := os.Open(src)
  310. if err != nil {
  311. return 0, err
  312. }
  313. defer source.Close()
  314. destination, err := os.Create(dst)
  315. if err != nil {
  316. return 0, err
  317. }
  318. defer destination.Close()
  319. nBytes, err := io.Copy(destination, source)
  320. err = os.Chmod(dst, 0755)
  321. if err != nil {
  322. log.Println(err)
  323. }
  324. return nBytes, err
  325. }
  326. // RunCmd - runs a local command
  327. func RunCmd(command string, printerr bool) (string, error) {
  328. args := strings.Fields(command)
  329. cmd := exec.Command(args[0], args[1:]...)
  330. cmd.Wait()
  331. out, err := cmd.CombinedOutput()
  332. if err != nil && printerr {
  333. log.Println("error running command:", command)
  334. log.Println(strings.TrimSuffix(string(out), "\n"))
  335. }
  336. return string(out), err
  337. }
  338. // RunsCmds - runs cmds
  339. func RunCmds(commands []string, printerr bool) error {
  340. var err error
  341. for _, command := range commands {
  342. args := strings.Fields(command)
  343. out, err := exec.Command(args[0], args[1:]...).CombinedOutput()
  344. if err != nil && printerr {
  345. log.Println("error running command:", command)
  346. log.Println(strings.TrimSuffix(string(out), "\n"))
  347. }
  348. }
  349. return err
  350. }
  351. // FileExists - checks if file exists locally
  352. func FileExists(f string) bool {
  353. info, err := os.Stat(f)
  354. if os.IsNotExist(err) {
  355. return false
  356. }
  357. return !info.IsDir()
  358. }
  359. // PrintLog - prints log
  360. func PrintLog(message string, loglevel int) {
  361. log.SetFlags(log.Flags() &^ (log.Llongfile | log.Lshortfile))
  362. if loglevel < 2 {
  363. log.Println("[netclient]", message)
  364. }
  365. }
  366. // GetSystemNetworks - get networks locally
  367. func GetSystemNetworks() ([]string, error) {
  368. var networks []string
  369. files, err := ioutil.ReadDir(GetNetclientPathSpecific())
  370. if err != nil {
  371. return networks, err
  372. }
  373. for _, f := range files {
  374. if strings.Contains(f.Name(), "netconfig-") {
  375. networkname := stringAfter(f.Name(), "netconfig-")
  376. networks = append(networks, networkname)
  377. }
  378. }
  379. return networks, err
  380. }
  381. func stringAfter(original string, substring string) string {
  382. position := strings.LastIndex(original, substring)
  383. if position == -1 {
  384. return ""
  385. }
  386. adjustedPosition := position + len(substring)
  387. if adjustedPosition >= len(original) {
  388. return ""
  389. }
  390. return original[adjustedPosition:]
  391. }