netclientutils.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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. // MAX_NAME_LENGTH - maximum node name length
  25. const MAX_NAME_LENGTH = 62
  26. // NO_DB_RECORD - error message result
  27. const NO_DB_RECORD = "no result found"
  28. // NO_DB_RECORDS - error record result
  29. const NO_DB_RECORDS = "could not find any records"
  30. // LINUX_APP_DATA_PATH - linux path
  31. const LINUX_APP_DATA_PATH = "/etc/netclient"
  32. // WINDOWS_APP_DATA_PATH - windows path
  33. const WINDOWS_APP_DATA_PATH = "C:\\ProgramData\\Netclient"
  34. // WINDOWS_APP_DATA_PATH - windows path
  35. const WINDOWS_WG_DATA_PATH = "C:\\Program Files\\WireGuard\\Data\\Configurations"
  36. // WINDOWS_SVC_NAME - service name
  37. const WINDOWS_SVC_NAME = "netclient"
  38. // NETCLIENT_DEFAULT_PORT - default port
  39. const NETCLIENT_DEFAULT_PORT = 51821
  40. // DEFAULT_GC_PERCENT - garbage collection percent
  41. const DEFAULT_GC_PERCENT = 10
  42. // Log - logs a message
  43. func Log(message string) {
  44. log.SetFlags(log.Flags() &^ (log.Llongfile | log.Lshortfile))
  45. log.Println("[netclient]", message)
  46. }
  47. // IsWindows - checks if is windows
  48. func IsWindows() bool {
  49. return runtime.GOOS == "windows"
  50. }
  51. // IsMac - checks if is a mac
  52. func IsMac() bool {
  53. return runtime.GOOS == "darwin"
  54. }
  55. // IsLinux - checks if is linux
  56. func IsLinux() bool {
  57. return runtime.GOOS == "linux"
  58. }
  59. // IsLinux - checks if is linux
  60. func IsFreeBSD() bool {
  61. return runtime.GOOS == "freebsd"
  62. }
  63. // GetWireGuard - checks if wg is installed
  64. func GetWireGuard() string {
  65. userspace := os.Getenv("WG_QUICK_USERSPACE_IMPLEMENTATION")
  66. if userspace != "" && (userspace == "boringtun" || userspace == "wireguard-go") {
  67. return userspace
  68. }
  69. return "wg"
  70. }
  71. // IsKernel - checks if running kernel WireGuard
  72. func IsKernel() bool {
  73. //TODO
  74. //Replace && true with some config file value
  75. //This value should be something like kernelmode, which should be 'on' by default.
  76. return IsLinux() && os.Getenv("WG_QUICK_USERSPACE_IMPLEMENTATION") == ""
  77. }
  78. // IsEmptyRecord - repeat from database
  79. func IsEmptyRecord(err error) bool {
  80. if err == nil {
  81. return false
  82. }
  83. return strings.Contains(err.Error(), NO_DB_RECORD) || strings.Contains(err.Error(), NO_DB_RECORDS)
  84. }
  85. //generate an access key value
  86. // GenPass - generates a pass
  87. func GenPass() string {
  88. var seededRand *rand.Rand = rand.New(
  89. rand.NewSource(time.Now().UnixNano()))
  90. length := 16
  91. charset := "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  92. b := make([]byte, length)
  93. for i := range b {
  94. b[i] = charset[seededRand.Intn(len(charset))]
  95. }
  96. return string(b)
  97. }
  98. // GetPublicIP - gets public ip
  99. func GetPublicIP() (string, error) {
  100. iplist := []string{"https://ip.client.gravitl.com", "https://ifconfig.me", "https://api.ipify.org", "https://ipinfo.io/ip"}
  101. endpoint := ""
  102. var err error
  103. for _, ipserver := range iplist {
  104. resp, err := http.Get(ipserver)
  105. if err != nil {
  106. continue
  107. }
  108. defer resp.Body.Close()
  109. if resp.StatusCode == http.StatusOK {
  110. bodyBytes, err := ioutil.ReadAll(resp.Body)
  111. if err != nil {
  112. continue
  113. }
  114. endpoint = string(bodyBytes)
  115. break
  116. }
  117. }
  118. if err == nil && endpoint == "" {
  119. err = errors.New("public address not found")
  120. }
  121. return endpoint, err
  122. }
  123. // GetMacAddr - get's mac address
  124. func GetMacAddr() ([]string, error) {
  125. ifas, err := net.Interfaces()
  126. if err != nil {
  127. return nil, err
  128. }
  129. var as []string
  130. for _, ifa := range ifas {
  131. a := ifa.HardwareAddr.String()
  132. if a != "" {
  133. as = append(as, a)
  134. }
  135. }
  136. return as, nil
  137. }
  138. func parsePeers(keepalive int32, peers []wgtypes.PeerConfig) (string, error) {
  139. peersString := ""
  140. if keepalive <= 0 {
  141. keepalive = 20
  142. }
  143. for _, peer := range peers {
  144. endpointString := ""
  145. if peer.Endpoint != nil && peer.Endpoint.String() != "" {
  146. endpointString += "Endpoint = " + peer.Endpoint.String()
  147. }
  148. newAllowedIps := []string{}
  149. for _, allowedIP := range peer.AllowedIPs {
  150. newAllowedIps = append(newAllowedIps, allowedIP.String())
  151. }
  152. peersString += fmt.Sprintf(`[Peer]
  153. PublicKey = %s
  154. AllowedIps = %s
  155. PersistentKeepAlive = %s
  156. %s
  157. `,
  158. peer.PublicKey.String(),
  159. strings.Join(newAllowedIps, ","),
  160. strconv.Itoa(int(keepalive)),
  161. endpointString,
  162. )
  163. }
  164. return peersString, nil
  165. }
  166. // GetLocalIP - gets local ip of machine
  167. func GetLocalIP(localrange string) (string, error) {
  168. _, localRange, err := net.ParseCIDR(localrange)
  169. if err != nil {
  170. return "", err
  171. }
  172. ifaces, err := net.Interfaces()
  173. if err != nil {
  174. return "", err
  175. }
  176. var local string
  177. found := false
  178. for _, i := range ifaces {
  179. if i.Flags&net.FlagUp == 0 {
  180. continue // interface down
  181. }
  182. if i.Flags&net.FlagLoopback != 0 {
  183. continue // loopback interface
  184. }
  185. addrs, err := i.Addrs()
  186. if err != nil {
  187. return "", err
  188. }
  189. for _, addr := range addrs {
  190. var ip net.IP
  191. switch v := addr.(type) {
  192. case *net.IPNet:
  193. if !found {
  194. ip = v.IP
  195. local = ip.String()
  196. found = localRange.Contains(ip)
  197. }
  198. case *net.IPAddr:
  199. if !found {
  200. ip = v.IP
  201. local = ip.String()
  202. found = localRange.Contains(ip)
  203. }
  204. }
  205. }
  206. }
  207. if !found || local == "" {
  208. return "", errors.New("Failed to find local IP in range " + localrange)
  209. }
  210. return local, nil
  211. }
  212. func GetNetworkIPMask(networkstring string) (string, string, error) {
  213. ip, ipnet, err := net.ParseCIDR(networkstring)
  214. if err != nil {
  215. return "", "", err
  216. }
  217. ipstring := ip.String()
  218. mask := ipnet.Mask
  219. maskstring := fmt.Sprintf("%d.%d.%d.%d", mask[0], mask[1], mask[2], mask[3])
  220. //maskstring := ipnet.Mask.String()
  221. return ipstring, maskstring, err
  222. }
  223. // GetFreePort - gets free port of machine
  224. func GetFreePort(rangestart int32) (int32, error) {
  225. if rangestart == 0 {
  226. rangestart = NETCLIENT_DEFAULT_PORT
  227. }
  228. wgclient, err := wgctrl.New()
  229. if err != nil {
  230. return 0, err
  231. }
  232. defer wgclient.Close()
  233. devices, err := wgclient.Devices()
  234. if err != nil {
  235. return 0, err
  236. }
  237. for x := rangestart; x <= 65535; x++ {
  238. conflict := false
  239. for _, i := range devices {
  240. if int32(i.ListenPort) == x {
  241. conflict = true
  242. break
  243. }
  244. }
  245. if conflict {
  246. continue
  247. }
  248. return int32(x), nil
  249. }
  250. return rangestart, err
  251. }
  252. // == OS PATH FUNCTIONS ==
  253. // GetHomeDirWindows - gets home directory in windows
  254. func GetHomeDirWindows() string {
  255. if IsWindows() {
  256. home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
  257. if home == "" {
  258. home = os.Getenv("USERPROFILE")
  259. }
  260. return home
  261. }
  262. return os.Getenv("HOME")
  263. }
  264. // GetNetclientPath - gets netclient path locally
  265. func GetNetclientPath() string {
  266. if IsWindows() {
  267. return WINDOWS_APP_DATA_PATH
  268. } else if IsMac() {
  269. return "/etc/netclient/"
  270. } else {
  271. return LINUX_APP_DATA_PATH
  272. }
  273. }
  274. // GetNetclientPathSpecific - gets specific netclient config path
  275. func GetNetclientPathSpecific() string {
  276. if IsWindows() {
  277. return WINDOWS_APP_DATA_PATH + "\\"
  278. } else if IsMac() {
  279. return "/etc/netclient/config/"
  280. } else {
  281. return LINUX_APP_DATA_PATH + "/config/"
  282. }
  283. }
  284. // GetNetclientPathSpecific - gets specific netclient config path
  285. func GetWGPathSpecific() string {
  286. if IsWindows() {
  287. return WINDOWS_WG_DATA_PATH + "\\"
  288. } else {
  289. return "/etc/wireguard/"
  290. }
  291. }
  292. // GRPCRequestOpts - gets grps request opts
  293. func GRPCRequestOpts(isSecure string) grpc.DialOption {
  294. var requestOpts grpc.DialOption
  295. requestOpts = grpc.WithInsecure()
  296. if isSecure == "on" {
  297. h2creds := credentials.NewTLS(&tls.Config{NextProtos: []string{"h2"}})
  298. requestOpts = grpc.WithTransportCredentials(h2creds)
  299. }
  300. return requestOpts
  301. }
  302. // Copy - copies a src file to dest
  303. func Copy(src, dst string) error {
  304. sourceFileStat, err := os.Stat(src)
  305. if err != nil {
  306. return err
  307. }
  308. if !sourceFileStat.Mode().IsRegular() {
  309. return errors.New(src + " is not a regular file")
  310. }
  311. source, err := os.Open(src)
  312. if err != nil {
  313. return err
  314. }
  315. defer source.Close()
  316. destination, err := os.Create(dst)
  317. if err != nil {
  318. return err
  319. }
  320. defer destination.Close()
  321. _, err = io.Copy(destination, source)
  322. if err != nil {
  323. return err
  324. }
  325. err = os.Chmod(dst, 0755)
  326. return err
  327. }
  328. // RunsCmds - runs cmds
  329. func RunCmds(commands []string, printerr bool) error {
  330. var err error
  331. for _, command := range commands {
  332. args := strings.Fields(command)
  333. out, err := exec.Command(args[0], args[1:]...).CombinedOutput()
  334. if err != nil && printerr {
  335. log.Println("error running command:", command)
  336. log.Println(strings.TrimSuffix(string(out), "\n"))
  337. }
  338. }
  339. return err
  340. }
  341. // FileExists - checks if file exists locally
  342. func FileExists(f string) bool {
  343. info, err := os.Stat(f)
  344. if os.IsNotExist(err) {
  345. return false
  346. }
  347. if err != nil && strings.Contains(err.Error(), "not a directory") {
  348. return false
  349. }
  350. if err != nil {
  351. Log("error reading file: " + f + ", " + err.Error())
  352. }
  353. return !info.IsDir()
  354. }
  355. // PrintLog - prints log
  356. func PrintLog(message string, loglevel int) {
  357. log.SetFlags(log.Flags() &^ (log.Llongfile | log.Lshortfile))
  358. if loglevel < 2 {
  359. log.Println("[netclient]", message)
  360. }
  361. }
  362. // GetSystemNetworks - get networks locally
  363. func GetSystemNetworks() ([]string, error) {
  364. var networks []string
  365. files, err := ioutil.ReadDir(GetNetclientPathSpecific())
  366. if err != nil {
  367. return networks, err
  368. }
  369. for _, f := range files {
  370. if strings.Contains(f.Name(), "netconfig-") && !strings.Contains(f.Name(), "backup") {
  371. networkname := stringAfter(f.Name(), "netconfig-")
  372. networks = append(networks, networkname)
  373. }
  374. }
  375. return networks, err
  376. }
  377. func stringAfter(original string, substring string) string {
  378. position := strings.LastIndex(original, substring)
  379. if position == -1 {
  380. return ""
  381. }
  382. adjustedPosition := position + len(substring)
  383. if adjustedPosition >= len(original) {
  384. return ""
  385. }
  386. return original[adjustedPosition:]
  387. }
  388. func ShortenString(input string, length int) string {
  389. output := input
  390. if len(input) > length {
  391. output = input[0:length]
  392. }
  393. return output
  394. }
  395. func DNSFormatString(input string) string {
  396. reg, err := regexp.Compile("[^a-zA-Z0-9-]+")
  397. if err != nil {
  398. Log("error with regex: " + err.Error())
  399. return ""
  400. }
  401. return reg.ReplaceAllString(input, "")
  402. }
  403. func GetHostname() string {
  404. hostname, err := os.Hostname()
  405. if err != nil {
  406. return ""
  407. }
  408. if len(hostname) > MAX_NAME_LENGTH {
  409. hostname = hostname[0:MAX_NAME_LENGTH]
  410. }
  411. return hostname
  412. }
  413. func CheckUID() {
  414. // start our application
  415. out, err := RunCmd("id -u", true)
  416. if err != nil {
  417. log.Fatal(out, err)
  418. }
  419. id, err := strconv.Atoi(string(out[:len(out)-1]))
  420. if err != nil {
  421. log.Fatal(err)
  422. }
  423. if id != 0 {
  424. log.Fatal("This program must be run with elevated privileges (sudo). This program installs a SystemD service and configures WireGuard and networking rules. Please re-run with sudo/root.")
  425. }
  426. }
  427. // CheckWG - Checks if WireGuard is installed. If not, exit
  428. func CheckWG() {
  429. var _, err = exec.LookPath("wg")
  430. uspace := GetWireGuard()
  431. if err != nil {
  432. if uspace == "wg" {
  433. PrintLog(err.Error(), 0)
  434. log.Fatal("WireGuard not installed. Please install WireGuard (wireguard-tools) and try again.")
  435. }
  436. PrintLog("Running with userspace wireguard: "+uspace, 0)
  437. } else if uspace != "wg" {
  438. log.Println("running userspace WireGuard with " + uspace)
  439. }
  440. }