netmaker/logic/server.go

424 lines
12 KiB
Go
Raw Normal View History

2021-10-13 03:44:19 +08:00
package logic
import (
"errors"
2021-10-27 21:27:52 +08:00
"fmt"
2021-10-13 03:44:19 +08:00
"net"
2021-10-13 22:02:04 +08:00
"os"
2021-10-13 03:44:19 +08:00
"runtime"
"strconv"
"strings"
"time"
2021-12-07 04:31:08 +08:00
"github.com/gravitl/netmaker/logger"
2021-10-13 03:44:19 +08:00
"github.com/gravitl/netmaker/models"
"github.com/gravitl/netmaker/netclient/ncutils"
"github.com/gravitl/netmaker/servercfg"
2021-10-13 03:44:19 +08:00
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
// == Join, Checkin, and Leave for Server ==
2021-10-16 02:15:32 +08:00
// KUBERNETES_LISTEN_PORT - starting port for Kubernetes in order to use NodePort range
const KUBERNETES_LISTEN_PORT = 31821
2021-12-11 04:01:10 +08:00
// KUBERNETES_SERVER_MTU - ideal mtu for kubernetes deployments right now
2021-10-18 03:31:37 +08:00
const KUBERNETES_SERVER_MTU = 1024
2021-10-16 02:15:32 +08:00
2021-10-14 03:15:20 +08:00
// ServerJoin - responsible for joining a server to a network
func ServerJoin(network string, serverID string, privateKey string) error {
if network == "" {
2021-10-13 03:44:19 +08:00
return errors.New("no network provided")
}
2021-10-14 03:15:20 +08:00
var err error
var node = &models.Node{
IsServer: "yes",
DNSOn: "no",
IsStatic: "yes",
Name: models.NODE_SERVER_NAME,
MacAddress: serverID,
UDPHolePunch: "no",
2021-10-14 03:15:20 +08:00
}
2021-10-27 00:27:29 +08:00
SetNodeDefaults(node)
2021-10-18 03:31:37 +08:00
2021-10-16 02:15:32 +08:00
if servercfg.GetPlatform() == "Kubernetes" {
node.ListenPort = KUBERNETES_LISTEN_PORT
2021-10-18 03:31:37 +08:00
node.MTU = KUBERNETES_SERVER_MTU
2021-10-16 02:15:32 +08:00
}
2021-10-14 03:15:20 +08:00
if node.LocalRange != "" && node.LocalAddress == "" {
2021-12-07 04:31:08 +08:00
logger.Log(1, "local vpn, getting local address from range:", node.LocalRange)
2021-10-14 03:15:20 +08:00
node.LocalAddress = GetLocalIP(*node)
2021-10-13 03:44:19 +08:00
}
2021-10-14 03:15:20 +08:00
if node.Endpoint == "" {
if node.IsLocal == "yes" && node.LocalAddress != "" {
node.Endpoint = node.LocalAddress
2021-10-13 03:44:19 +08:00
} else {
2021-10-14 03:15:20 +08:00
node.Endpoint, err = ncutils.GetPublicIP()
2021-10-13 03:44:19 +08:00
}
2021-10-14 03:15:20 +08:00
if err != nil || node.Endpoint == "" {
2021-12-07 04:31:08 +08:00
logger.Log(0, "Error setting server node Endpoint.")
2021-10-13 03:44:19 +08:00
return err
}
}
// Generate and set public/private WireGuard Keys
if privateKey == "" {
wgPrivatekey, err := wgtypes.GeneratePrivateKey()
if err != nil {
2021-12-07 04:31:08 +08:00
logger.Log(1, err.Error())
2021-10-13 03:44:19 +08:00
return err
}
privateKey = wgPrivatekey.String()
2021-10-14 03:15:20 +08:00
node.PublicKey = wgPrivatekey.PublicKey().String()
2021-10-13 03:44:19 +08:00
}
node.Network = network
logger.Log(2, "adding a server instance on network", node.Network)
2021-12-11 10:09:42 +08:00
err = CreateNode(node)
2021-10-13 03:44:19 +08:00
if err != nil {
return err
}
err = SetNetworkNodesLastModified(node.Network)
if err != nil {
return err
}
// get free port based on returned default listen port
node.ListenPort, err = ncutils.GetFreePort(node.ListenPort)
if err != nil {
2021-12-07 04:31:08 +08:00
logger.Log(2, "Error retrieving port:", err.Error())
2021-10-27 21:27:52 +08:00
} else {
2021-12-07 04:31:08 +08:00
logger.Log(1, "Set client port to", fmt.Sprintf("%d", node.ListenPort), "for network", node.Network)
2021-10-13 03:44:19 +08:00
}
// safety check. If returned node from server is local, but not currently configured as local, set to local addr
2021-10-14 03:15:20 +08:00
if node.IsLocal == "yes" && node.LocalRange != "" {
2021-10-13 03:44:19 +08:00
node.LocalAddress, err = ncutils.GetLocalIP(node.LocalRange)
if err != nil {
return err
}
node.Endpoint = node.LocalAddress
}
node.SetID()
if err = StorePrivKey(node.ID, privateKey); err != nil {
return err
}
2021-10-27 22:02:39 +08:00
if err = ServerPush(node); err != nil {
2021-10-13 03:44:19 +08:00
return err
}
2021-12-11 04:01:10 +08:00
peers, hasGateway, gateways, err := GetServerPeers(node)
2021-10-13 03:44:19 +08:00
if err != nil && !ncutils.IsEmptyRecord(err) {
2021-12-07 04:31:08 +08:00
logger.Log(1, "failed to retrieve peers")
2021-10-13 03:44:19 +08:00
return err
}
2021-12-11 04:01:10 +08:00
err = initWireguard(node, privateKey, peers[:], hasGateway, gateways[:])
2021-10-13 03:44:19 +08:00
if err != nil {
return err
}
return nil
}
2021-10-14 03:15:20 +08:00
// ServerCheckin - runs pulls and pushes for server
func ServerCheckin(mac string, network string) error {
2021-12-12 01:07:54 +08:00
var serverNode = &models.Node{}
2021-12-11 04:01:10 +08:00
var currentNode, err = GetNode(mac, network)
2021-10-14 03:15:20 +08:00
if err != nil {
return err
}
2021-12-11 04:01:10 +08:00
serverNode = &currentNode
2021-10-14 03:15:20 +08:00
2021-12-11 04:01:10 +08:00
err = ServerPull(serverNode, false)
2021-10-14 03:15:20 +08:00
if isDeleteError(err) {
return ServerLeave(mac, network)
} else if err != nil {
return err
}
2021-12-11 04:01:10 +08:00
actionCompleted := checkNodeActions(serverNode)
2021-10-14 03:15:20 +08:00
if actionCompleted == models.NODE_DELETE {
return errors.New("node has been removed")
}
2021-12-11 04:01:10 +08:00
return ServerPush(serverNode)
2021-10-14 03:15:20 +08:00
}
2021-10-13 22:02:04 +08:00
// ServerPull - pulls current config/peers for server
2021-12-11 04:01:10 +08:00
func ServerPull(serverNode *models.Node, onErr bool) error {
2021-10-13 22:02:04 +08:00
var err error
if serverNode.IPForwarding == "yes" {
if err = setIPForwardingLinux(); err != nil {
2021-12-11 04:01:10 +08:00
return err
2021-10-13 22:02:04 +08:00
}
}
serverNode.OS = runtime.GOOS
if serverNode.PullChanges == "yes" || onErr {
2021-10-13 22:02:04 +08:00
// check for interface change
// checks if address is in use by another interface
2021-12-11 04:01:10 +08:00
var oldIfaceName, isIfacePresent = isInterfacePresent(serverNode.Interface, serverNode.Address)
2021-10-13 22:02:04 +08:00
if !isIfacePresent {
if err = deleteInterface(oldIfaceName, serverNode.PostDown); err != nil {
2021-12-07 04:31:08 +08:00
logger.Log(1, "could not delete old interface", oldIfaceName)
2021-10-13 22:02:04 +08:00
}
2021-12-07 04:31:08 +08:00
logger.Log(1, "removed old interface", oldIfaceName)
2021-10-13 22:02:04 +08:00
}
serverNode.PullChanges = "no"
2021-12-11 04:01:10 +08:00
if err = setWGConfig(serverNode, false); err != nil {
return err
2021-10-13 22:02:04 +08:00
}
// handle server side update
2021-10-27 22:02:39 +08:00
if err = UpdateNode(serverNode, serverNode); err != nil {
2021-12-11 04:01:10 +08:00
return err
2021-10-13 22:02:04 +08:00
}
} else {
2021-12-11 04:01:10 +08:00
if err = setWGConfig(serverNode, true); err != nil {
2021-10-13 22:02:04 +08:00
if errors.Is(err, os.ErrNotExist) {
2021-10-27 22:02:39 +08:00
return ServerPull(serverNode, true)
2021-10-13 22:02:04 +08:00
} else {
2021-12-11 04:01:10 +08:00
return err
2021-10-13 22:02:04 +08:00
}
}
}
2021-12-11 04:01:10 +08:00
return nil
2021-10-13 22:02:04 +08:00
}
2021-10-13 03:44:19 +08:00
// ServerPush - pushes config changes for server checkins/join
2021-10-27 22:02:39 +08:00
func ServerPush(serverNode *models.Node) error {
2021-10-13 03:44:19 +08:00
serverNode.OS = runtime.GOOS
serverNode.SetLastCheckIn()
2021-10-27 22:02:39 +08:00
return UpdateNode(serverNode, serverNode)
2021-10-13 22:02:04 +08:00
}
// ServerLeave - removes a server node
func ServerLeave(mac string, network string) error {
2021-12-11 04:01:10 +08:00
var serverNode, err = GetNode(mac, network)
2021-10-13 22:02:04 +08:00
if err != nil {
return err
}
serverNode.SetID()
return DeleteNode(&serverNode, true)
2021-10-13 03:44:19 +08:00
}
/**
* Below function needs major refactor
*
*/
2021-10-13 22:02:04 +08:00
// GetServerPeers - gets peers of server
2021-12-11 04:01:10 +08:00
func GetServerPeers(serverNode *models.Node) ([]wgtypes.PeerConfig, bool, []string, error) {
2021-10-13 03:44:19 +08:00
hasGateway := false
var gateways []string
var peers []wgtypes.PeerConfig
var nodes []models.Node // fill above fields from server or client
2021-12-11 04:01:10 +08:00
var nodecfg, err = GetNode(serverNode.MacAddress, serverNode.Network)
2021-10-13 03:44:19 +08:00
if err != nil {
return nil, hasGateway, gateways, err
}
2021-12-11 04:01:10 +08:00
nodes, err = GetPeers(&nodecfg)
2021-10-13 03:44:19 +08:00
if err != nil {
return nil, hasGateway, gateways, err
}
keepalive := nodecfg.PersistentKeepalive
keepalivedur, err := time.ParseDuration(strconv.FormatInt(int64(keepalive), 10) + "s")
if err != nil {
2021-12-11 04:01:10 +08:00
logger.Log(1, "Issue with format of keepalive duration value, Please view server config:", err.Error())
2021-10-13 03:44:19 +08:00
return nil, hasGateway, gateways, err
}
for _, node := range nodes {
pubkey, err := wgtypes.ParseKey(node.PublicKey)
if err != nil {
2021-12-07 04:31:08 +08:00
logger.Log(1, "error parsing key", pubkey.String())
2021-10-13 03:44:19 +08:00
return peers, hasGateway, gateways, err
}
if nodecfg.PublicKey == node.PublicKey {
continue
}
if nodecfg.Endpoint == node.Endpoint {
if nodecfg.LocalAddress != node.LocalAddress && node.LocalAddress != "" {
node.Endpoint = node.LocalAddress
} else {
continue
}
}
var peer wgtypes.PeerConfig
var peeraddr = net.IPNet{
IP: net.ParseIP(node.Address),
Mask: net.CIDRMask(32, 32),
}
2021-12-11 04:01:10 +08:00
var allowedips = []net.IPNet{
peeraddr,
}
2021-10-13 03:44:19 +08:00
// handle manually set peers
for _, allowedIp := range node.AllowedIPs {
if _, ipnet, err := net.ParseCIDR(allowedIp); err == nil {
nodeEndpointArr := strings.Split(node.Endpoint, ":")
if !ipnet.Contains(net.IP(nodeEndpointArr[0])) && ipnet.IP.String() != node.Address { // don't need to add an allowed ip that already exists..
allowedips = append(allowedips, *ipnet)
}
} else if appendip := net.ParseIP(allowedIp); appendip != nil && allowedIp != node.Address {
ipnet := net.IPNet{
IP: net.ParseIP(allowedIp),
Mask: net.CIDRMask(32, 32),
}
allowedips = append(allowedips, ipnet)
}
}
// handle egress gateway peers
if node.IsEgressGateway == "yes" {
hasGateway = true
2021-12-11 10:09:42 +08:00
ranges := node.EgressGatewayRanges
2021-10-13 03:44:19 +08:00
for _, iprange := range ranges { // go through each cidr for egress gateway
_, ipnet, err := net.ParseCIDR(iprange) // confirming it's valid cidr
if err != nil {
2021-12-07 04:31:08 +08:00
logger.Log(1, "could not parse gateway IP range. Not adding", iprange)
2021-10-13 03:44:19 +08:00
continue // if can't parse CIDR
}
nodeEndpointArr := strings.Split(node.Endpoint, ":") // getting the public ip of node
if ipnet.Contains(net.ParseIP(nodeEndpointArr[0])) { // ensuring egress gateway range does not contain public ip of node
2021-12-07 04:31:08 +08:00
logger.Log(2, "egress IP range of", iprange, "overlaps with", node.Endpoint, ", omitting")
2021-10-13 03:44:19 +08:00
continue // skip adding egress range if overlaps with node's ip
}
if ipnet.Contains(net.ParseIP(nodecfg.LocalAddress)) { // ensuring egress gateway range does not contain public ip of node
2021-12-07 04:31:08 +08:00
logger.Log(2, "egress IP range of", iprange, "overlaps with", nodecfg.LocalAddress, ", omitting")
2021-10-13 03:44:19 +08:00
continue // skip adding egress range if overlaps with node's local ip
}
gateways = append(gateways, iprange)
if err != nil {
2021-12-07 04:31:08 +08:00
logger.Log(1, "ERROR ENCOUNTERED SETTING GATEWAY:", err.Error())
2021-10-13 03:44:19 +08:00
} else {
allowedips = append(allowedips, *ipnet)
}
}
2021-12-11 04:01:10 +08:00
ranges = nil
2021-10-13 03:44:19 +08:00
}
2021-12-11 04:01:10 +08:00
if node.Address6 != "" && serverNode.IsDualStack == "yes" {
2021-10-13 03:44:19 +08:00
var addr6 = net.IPNet{
IP: net.ParseIP(node.Address6),
Mask: net.CIDRMask(128, 128),
}
allowedips = append(allowedips, addr6)
}
2021-12-11 04:01:10 +08:00
peer = wgtypes.PeerConfig{
PublicKey: pubkey,
PersistentKeepaliveInterval: &(keepalivedur),
ReplaceAllowedIPs: true,
AllowedIPs: allowedips,
2021-10-13 03:44:19 +08:00
}
peers = append(peers, peer)
}
2021-12-11 04:01:10 +08:00
if serverNode.IsIngressGateway == "yes" {
extPeers, err := GetServerExtPeers(serverNode)
2021-10-13 03:44:19 +08:00
if err == nil {
peers = append(peers, extPeers...)
} else {
2021-12-07 04:31:08 +08:00
logger.Log(1, "ERROR RETRIEVING EXTERNAL PEERS ON SERVER:", err.Error())
2021-10-13 03:44:19 +08:00
}
2021-12-11 04:01:10 +08:00
extPeers = nil
2021-10-13 03:44:19 +08:00
}
2021-12-11 04:01:10 +08:00
return peers, hasGateway, gateways, err
2021-10-13 03:44:19 +08:00
}
// GetServerExtPeers - gets the extpeers for a client
2021-12-11 04:01:10 +08:00
func GetServerExtPeers(serverNode *models.Node) ([]wgtypes.PeerConfig, error) {
2021-10-13 03:44:19 +08:00
var peers []wgtypes.PeerConfig
var extPeers []models.Node
var err error
var tempPeers []models.ExtPeersResponse
2021-12-11 04:01:10 +08:00
tempPeers, err = GetExtPeersList(serverNode.MacAddress, serverNode.Network)
2021-10-13 03:44:19 +08:00
if err != nil {
return nil, err
}
2021-12-11 04:01:10 +08:00
2021-10-13 03:44:19 +08:00
for i := 0; i < len(tempPeers); i++ {
extPeers = append(extPeers, models.Node{
Address: tempPeers[i].Address,
Address6: tempPeers[i].Address6,
Endpoint: tempPeers[i].Endpoint,
PublicKey: tempPeers[i].PublicKey,
PersistentKeepalive: tempPeers[i].KeepAlive,
ListenPort: tempPeers[i].ListenPort,
LocalAddress: tempPeers[i].LocalAddress,
})
}
for _, extPeer := range extPeers {
pubkey, err := wgtypes.ParseKey(extPeer.PublicKey)
if err != nil {
return peers, err
}
2021-12-11 04:01:10 +08:00
if serverNode.PublicKey == extPeer.PublicKey {
2021-10-13 03:44:19 +08:00
continue
}
var peer wgtypes.PeerConfig
var peeraddr = net.IPNet{
IP: net.ParseIP(extPeer.Address),
Mask: net.CIDRMask(32, 32),
}
2021-12-11 04:01:10 +08:00
var allowedips = []net.IPNet{
peeraddr,
}
2021-10-13 03:44:19 +08:00
2021-12-11 04:01:10 +08:00
if extPeer.Address6 != "" && serverNode.IsDualStack == "yes" {
2021-10-13 03:44:19 +08:00
var addr6 = net.IPNet{
IP: net.ParseIP(extPeer.Address6),
Mask: net.CIDRMask(128, 128),
}
allowedips = append(allowedips, addr6)
}
peer = wgtypes.PeerConfig{
PublicKey: pubkey,
ReplaceAllowedIPs: true,
AllowedIPs: allowedips,
}
peers = append(peers, peer)
2021-12-11 04:01:10 +08:00
allowedips = nil
2021-10-13 03:44:19 +08:00
}
2021-12-11 04:01:10 +08:00
tempPeers = nil
extPeers = nil
return peers, err
2021-10-13 03:44:19 +08:00
}
2021-10-14 03:15:20 +08:00
// == Private ==
func isDeleteError(err error) bool {
return err != nil && strings.Contains(err.Error(), models.NODE_DELETE)
}
2021-12-11 04:01:10 +08:00
func checkNodeActions(node *models.Node) string {
if (node.Action == models.NODE_UPDATE_KEY) &&
2021-10-14 03:15:20 +08:00
node.IsStatic != "yes" {
err := setWGKeyConfig(node)
2021-10-14 03:15:20 +08:00
if err != nil {
2021-12-07 04:31:08 +08:00
logger.Log(1, "unable to process reset keys request:", err.Error())
2021-10-14 03:15:20 +08:00
return ""
}
}
2021-12-11 04:01:10 +08:00
if node.Action == models.NODE_DELETE {
err := ServerLeave(node.MacAddress, node.Network)
2021-10-14 03:15:20 +08:00
if err != nil {
2021-12-07 04:31:08 +08:00
logger.Log(1, "error deleting locally:", err.Error())
2021-10-14 03:15:20 +08:00
}
return models.NODE_DELETE
}
return ""
}