netclientutils.go 11 KB

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