netclientutils.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. // 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. // GetNetclientPathSpecific - gets specific netclient config path
  303. func GetWGPathSpecific() string {
  304. if IsWindows() {
  305. return WINDOWS_WG_DATA_PATH + "\\"
  306. } else {
  307. return "/etc/wireguard/"
  308. }
  309. }
  310. // GRPCRequestOpts - gets grps request opts
  311. func GRPCRequestOpts(isSecure string) grpc.DialOption {
  312. var requestOpts grpc.DialOption
  313. requestOpts = grpc.WithInsecure()
  314. if isSecure == "on" {
  315. h2creds := credentials.NewTLS(&tls.Config{NextProtos: []string{"h2"}})
  316. requestOpts = grpc.WithTransportCredentials(h2creds)
  317. }
  318. return requestOpts
  319. }
  320. // Copy - copies a src file to dest
  321. func Copy(src, dst string) error {
  322. sourceFileStat, err := os.Stat(src)
  323. if err != nil {
  324. return err
  325. }
  326. if !sourceFileStat.Mode().IsRegular() {
  327. return errors.New(src + " is not a regular file")
  328. }
  329. source, err := os.Open(src)
  330. if err != nil {
  331. return err
  332. }
  333. defer source.Close()
  334. destination, err := os.Create(dst)
  335. if err != nil {
  336. return err
  337. }
  338. defer destination.Close()
  339. _, err = io.Copy(destination, source)
  340. if err != nil {
  341. return err
  342. }
  343. err = os.Chmod(dst, 0755)
  344. return err
  345. }
  346. // RunCmd - runs a local command
  347. func RunCmd(command string, printerr bool) (string, error) {
  348. args := strings.Fields(command)
  349. cmd := exec.Command(args[0], args[1:]...)
  350. cmd.Wait()
  351. out, err := cmd.CombinedOutput()
  352. if err != nil && printerr {
  353. log.Println("error running command:", command)
  354. log.Println(strings.TrimSuffix(string(out), "\n"))
  355. }
  356. return string(out), err
  357. }
  358. /* new version - cant build on windows
  359. func RunCmd(command string, printerr bool) (string, error) {
  360. args := strings.Fields(command)
  361. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  362. defer cancel()
  363. cmd := exec.Command(args[0], args[1:]...)
  364. cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
  365. go func() {
  366. <-ctx.Done()
  367. _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
  368. }()
  369. out, err := cmd.CombinedOutput()
  370. if err != nil && printerr {
  371. log.Println("error running command:", command)
  372. log.Println(strings.TrimSuffix(string(out), "\n"))
  373. }
  374. return string(out), err
  375. }
  376. */
  377. // RunsCmds - runs cmds
  378. func RunCmds(commands []string, printerr bool) error {
  379. var err error
  380. for _, command := range commands {
  381. args := strings.Fields(command)
  382. out, err := exec.Command(args[0], args[1:]...).CombinedOutput()
  383. if err != nil && printerr {
  384. log.Println("error running command:", command)
  385. log.Println(strings.TrimSuffix(string(out), "\n"))
  386. }
  387. }
  388. return err
  389. }
  390. // FileExists - checks if file exists locally
  391. func FileExists(f string) bool {
  392. info, err := os.Stat(f)
  393. if os.IsNotExist(err) {
  394. return false
  395. }
  396. if err != nil && strings.Contains(err.Error(), "not a directory") {
  397. return false
  398. }
  399. if err != nil {
  400. Log("error reading file: " + f + ", " + err.Error())
  401. }
  402. return !info.IsDir()
  403. }
  404. // PrintLog - prints log
  405. func PrintLog(message string, loglevel int) {
  406. log.SetFlags(log.Flags() &^ (log.Llongfile | log.Lshortfile))
  407. if loglevel < 2 {
  408. log.Println("[netclient]", message)
  409. }
  410. }
  411. // GetSystemNetworks - get networks locally
  412. func GetSystemNetworks() ([]string, error) {
  413. var networks []string
  414. files, err := ioutil.ReadDir(GetNetclientPathSpecific())
  415. if err != nil {
  416. return networks, err
  417. }
  418. for _, f := range files {
  419. if strings.Contains(f.Name(), "netconfig-") {
  420. networkname := stringAfter(f.Name(), "netconfig-")
  421. networks = append(networks, networkname)
  422. }
  423. }
  424. return networks, err
  425. }
  426. func stringAfter(original string, substring string) string {
  427. position := strings.LastIndex(original, substring)
  428. if position == -1 {
  429. return ""
  430. }
  431. adjustedPosition := position + len(substring)
  432. if adjustedPosition >= len(original) {
  433. return ""
  434. }
  435. return original[adjustedPosition:]
  436. }