netclientutils.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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_APP_DATA_PATH - windows path
  32. const WINDOWS_WG_DATA_PATH = "C:\\Program Files\\WireGuard\\Data\\Configurations"
  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. func GetNetworkIPMask(networkstring string) (string, string, error) {
  243. ip, ipnet, err := net.ParseCIDR(networkstring)
  244. if err != nil {
  245. return "", "", err
  246. }
  247. ipstring := ip.String()
  248. maskstring := ipnet.Mask.String()
  249. return ipstring, maskstring, err
  250. }
  251. // GetFreePort - gets free port of machine
  252. func GetFreePort(rangestart int32) (int32, error) {
  253. if rangestart == 0 {
  254. rangestart = NETCLIENT_DEFAULT_PORT
  255. }
  256. wgclient, err := wgctrl.New()
  257. if err != nil {
  258. return 0, err
  259. }
  260. devices, err := wgclient.Devices()
  261. if err != nil {
  262. return 0, err
  263. }
  264. for x := rangestart; x <= 65535; x++ {
  265. conflict := false
  266. for _, i := range devices {
  267. if int32(i.ListenPort) == x {
  268. conflict = true
  269. break
  270. }
  271. }
  272. if conflict {
  273. continue
  274. }
  275. return int32(x), nil
  276. }
  277. return rangestart, err
  278. }
  279. // == OS PATH FUNCTIONS ==
  280. // GetHomeDirWindows - gets home directory in windows
  281. func GetHomeDirWindows() string {
  282. if IsWindows() {
  283. home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
  284. if home == "" {
  285. home = os.Getenv("USERPROFILE")
  286. }
  287. return home
  288. }
  289. return os.Getenv("HOME")
  290. }
  291. // GetNetclientPath - gets netclient path locally
  292. func GetNetclientPath() string {
  293. if IsWindows() {
  294. return WINDOWS_APP_DATA_PATH
  295. } else if IsMac() {
  296. return "/etc/netclient/"
  297. } else {
  298. return LINUX_APP_DATA_PATH
  299. }
  300. }
  301. // GetNetclientPathSpecific - gets specific netclient config path
  302. func GetNetclientPathSpecific() string {
  303. if IsWindows() {
  304. return WINDOWS_APP_DATA_PATH + "\\"
  305. } else if IsMac() {
  306. return "/etc/netclient/config/"
  307. } else {
  308. return LINUX_APP_DATA_PATH + "/config/"
  309. }
  310. }
  311. // GetNetclientPathSpecific - gets specific netclient config path
  312. func GetWGPathSpecific() string {
  313. if IsWindows() {
  314. return WINDOWS_WG_DATA_PATH + "\\"
  315. } else {
  316. return "/etc/wireguard/"
  317. }
  318. }
  319. // GRPCRequestOpts - gets grps request opts
  320. func GRPCRequestOpts(isSecure string) grpc.DialOption {
  321. var requestOpts grpc.DialOption
  322. requestOpts = grpc.WithInsecure()
  323. if isSecure == "on" {
  324. h2creds := credentials.NewTLS(&tls.Config{NextProtos: []string{"h2"}})
  325. requestOpts = grpc.WithTransportCredentials(h2creds)
  326. }
  327. return requestOpts
  328. }
  329. // Copy - copies a src file to dest
  330. func Copy(src, dst string) error {
  331. sourceFileStat, err := os.Stat(src)
  332. if err != nil {
  333. return err
  334. }
  335. if !sourceFileStat.Mode().IsRegular() {
  336. return errors.New(src + " is not a regular file")
  337. }
  338. source, err := os.Open(src)
  339. if err != nil {
  340. return err
  341. }
  342. defer source.Close()
  343. destination, err := os.Create(dst)
  344. if err != nil {
  345. return err
  346. }
  347. defer destination.Close()
  348. _, err = io.Copy(destination, source)
  349. if err != nil {
  350. return err
  351. }
  352. err = os.Chmod(dst, 0755)
  353. return err
  354. }
  355. // RunCmd - runs a local command
  356. func RunCmd(command string, printerr bool) (string, error) {
  357. args := strings.Fields(command)
  358. cmd := exec.Command(args[0], args[1:]...)
  359. cmd.Wait()
  360. out, err := cmd.CombinedOutput()
  361. if err != nil && printerr {
  362. log.Println("error running command:", command)
  363. log.Println(strings.TrimSuffix(string(out), "\n"))
  364. }
  365. return string(out), err
  366. }
  367. /* new version - cant build on windows
  368. func RunCmd(command string, printerr bool) (string, error) {
  369. args := strings.Fields(command)
  370. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  371. defer cancel()
  372. cmd := exec.Command(args[0], args[1:]...)
  373. cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
  374. go func() {
  375. <-ctx.Done()
  376. _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
  377. }()
  378. out, err := cmd.CombinedOutput()
  379. if err != nil && printerr {
  380. log.Println("error running command:", command)
  381. log.Println(strings.TrimSuffix(string(out), "\n"))
  382. }
  383. return string(out), err
  384. }
  385. */
  386. // RunsCmds - runs cmds
  387. func RunCmds(commands []string, printerr bool) error {
  388. var err error
  389. for _, command := range commands {
  390. args := strings.Fields(command)
  391. out, err := exec.Command(args[0], args[1:]...).CombinedOutput()
  392. if err != nil && printerr {
  393. log.Println("error running command:", command)
  394. log.Println(strings.TrimSuffix(string(out), "\n"))
  395. }
  396. }
  397. return err
  398. }
  399. // FileExists - checks if file exists locally
  400. func FileExists(f string) bool {
  401. info, err := os.Stat(f)
  402. if os.IsNotExist(err) {
  403. return false
  404. }
  405. if err != nil && strings.Contains(err.Error(), "not a directory") {
  406. return false
  407. }
  408. if err != nil {
  409. Log("error reading file: " + f + ", " + err.Error())
  410. }
  411. return !info.IsDir()
  412. }
  413. // PrintLog - prints log
  414. func PrintLog(message string, loglevel int) {
  415. log.SetFlags(log.Flags() &^ (log.Llongfile | log.Lshortfile))
  416. if loglevel < 2 {
  417. log.Println("[netclient]", message)
  418. }
  419. }
  420. // GetSystemNetworks - get networks locally
  421. func GetSystemNetworks() ([]string, error) {
  422. var networks []string
  423. files, err := ioutil.ReadDir(GetNetclientPathSpecific())
  424. if err != nil {
  425. return networks, err
  426. }
  427. for _, f := range files {
  428. if strings.Contains(f.Name(), "netconfig-") {
  429. networkname := stringAfter(f.Name(), "netconfig-")
  430. networks = append(networks, networkname)
  431. }
  432. }
  433. return networks, err
  434. }
  435. func stringAfter(original string, substring string) string {
  436. position := strings.LastIndex(original, substring)
  437. if position == -1 {
  438. return ""
  439. }
  440. adjustedPosition := position + len(substring)
  441. if adjustedPosition >= len(original) {
  442. return ""
  443. }
  444. return original[adjustedPosition:]
  445. }