netmaker/netclient/functions/join.go

305 lines
8.6 KiB
Go
Raw Normal View History

2021-05-26 00:48:04 +08:00
package functions
import (
2021-07-26 02:22:20 +08:00
"context"
2022-01-29 04:33:30 +08:00
"crypto/rand"
2021-08-03 06:06:26 +08:00
"encoding/json"
2021-05-26 00:48:04 +08:00
"errors"
2021-07-26 02:22:20 +08:00
"fmt"
2021-11-04 03:43:10 +08:00
"log"
2022-01-27 00:20:46 +08:00
"runtime"
2021-11-04 03:43:10 +08:00
2021-07-26 02:22:20 +08:00
nodepb "github.com/gravitl/netmaker/grpc"
"github.com/gravitl/netmaker/logger"
"github.com/gravitl/netmaker/logic"
2021-08-03 06:06:26 +08:00
"github.com/gravitl/netmaker/models"
"github.com/gravitl/netmaker/netclient/auth"
2021-07-26 02:22:20 +08:00
"github.com/gravitl/netmaker/netclient/config"
2021-09-20 02:03:47 +08:00
"github.com/gravitl/netmaker/netclient/daemon"
2021-07-26 02:22:20 +08:00
"github.com/gravitl/netmaker/netclient/local"
2021-09-20 02:03:47 +08:00
"github.com/gravitl/netmaker/netclient/ncutils"
2021-07-26 02:22:20 +08:00
"github.com/gravitl/netmaker/netclient/server"
"github.com/gravitl/netmaker/netclient/wireguard"
2022-01-30 04:02:37 +08:00
"golang.org/x/crypto/nacl/box"
2021-05-26 00:48:04 +08:00
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
2021-07-26 02:22:20 +08:00
"google.golang.org/grpc"
2021-05-26 00:48:04 +08:00
)
2021-10-09 03:07:12 +08:00
// JoinNetwork - helps a client join a network
func JoinNetwork(cfg *config.ClientConfig, privateKey string, iscomms bool) error {
2021-06-02 23:00:10 +08:00
if cfg.Node.Network == "" {
return errors.New("no network provided")
}
2021-05-26 00:48:04 +08:00
2021-10-13 03:44:19 +08:00
var err error
2022-01-29 04:33:30 +08:00
if local.HasNetwork(cfg.Network) {
err := errors.New("ALREADY_INSTALLED. Netclient appears to already be installed for " + cfg.Network + ". To re-install, please remove by executing 'sudo netclient leave -n " + cfg.Network + "'. Then re-run the install command.")
return err
}
2021-11-12 21:53:50 +08:00
err = config.Write(cfg, cfg.Network)
2022-01-29 04:33:30 +08:00
if err != nil {
return err
}
if cfg.Node.Password == "" {
cfg.Node.Password = logic.GenKey()
2022-01-29 04:33:30 +08:00
}
2022-01-30 04:02:37 +08:00
var trafficPubKey, trafficPrivKey, errT = box.GenerateKey(rand.Reader) // generate traffic keys
if errT != nil {
return errT
2022-01-29 04:33:30 +08:00
}
2022-01-30 04:02:37 +08:00
// == handle keys ==
2022-01-29 05:28:21 +08:00
if err = auth.StoreSecret(cfg.Node.Password, cfg.Node.Network); err != nil {
return err
}
2022-01-30 04:02:37 +08:00
if err = auth.StoreTrafficKey(trafficPrivKey, cfg.Node.Network); err != nil {
return err
2021-10-13 03:44:19 +08:00
}
2022-01-30 04:02:37 +08:00
trafficPubKeyBytes, err := ncutils.ConvertKeyToBytes(trafficPubKey)
if err != nil {
2022-01-29 05:28:21 +08:00
return err
} else if trafficPubKeyBytes == nil {
return fmt.Errorf("traffic key is nil")
2022-01-29 05:28:21 +08:00
}
2021-10-13 03:44:19 +08:00
2022-01-30 04:02:37 +08:00
cfg.Node.TrafficKeys.Mine = trafficPubKeyBytes
cfg.Node.TrafficKeys.Server = nil
// == end handle keys ==
2022-02-06 03:26:19 +08:00
if cfg.Node.LocalAddress == "" {
2022-02-02 13:02:36 +08:00
intIP, err := getPrivateAddr()
if err == nil {
cfg.Node.LocalAddress = intIP
2022-02-06 03:26:19 +08:00
} else {
logger.Log(1, "error retrieving private address: ", err.Error())
2022-02-02 13:02:36 +08:00
}
2021-05-26 00:48:04 +08:00
}
2021-09-20 02:03:47 +08:00
// set endpoint if blank. set to local if local net, retrieve from function if not
2021-07-26 02:22:20 +08:00
if cfg.Node.Endpoint == "" {
2021-05-26 00:48:04 +08:00
if cfg.Node.IsLocal == "yes" && cfg.Node.LocalAddress != "" {
cfg.Node.Endpoint = cfg.Node.LocalAddress
} else {
2021-09-20 02:03:47 +08:00
cfg.Node.Endpoint, err = ncutils.GetPublicIP()
}
if err != nil || cfg.Node.Endpoint == "" {
logger.Log(0, "Error setting cfg.Node.Endpoint.")
return err
2021-05-26 00:48:04 +08:00
}
2021-07-26 02:22:20 +08:00
}
// Generate and set public/private WireGuard Keys
2021-08-03 06:06:26 +08:00
if privateKey == "" {
wgPrivatekey, err := wgtypes.GeneratePrivateKey()
2021-05-26 00:48:04 +08:00
if err != nil {
log.Fatal(err)
}
2021-08-03 06:06:26 +08:00
privateKey = wgPrivatekey.String()
cfg.Node.PublicKey = wgPrivatekey.PublicKey().String()
2021-05-26 00:48:04 +08:00
}
// Find and set node MacAddress
2021-05-26 00:48:04 +08:00
if cfg.Node.MacAddress == "" {
2021-09-20 02:03:47 +08:00
macs, err := ncutils.GetMacAddr()
2022-03-08 09:33:03 +08:00
if err != nil || iscomms {
2022-02-15 03:13:18 +08:00
//if macaddress can't be found set to random string
cfg.Node.MacAddress = ncutils.MakeRandomString(18)
2021-05-26 00:48:04 +08:00
} else {
2021-07-26 02:22:20 +08:00
cfg.Node.MacAddress = macs[0]
2021-05-26 00:48:04 +08:00
}
}
2022-01-11 23:44:49 +08:00
2022-03-04 04:07:27 +08:00
// if ncutils.IsLinux() {
// _, err := exec.LookPath("resolvectl")
// if err != nil {
// logger.Log("resolvectl not present", 2)
// logger.Log("unable to configure DNS automatically, disabling automated DNS management", 2)
2022-03-04 04:07:27 +08:00
// cfg.Node.DNSOn = "no"
// }
// }
2021-11-11 00:59:03 +08:00
if ncutils.IsFreeBSD() {
cfg.Node.UDPHolePunch = "no"
}
2021-11-16 00:42:52 +08:00
// make sure name is appropriate, if not, give blank name
cfg.Node.Name = formatName(cfg.Node)
// differentiate between client/server here
2022-01-27 00:20:46 +08:00
var node = models.Node{
2022-02-16 04:40:38 +08:00
Password: cfg.Node.Password,
Address: cfg.Node.Address,
Address6: cfg.Node.Address6,
ID: cfg.Node.ID,
MacAddress: cfg.Node.MacAddress,
AccessKey: cfg.Server.AccessKey,
IsStatic: cfg.Node.IsStatic,
//Roaming: cfg.Node.Roaming,
2021-08-10 23:52:50 +08:00
Network: cfg.Network,
ListenPort: cfg.Node.ListenPort,
PostUp: cfg.Node.PostUp,
PostDown: cfg.Node.PostDown,
PersistentKeepalive: cfg.Node.PersistentKeepalive,
LocalAddress: cfg.Node.LocalAddress,
Interface: cfg.Node.Interface,
PublicKey: cfg.Node.PublicKey,
DNSOn: cfg.Node.DNSOn,
2021-08-10 23:52:50 +08:00
Name: cfg.Node.Name,
Endpoint: cfg.Node.Endpoint,
UDPHolePunch: cfg.Node.UDPHolePunch,
2022-01-30 04:02:37 +08:00
TrafficKeys: cfg.Node.TrafficKeys,
2022-02-04 04:33:19 +08:00
OS: runtime.GOOS,
Version: ncutils.Version,
2021-08-10 23:52:50 +08:00
}
logger.Log(0, "joining "+cfg.Network+" at "+cfg.Server.GRPCAddress)
2022-01-27 00:20:46 +08:00
var wcclient nodepb.NodeServiceClient
2021-08-03 06:06:26 +08:00
2022-01-27 00:20:46 +08:00
conn, err := grpc.Dial(cfg.Server.GRPCAddress,
ncutils.GRPCRequestOpts(cfg.Server.GRPCSSL))
2022-01-27 00:20:46 +08:00
if err != nil {
log.Fatalf("Unable to establish client connection to "+cfg.Server.GRPCAddress+": %v", err)
2021-07-26 02:22:20 +08:00
}
2022-01-27 00:20:46 +08:00
defer conn.Close()
wcclient = nodepb.NewNodeServiceClient(conn)
2021-05-26 00:48:04 +08:00
// safety check. If returned node from server is local, but not currently configured as local, set to local addr
if cfg.Node.IsLocal != "yes" && node.IsLocal == "yes" && node.LocalRange != "" {
2021-09-20 02:03:47 +08:00
node.LocalAddress, err = ncutils.GetLocalIP(node.LocalRange)
2021-05-26 00:48:04 +08:00
if err != nil {
return err
}
2021-08-03 06:06:26 +08:00
node.Endpoint = node.LocalAddress
2021-05-26 00:48:04 +08:00
}
2021-11-11 00:59:03 +08:00
if ncutils.IsFreeBSD() {
node.UDPHolePunch = "no"
cfg.Node.IsStatic = "yes"
}
2022-01-27 00:20:46 +08:00
err = wireguard.StorePrivKey(privateKey, cfg.Network)
if err != nil {
return err
}
if node.IsPending == "yes" {
logger.Log(0, "Node is marked as PENDING.")
logger.Log(0, "Awaiting approval from Admin before configuring WireGuard.")
2022-01-27 00:20:46 +08:00
if cfg.Daemon != "off" {
return daemon.InstallDaemon(cfg)
2021-11-04 03:43:10 +08:00
}
2021-05-26 00:48:04 +08:00
}
2022-01-27 00:20:46 +08:00
data, err := json.Marshal(&node)
if err != nil {
return err
}
// Create node on server
res, err := wcclient.CreateNode(
context.TODO(),
&nodepb.Object{
Data: string(data),
Type: nodepb.NODE_TYPE,
},
)
if err != nil {
return err
}
logger.Log(1, "node created on remote server...updating configs")
2022-01-27 00:20:46 +08:00
2022-02-23 06:50:41 +08:00
// keep track of the old listenport value
oldListenPort := node.ListenPort
2022-01-27 00:20:46 +08:00
nodeData := res.Data
if err = json.Unmarshal([]byte(nodeData), &node); err != nil {
return err
}
2022-02-04 04:33:19 +08:00
2022-01-27 00:20:46 +08:00
cfg.Node = node
2022-02-23 06:50:41 +08:00
setListenPort(oldListenPort, cfg)
2022-02-23 06:50:41 +08:00
err = config.ModConfig(&cfg.Node)
2022-01-27 00:20:46 +08:00
if err != nil {
return err
}
// attempt to make backup
if err = config.SaveBackup(node.Network); err != nil {
logger.Log(0, "failed to make backup, node will not auto restore if config is corrupted")
2022-01-27 00:20:46 +08:00
}
logger.Log(0, "retrieving peers")
peers, hasGateway, gateways, err := server.GetPeers(node.MacAddress, cfg.Network, cfg.Server.GRPCAddress, node.IsDualStack == "yes", node.IsIngressGateway == "yes", node.IsServer == "yes")
2021-09-20 02:03:47 +08:00
if err != nil && !ncutils.IsEmptyRecord(err) {
logger.Log(0, "failed to retrieve peers")
2021-07-26 02:22:20 +08:00
return err
}
2021-08-10 22:55:48 +08:00
logger.Log(0, "starting wireguard")
2021-11-13 00:24:29 +08:00
err = wireguard.InitWireguard(&node, privateKey, peers, hasGateway, gateways, false)
2021-07-26 02:22:20 +08:00
if err != nil {
return err
}
2022-03-04 04:07:27 +08:00
// if node.DNSOn == "yes" {
// for _, server := range node.NetworkSettings.DefaultServerAddrs {
// if server.IsLeader {
// go func() {
// if !local.SetDNSWithRetry(node, server.Address) {
// cfg.Node.DNSOn = "no"
// var currentCommsCfg = getCommsCfgByNode(&cfg.Node)
// PublishNodeUpdate(&currentCommsCfg, &cfg)
// }
// }()
// break
// }
// }
// }
2022-02-07 00:06:04 +08:00
2022-02-19 09:21:03 +08:00
if !iscomms {
if cfg.Daemon != "off" {
err = daemon.InstallDaemon(cfg)
}
if err != nil {
return err
} else {
daemon.Restart()
}
2021-07-26 02:22:20 +08:00
}
2021-05-26 00:48:04 +08:00
2022-02-19 09:21:03 +08:00
return nil
2021-05-26 00:48:04 +08:00
}
2021-11-16 00:42:52 +08:00
// format name appropriately. Set to blank on failure
func formatName(node models.Node) string {
// Logic to properly format name
if !node.NameInNodeCharSet() {
node.Name = ncutils.DNSFormatString(node.Name)
}
if len(node.Name) > models.MAX_NAME_LENGTH {
node.Name = ncutils.ShortenString(node.Name, models.MAX_NAME_LENGTH)
}
if !node.NameInNodeCharSet() || len(node.Name) > models.MAX_NAME_LENGTH {
logger.Log(1, "could not properly format name: "+node.Name)
logger.Log(1, "setting name to blank")
2021-11-16 00:42:52 +08:00
node.Name = ""
}
return node.Name
}
2022-02-23 06:50:41 +08:00
func setListenPort(oldListenPort int32, cfg *config.ClientConfig) {
// keep track of the returned listenport value
newListenPort := cfg.Node.ListenPort
if newListenPort != oldListenPort {
var errN error
// get free port based on returned default listen port
cfg.Node.ListenPort, errN = ncutils.GetFreePort(cfg.Node.ListenPort)
if errN != nil {
cfg.Node.ListenPort = newListenPort
logger.Log(1, "Error retrieving port: ", errN.Error())
2022-02-23 06:50:41 +08:00
}
// if newListenPort has been modified to find an available port, publish to server
if cfg.Node.ListenPort != newListenPort {
var currentCommsCfg = getCommsCfgByNode(&cfg.Node)
PublishNodeUpdate(&currentCommsCfg, cfg)
}
}
}