-
Notifications
You must be signed in to change notification settings - Fork 26
/
netclientutils.go
638 lines (573 loc) · 14.8 KB
/
netclientutils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
// Package ncutils contains utility functions
package ncutils
import (
"bytes"
"crypto/md5"
"crypto/rand"
"encoding/base32"
"encoding/gob"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/exec"
"regexp"
"runtime"
"strconv"
"strings"
"time"
"github.com/c-robinson/iplib"
"github.com/gravitl/netmaker/logger"
"github.com/gravitl/netmaker/models"
)
var ifaceName string
// MaxNameLength - maximum node name length
const MaxNameLength = 62
// NoDBRecord - error message result
const NoDBRecord = "no result found"
// NoDBRecords - error record result
const NoDBRecords = "could not find any records"
// WindowsSvcName - service name
const WindowsSvcName = "netclient"
// NetclientDefaultPort - default port
const NetclientDefaultPort = 51821
// DefaultGCPercent - garbage collection percent
const DefaultGCPercent = 10
// KeySize = ideal length for keys
const KeySize = 2048
// IsWindows - checks if is windows
func IsWindows() bool {
return runtime.GOOS == "windows"
}
// IsMac - checks if is a mac
func IsMac() bool {
return runtime.GOOS == "darwin"
}
// IsLinux - checks if is linux
func IsLinux() bool {
return runtime.GOOS == "linux"
}
// IsFreeBSD - checks if is freebsd
func IsFreeBSD() bool {
return runtime.GOOS == "freebsd"
}
// HasWgQuick - checks if WGQuick command is present
func HasWgQuick() bool {
cmd, err := exec.LookPath("wg-quick")
return err == nil && cmd != ""
}
// GetWireGuard - checks if wg is installed
func GetWireGuard() string {
userspace := os.Getenv("WG_QUICK_USERSPACE_IMPLEMENTATION")
if userspace != "" && (userspace == "boringtun" || userspace == "wireguard-go") {
return userspace
}
return "wg"
}
// IsNFTablesPresent - returns true if nftables is present, false otherwise.
// Does not consider OS, up to the caller to determine if the OS supports nftables/whether this check is valid.
func IsNFTablesPresent() bool {
found := false
_, err := exec.LookPath("nft")
if err == nil {
found = true
}
return found
}
// IsIPTablesPresent - returns true if iptables is present, false otherwise
// Does not consider OS, up to the caller to determine if the OS supports iptables/whether this check is valid.
func IsIPTablesPresent() bool {
found := false
_, err := exec.LookPath("iptables")
if err == nil {
found = true
}
return found
}
// IsKernel - checks if running kernel WireGuard
func IsKernel() bool {
//TODO
//Replace && true with some config file value
//This value should be something like kernelmode, which should be 'on' by default.
return IsLinux() && os.Getenv("WG_QUICK_USERSPACE_IMPLEMENTATION") == ""
}
// IsEmptyRecord - repeat from database
func IsEmptyRecord(err error) bool {
if err == nil {
return false
}
return strings.Contains(err.Error(), NoDBRecord) || strings.Contains(err.Error(), NoDBRecords)
}
// GetPublicIP - gets public ip
func GetPublicIP(api string) (net.IP, error) {
iplist := []string{"https://ifconfig.me", "https://api.ipify.org", "https://ipinfo.io/ip"}
if api != "" {
api = "https://" + api + "/api/getip"
iplist = append([]string{api}, iplist...)
}
endpoint := ""
var err error
for _, ipserver := range iplist {
client := &http.Client{
Timeout: time.Second * 10,
}
resp, err := client.Get(ipserver)
if err != nil {
continue
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
continue
}
endpoint = string(bodyBytes)
break
}
}
if err == nil && endpoint == "" {
err = errors.New("public address not found")
}
return net.ParseIP(endpoint), err
}
// GetPublicIPv6 - gets public ipv6 address
func GetPublicIPv6() (net.IP, error) {
iplist := []string{"https://ifconfig.me"}
endpoint := ""
var err error
for _, ipserver := range iplist {
client := &http.Client{
Timeout: time.Second * 10,
}
resp, err := client.Get(ipserver)
if err != nil {
continue
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
continue
}
endpoint = string(bodyBytes)
break
}
}
if err == nil && endpoint == "" {
err = errors.New("public ipv6 address not found")
}
return net.ParseIP(endpoint), err
}
// GetMacAddr - get's mac address
func GetMacAddr() ([]net.HardwareAddr, error) {
ifas, err := net.Interfaces()
if err != nil {
return nil, err
}
var as []net.HardwareAddr
for _, ifa := range ifas {
a := ifa.HardwareAddr
if a != nil {
as = append(as, a)
}
}
return as, nil
}
// GetLocalIP - gets local ip of machine
// returns first interface that is up, is not a loopback and is
func GetLocalIP(localrange net.IPNet) (*net.IPNet, error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, i := range ifaces {
if i.Flags&net.FlagUp == 0 {
continue // interface down
}
if i.Flags&net.FlagLoopback != 0 {
continue // loopback interface
}
addrs, err := i.Addrs()
if err != nil {
return nil, err
}
for _, addr := range addrs {
if net, ok := addr.(*net.IPNet); ok {
if localrange.Contains(net.IP) {
return net, nil
}
}
}
}
return nil, errors.New("not found")
}
// GetNetworkIPMask - Pulls the netmask out of the network
func GetNetworkIPMask(networkstring string) (string, string, error) {
ip, ipnet, err := net.ParseCIDR(networkstring)
if err != nil {
return "", "", err
}
ipstring := ip.String()
mask := ipnet.Mask
maskstring := fmt.Sprintf("%d.%d.%d.%d", mask[0], mask[1], mask[2], mask[3])
//maskstring := ipnet.Mask.String()
return ipstring, maskstring, err
}
// GetFreePort - gets free port of machine
func GetFreePort(rangestart int) (int, error) {
addr := net.UDPAddr{}
if rangestart == 0 {
rangestart = NetclientDefaultPort
}
for x := rangestart; x <= 65535; x++ {
addr.Port = int(x)
conn, err := net.ListenUDP("udp", &addr)
if err != nil {
continue
}
defer conn.Close()
return x, nil
}
return rangestart, errors.New("no free ports")
}
// IsPortFree - checks if port is free
func IsPortFree(port int) (free bool) {
conn, err := net.ListenUDP("udp", &net.UDPAddr{Port: port})
if err == nil {
free = true
conn.Close()
}
return
}
// GetFreeTCPPort - gets free TCP port
func GetFreeTCPPort() (string, error) {
addr := net.TCPAddr{
IP: net.ParseIP("127.0.0.1"),
}
conn, err := net.ListenTCP("tcp", &addr)
if err != nil {
return "", err
}
defer conn.Close()
x := strconv.Itoa(conn.Addr().(*net.TCPAddr).Port)
log.Println("--- free port found: ", x, "---")
return x, nil
}
// == OS PATH FUNCTIONS ==
// GetHomeDirWindows - gets home directory in windows
func GetHomeDirWindows() string {
if IsWindows() {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home
}
return os.Getenv("HOME")
}
// GetSeparator - gets the separator for OS
func GetSeparator() string {
if IsWindows() {
return "\\"
} else {
return "/"
}
}
// GetFileWithRetry - retry getting file X number of times before failing
func GetFileWithRetry(path string, retryCount int) ([]byte, error) {
var data []byte
var err error
for count := 0; count < retryCount; count++ {
data, err = os.ReadFile(path)
if err == nil {
return data, err
} else {
logger.Log(1, "failed to retrieve file ", path, ", retrying...")
time.Sleep(time.Second >> 2)
}
}
return data, err
}
func CheckIPAddress(ip string) error {
if net.ParseIP(ip) == nil {
return fmt.Errorf("ip address %s is invalid", ip)
}
return nil
}
// GetNewIface - Gets the name of the real interface created on Mac
func GetNewIface(dir string) (string, error) {
files, _ := os.ReadDir(dir)
var newestFile string
var newestTime int64 = 0
var err error
for _, f := range files {
fi, err := os.Stat(dir + f.Name())
if err != nil {
return "", err
}
currTime := fi.ModTime().Unix()
if currTime > newestTime && strings.Contains(f.Name(), ".sock") {
newestTime = currTime
newestFile = f.Name()
}
}
resultArr := strings.Split(newestFile, ".")
if resultArr[0] == "" {
err = errors.New("sock file does not exist")
}
return resultArr[0], err
}
// GetFileAsString - returns the string contents of a given file
func GetFileAsString(path string) (string, error) {
content, err := os.ReadFile(path)
if err != nil {
return "", err
}
return string(content), err
}
// Copy - copies a src file to dest
func Copy(src, dst string) error {
sourceFileStat, err := os.Stat(src)
if err != nil {
return err
}
if !sourceFileStat.Mode().IsRegular() {
return errors.New(src + " is not a regular file")
}
source, err := os.Open(src)
if err != nil {
return err
}
defer source.Close()
destination, err := os.Create(dst)
if err != nil {
return err
}
defer destination.Close()
_, err = io.Copy(destination, source)
if err != nil {
return err
}
err = os.Chmod(dst, 0755)
return err
}
// RunCmds - runs cmds
func RunCmds(commands []string, printerr bool) error {
var err error
for _, command := range commands {
//prevent panic
if len(strings.Trim(command, " ")) == 0 {
continue
}
args := strings.Fields(command)
out, err := exec.Command(args[0], args[1:]...).CombinedOutput()
if err != nil && printerr {
logger.Log(0, "error running command:", command)
logger.Log(0, strings.TrimSuffix(string(out), "\n"))
}
}
return err
}
// FileExists - checks if file exists locally
func FileExists(f string) bool {
info, err := os.Stat(f)
if os.IsNotExist(err) {
return false
}
if err != nil && strings.Contains(err.Error(), "not a directory") {
return false
}
if err != nil {
logger.Log(0, "error reading file: "+f+", "+err.Error())
}
return !info.IsDir()
}
// ShortenString - Brings string down to specified length. Stops names from being too long
func ShortenString(input string, length int) string {
output := input
if len(input) > length {
output = input[0:length]
}
return output
}
// DNSFormatString - Formats a string with correct usage for DNS
func DNSFormatString(input string) string {
reg, err := regexp.Compile("[^a-zA-Z0-9-]+")
if err != nil {
logger.Log(0, "error with regex: "+err.Error())
return ""
}
return reg.ReplaceAllString(input, "")
}
// GetHostname - Gets hostname of machine
func GetHostname() string {
hostname, err := os.Hostname()
if err != nil {
return ""
}
if len(hostname) > MaxNameLength {
hostname = hostname[0:MaxNameLength]
}
return hostname
}
// CheckUID - Checks to make sure user has root privileges
//func CheckUID() {
// // start our application
// out, err := RunCmd("id -u", true)
//
// if err != nil {
// log.Fatal(out, err)
// }
// id, err := strconv.Atoi(string(out[:len(out)-1]))
//
// if err != nil {
// log.Fatal(err)
// }
//
// if id != 0 {
// 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.")
// }
//}
// CheckFirewall - checks if iptables of nft install, if not exit
func CheckFirewall() {
if !IsIPTablesPresent() && !IsNFTablesPresent() {
log.Fatal("neither iptables nor nft is installed - please install one or the other and try again")
}
}
// CheckWG - Checks if WireGuard is installed. If not, exit
func CheckWG() {
uspace := GetWireGuard()
if !HasWG() {
if uspace == "wg" {
log.Fatal("WireGuard not installed. Please install WireGuard (wireguard-tools) and try again.")
}
logger.Log(0, "running with userspace wireguard: ", uspace)
} else if uspace != "wg" {
logger.Log(0, "running userspace WireGuard with ", uspace)
}
}
// HasWG - returns true if wg command exists
func HasWG() bool {
var _, err = exec.LookPath("wg")
return err == nil
}
// ConvertKeyToBytes - util to convert a key to bytes to use elsewhere
func ConvertKeyToBytes(key *[32]byte) ([]byte, error) {
var buffer bytes.Buffer
var enc = gob.NewEncoder(&buffer)
if err := enc.Encode(key); err != nil {
return nil, err
}
return buffer.Bytes(), nil
}
// ServerAddrSliceContains - sees if a string slice contains a string element
func ServerAddrSliceContains(slice []models.ServerAddr, item models.ServerAddr) bool {
for _, s := range slice {
if s.Address == item.Address && s.IsLeader == item.IsLeader {
return true
}
}
return false
}
func GetIPNetFromString(ip string) (net.IPNet, error) {
var ipnet *net.IPNet
var err error
// parsing as a CIDR first. If valid CIDR, append
if _, cidr, err := net.ParseCIDR(ip); err == nil {
ipnet = cidr
} else { // parsing as an IP second. If valid IP, check if ipv4 or ipv6, then append
if iplib.Version(net.ParseIP(ip)) == 4 {
ipnet = &net.IPNet{
IP: net.ParseIP(ip),
Mask: net.CIDRMask(32, 32),
}
} else if iplib.Version(net.ParseIP(ip)) == 6 {
ipnet = &net.IPNet{
IP: net.ParseIP(ip),
Mask: net.CIDRMask(128, 128),
}
}
}
if ipnet == nil {
err = errors.New(ip + " is not a valid ip or cidr")
return net.IPNet{}, err
}
return *ipnet, err
}
// ConvertBytesToKey - util to convert bytes to a key to use elsewhere
func ConvertBytesToKey(data []byte) (*[32]byte, error) {
var buffer = bytes.NewBuffer(data)
var dec = gob.NewDecoder(buffer)
var result = new([32]byte)
var err = dec.Decode(result)
if err != nil {
return nil, err
}
return result, err
}
func IPIsPrivate(ipnet net.IP) bool {
return ipnet.IsPrivate() || ipnet.IsLoopback()
}
func SetInterfaceName(iface string) {
if runtime.GOOS == "darwin" && !strings.HasPrefix(iface, "utun") {
return
}
ifaceName = iface
}
// GetInterfaceName - fetches the interface name
func GetInterfaceName() string {
if ifaceName != "" {
return ifaceName
}
if runtime.GOOS == "darwin" {
return "utun69"
}
return "netmaker"
}
// RandomMacAddress returns a random macaddress
func RandomMacAddress() net.HardwareAddr {
//var mac net.HardwareAddr
buff := make([]byte, 6)
if _, err := rand.Read(buff); err != nil {
logger.Log(0, "error reading buffer, setting macaddress to zeo value", err.Error())
return net.HardwareAddr{}
}
// Set local bit to ensure no clash with globally administered addresses
buff[0] |= 2
mac := net.HardwareAddr(buff)
if _, err := net.ParseMAC(mac.String()); err != nil {
logger.Log(0, "randommac is not valid mac", err.Error())
return net.HardwareAddr{}
}
return mac
}
// RandomString - returns a random string in a charset
func RandomString(length int) string {
randombytes := make([]byte, length)
_, err := rand.Read(randombytes)
if err != nil {
logger.Log(0, "random string", err.Error())
return ""
}
return base32.StdEncoding.EncodeToString(randombytes)[:length]
}
// ConvHostPassToHash - converts password to md5 hash
func ConvHostPassToHash(hostPass string) string {
return fmt.Sprintf("%x", md5.Sum([]byte(hostPass)))
}
// InterfaceExists - checks if iface exists already
func InterfaceExists(ifaceName string) (bool, error) {
interfaces, err := net.Interfaces()
if err != nil {
return false, err
}
for _, inet := range interfaces {
if inet.Name == ifaceName {
return true, nil
}
}
return false, nil
}