netclientutils.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. "regexp"
  15. "runtime"
  16. "strconv"
  17. "strings"
  18. "time"
  19. "golang.zx2c4.com/wireguard/wgctrl"
  20. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  21. "google.golang.org/grpc"
  22. "google.golang.org/grpc/credentials"
  23. )
  24. // NO_DB_RECORD - error message result
  25. const NO_DB_RECORD = "no result found"
  26. // NO_DB_RECORDS - error record result
  27. const NO_DB_RECORDS = "could not find any records"
  28. // LINUX_APP_DATA_PATH - linux path
  29. const LINUX_APP_DATA_PATH = "/etc/netclient"
  30. // WINDOWS_APP_DATA_PATH - windows path
  31. const WINDOWS_APP_DATA_PATH = "C:\\ProgramData\\Netclient"
  32. // WINDOWS_APP_DATA_PATH - windows path
  33. const WINDOWS_WG_DATA_PATH = "C:\\Program Files\\WireGuard\\Data\\Configurations"
  34. // WINDOWS_SVC_NAME - service name
  35. const WINDOWS_SVC_NAME = "netclient"
  36. // NETCLIENT_DEFAULT_PORT - default port
  37. const NETCLIENT_DEFAULT_PORT = 51821
  38. // DEFAULT_GC_PERCENT - garbage collection percent
  39. const DEFAULT_GC_PERCENT = 10
  40. // Log - logs a message
  41. func Log(message string) {
  42. log.SetFlags(log.Flags() &^ (log.Llongfile | log.Lshortfile))
  43. log.Println("[netclient]", message)
  44. }
  45. // IsWindows - checks if is windows
  46. func IsWindows() bool {
  47. return runtime.GOOS == "windows"
  48. }
  49. // IsMac - checks if is a mac
  50. func IsMac() bool {
  51. return runtime.GOOS == "darwin"
  52. }
  53. // IsLinux - checks if is linux
  54. func IsLinux() bool {
  55. return runtime.GOOS == "linux"
  56. }
  57. // IsLinux - checks if is linux
  58. func IsFreeBSD() bool {
  59. return runtime.GOOS == "freebsd"
  60. }
  61. // GetWireGuard - checks if wg is installed
  62. func GetWireGuard() string {
  63. userspace := os.Getenv("WG_QUICK_USERSPACE_IMPLEMENTATION")
  64. if userspace != "" && (userspace == "boringtun" || userspace == "wireguard-go") {
  65. return userspace
  66. }
  67. return "wg"
  68. }
  69. // IsKernel - checks if running kernel WireGuard
  70. func IsKernel() bool {
  71. //TODO
  72. //Replace && true with some config file value
  73. //This value should be something like kernelmode, which should be 'on' by default.
  74. return IsLinux() && os.Getenv("WG_QUICK_USERSPACE_IMPLEMENTATION") == ""
  75. }
  76. // IsEmptyRecord - repeat from database
  77. func IsEmptyRecord(err error) bool {
  78. if err == nil {
  79. return false
  80. }
  81. return strings.Contains(err.Error(), NO_DB_RECORD) || strings.Contains(err.Error(), NO_DB_RECORDS)
  82. }
  83. //generate an access key value
  84. // GenPass - generates a pass
  85. func GenPass() string {
  86. var seededRand *rand.Rand = rand.New(
  87. rand.NewSource(time.Now().UnixNano()))
  88. length := 16
  89. charset := "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  90. b := make([]byte, length)
  91. for i := range b {
  92. b[i] = charset[seededRand.Intn(len(charset))]
  93. }
  94. return string(b)
  95. }
  96. // GetPublicIP - gets public ip
  97. func GetPublicIP() (string, error) {
  98. iplist := []string{"https://ip.client.gravitl.com", "https://ifconfig.me", "https://api.ipify.org", "https://ipinfo.io/ip"}
  99. endpoint := ""
  100. var err error
  101. for _, ipserver := range iplist {
  102. resp, err := http.Get(ipserver)
  103. if err != nil {
  104. continue
  105. }
  106. defer resp.Body.Close()
  107. if resp.StatusCode == http.StatusOK {
  108. bodyBytes, err := ioutil.ReadAll(resp.Body)
  109. if err != nil {
  110. continue
  111. }
  112. endpoint = string(bodyBytes)
  113. break
  114. }
  115. }
  116. if err == nil && endpoint == "" {
  117. err = errors.New("public address not found")
  118. }
  119. return endpoint, err
  120. }
  121. // GetMacAddr - get's mac address
  122. func GetMacAddr() ([]string, error) {
  123. ifas, err := net.Interfaces()
  124. if err != nil {
  125. return nil, err
  126. }
  127. var as []string
  128. for _, ifa := range ifas {
  129. a := ifa.HardwareAddr.String()
  130. if a != "" {
  131. as = append(as, a)
  132. }
  133. }
  134. return as, nil
  135. }
  136. func parsePeers(keepalive int32, peers []wgtypes.PeerConfig) (string, error) {
  137. peersString := ""
  138. if keepalive <= 0 {
  139. keepalive = 20
  140. }
  141. for _, peer := range peers {
  142. endpointString := ""
  143. if peer.Endpoint != nil && peer.Endpoint.String() != "" {
  144. endpointString += "Endpoint = " + peer.Endpoint.String()
  145. }
  146. newAllowedIps := []string{}
  147. for _, allowedIP := range peer.AllowedIPs {
  148. newAllowedIps = append(newAllowedIps, allowedIP.String())
  149. }
  150. peersString += fmt.Sprintf(`[Peer]
  151. PublicKey = %s
  152. AllowedIps = %s
  153. PersistentKeepAlive = %s
  154. %s
  155. `,
  156. peer.PublicKey.String(),
  157. strings.Join(newAllowedIps, ","),
  158. strconv.Itoa(int(keepalive)),
  159. endpointString,
  160. )
  161. }
  162. return peersString, nil
  163. }
  164. // CreateUserSpaceConf - creates a user space WireGuard conf
  165. func CreateUserSpaceConf(address string, privatekey string, listenPort string, mtu int32, fwmark int32, perskeepalive int32, peers []wgtypes.PeerConfig) (string, error) {
  166. peersString, err := parsePeers(perskeepalive, peers)
  167. var listenPortString string
  168. var fwmarkString string
  169. if mtu <= 0 {
  170. mtu = 1280
  171. }
  172. if listenPort != "" {
  173. listenPortString += "ListenPort = " + listenPort
  174. }
  175. if fwmark != 0 {
  176. fwmarkString += "FWMark = " + strconv.Itoa(int(fwmark))
  177. }
  178. if err != nil {
  179. return "", err
  180. }
  181. config := fmt.Sprintf(`[Interface]
  182. Address = %s
  183. PrivateKey = %s
  184. MTU = %s
  185. %s
  186. %s
  187. %s
  188. `,
  189. address+"/32",
  190. privatekey,
  191. strconv.Itoa(int(mtu)),
  192. listenPortString,
  193. fwmarkString,
  194. peersString)
  195. return config, nil
  196. }
  197. // GetLocalIP - gets local ip of machine
  198. func GetLocalIP(localrange string) (string, error) {
  199. _, localRange, err := net.ParseCIDR(localrange)
  200. if err != nil {
  201. return "", err
  202. }
  203. ifaces, err := net.Interfaces()
  204. if err != nil {
  205. return "", err
  206. }
  207. var local string
  208. found := false
  209. for _, i := range ifaces {
  210. if i.Flags&net.FlagUp == 0 {
  211. continue // interface down
  212. }
  213. if i.Flags&net.FlagLoopback != 0 {
  214. continue // loopback interface
  215. }
  216. addrs, err := i.Addrs()
  217. if err != nil {
  218. return "", err
  219. }
  220. for _, addr := range addrs {
  221. var ip net.IP
  222. switch v := addr.(type) {
  223. case *net.IPNet:
  224. if !found {
  225. ip = v.IP
  226. local = ip.String()
  227. found = localRange.Contains(ip)
  228. }
  229. case *net.IPAddr:
  230. if !found {
  231. ip = v.IP
  232. local = ip.String()
  233. found = localRange.Contains(ip)
  234. }
  235. }
  236. }
  237. }
  238. if !found || local == "" {
  239. return "", errors.New("Failed to find local IP in range " + localrange)
  240. }
  241. return local, nil
  242. }
  243. func GetNetworkIPMask(networkstring string) (string, string, error) {
  244. ip, ipnet, err := net.ParseCIDR(networkstring)
  245. if err != nil {
  246. return "", "", err
  247. }
  248. ipstring := ip.String()
  249. maskstring := ipnet.Mask.String()
  250. return ipstring, maskstring, err
  251. }
  252. // GetFreePort - gets free port of machine
  253. func GetFreePort(rangestart int32) (int32, error) {
  254. if rangestart == 0 {
  255. rangestart = NETCLIENT_DEFAULT_PORT
  256. }
  257. wgclient, err := wgctrl.New()
  258. if err != nil {
  259. return 0, err
  260. }
  261. devices, err := wgclient.Devices()
  262. if err != nil {
  263. return 0, err
  264. }
  265. for x := rangestart; x <= 65535; x++ {
  266. conflict := false
  267. for _, i := range devices {
  268. if int32(i.ListenPort) == x {
  269. conflict = true
  270. break
  271. }
  272. }
  273. if conflict {
  274. continue
  275. }
  276. return int32(x), nil
  277. }
  278. return rangestart, err
  279. }
  280. // == OS PATH FUNCTIONS ==
  281. // GetHomeDirWindows - gets home directory in windows
  282. func GetHomeDirWindows() string {
  283. if IsWindows() {
  284. home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
  285. if home == "" {
  286. home = os.Getenv("USERPROFILE")
  287. }
  288. return home
  289. }
  290. return os.Getenv("HOME")
  291. }
  292. // GetNetclientPath - gets netclient path locally
  293. func GetNetclientPath() string {
  294. if IsWindows() {
  295. return WINDOWS_APP_DATA_PATH
  296. } else if IsMac() {
  297. return "/etc/netclient/"
  298. } else {
  299. return LINUX_APP_DATA_PATH
  300. }
  301. }
  302. // GetNetclientPathSpecific - gets specific netclient config path
  303. func GetNetclientPathSpecific() string {
  304. if IsWindows() {
  305. return WINDOWS_APP_DATA_PATH + "\\"
  306. } else if IsMac() {
  307. return "/etc/netclient/config/"
  308. } else {
  309. return LINUX_APP_DATA_PATH + "/config/"
  310. }
  311. }
  312. // GetNetclientPathSpecific - gets specific netclient config path
  313. func GetWGPathSpecific() string {
  314. if IsWindows() {
  315. return WINDOWS_WG_DATA_PATH + "\\"
  316. } else {
  317. return "/etc/wireguard/"
  318. }
  319. }
  320. // GRPCRequestOpts - gets grps request opts
  321. func GRPCRequestOpts(isSecure string) grpc.DialOption {
  322. var requestOpts grpc.DialOption
  323. requestOpts = grpc.WithInsecure()
  324. if isSecure == "on" {
  325. h2creds := credentials.NewTLS(&tls.Config{NextProtos: []string{"h2"}})
  326. requestOpts = grpc.WithTransportCredentials(h2creds)
  327. }
  328. return requestOpts
  329. }
  330. // Copy - copies a src file to dest
  331. func Copy(src, dst string) error {
  332. sourceFileStat, err := os.Stat(src)
  333. if err != nil {
  334. return err
  335. }
  336. if !sourceFileStat.Mode().IsRegular() {
  337. return errors.New(src + " is not a regular file")
  338. }
  339. source, err := os.Open(src)
  340. if err != nil {
  341. return err
  342. }
  343. defer source.Close()
  344. destination, err := os.Create(dst)
  345. if err != nil {
  346. return err
  347. }
  348. defer destination.Close()
  349. _, err = io.Copy(destination, source)
  350. if err != nil {
  351. return err
  352. }
  353. err = os.Chmod(dst, 0755)
  354. return 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. }
  416. func ShortenString(input string, length int) string {
  417. output := input
  418. if len(input) > length {
  419. output = input[0:length]
  420. }
  421. return output
  422. }
  423. func DNSFormatString(input string) string {
  424. reg, err := regexp.Compile("[^a-zA-Z0-9-]+")
  425. if err != nil {
  426. Log("error with regex: " + err.Error())
  427. return ""
  428. }
  429. return reg.ReplaceAllString(input, "")
  430. }