netmaker/logic/peers.go

348 lines
10 KiB
Go
Raw Normal View History

package logic
import (
2022-03-14 23:34:25 +08:00
"fmt"
"log"
"net"
"strconv"
"strings"
"time"
2022-02-19 00:43:49 +08:00
"github.com/gravitl/netmaker/database"
2022-01-31 04:18:15 +08:00
"github.com/gravitl/netmaker/logger"
2022-03-11 01:37:52 +08:00
"github.com/gravitl/netmaker/logic/acls"
"github.com/gravitl/netmaker/logic/acls/nodeacls"
"github.com/gravitl/netmaker/models"
"github.com/gravitl/netmaker/netclient/ncutils"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
2022-02-19 00:43:49 +08:00
// GetHubPeer - in HubAndSpoke networks, if not the hub, return the hub
2022-02-22 00:12:15 +08:00
/*
2022-02-19 00:43:49 +08:00
func GetHubPeer(networkName string) []models.Node {
var hubpeer = make([]models.Node, 0)
servernodes, err := GetNetworkNodes(networkName)
if err != nil {
return hubpeer
}
for i := range servernodes {
if servernodes[i].IsHub == "yes" {
return []models.Node{servernodes[i]}
}
}
return hubpeer
}
2022-02-22 00:12:15 +08:00
*/
2022-02-19 00:43:49 +08:00
// GetNodePeers - fetches peers for a given node
2022-03-11 01:37:52 +08:00
func GetNodePeers(networkName, nodeid string, excludeRelayed bool, isP2S bool) ([]models.Node, error) {
2022-02-19 00:43:49 +08:00
var peers []models.Node
var networkNodes, egressNetworkNodes, err = getNetworkEgressAndNodes(networkName)
if err != nil {
return peers, nil
}
udppeers, errN := database.GetPeers(networkName)
if errN != nil {
logger.Log(2, errN.Error())
}
2022-03-11 01:37:52 +08:00
currentNetworkACLs, aclErr := nodeacls.FetchAllACLs(nodeacls.NetworkID(networkName))
if aclErr != nil {
return peers, aclErr
}
2022-02-19 00:43:49 +08:00
for _, node := range networkNodes {
2022-03-12 04:19:06 +08:00
if !currentNetworkACLs.IsAllowed(acls.AclID(nodeid), acls.AclID(node.ID)) {
continue
}
2022-02-19 00:43:49 +08:00
var peer = models.Node{}
if node.IsEgressGateway == "yes" { // handle egress stuff
peer.EgressGatewayRanges = node.EgressGatewayRanges
peer.IsEgressGateway = node.IsEgressGateway
}
allow := node.IsRelayed != "yes" || !excludeRelayed
if node.Network == networkName && node.IsPending != "yes" && allow {
peer = setPeerInfo(&node)
if node.UDPHolePunch == "yes" && errN == nil && CheckEndpoint(udppeers[node.PublicKey]) {
endpointstring := udppeers[node.PublicKey]
endpointarr := strings.Split(endpointstring, ":")
if len(endpointarr) == 2 {
port, err := strconv.Atoi(endpointarr[1])
if err == nil {
// peer.Endpoint = endpointarr[0]
peer.ListenPort = int32(port)
}
}
}
if node.IsRelay == "yes" {
network, err := GetNetwork(networkName)
if err == nil {
peer.AllowedIPs = append(peer.AllowedIPs, network.AddressRange)
} else {
peer.AllowedIPs = append(peer.AllowedIPs, node.RelayAddrs...)
}
for _, egressNode := range egressNetworkNodes {
if egressNode.IsRelayed == "yes" && StringSliceContains(node.RelayAddrs, egressNode.Address) {
peer.AllowedIPs = append(peer.AllowedIPs, egressNode.EgressGatewayRanges...)
}
}
}
2022-03-11 03:55:25 +08:00
if (!isP2S || peer.IsHub == "yes") && currentNetworkACLs.IsAllowed(acls.AclID(nodeid), acls.AclID(node.ID)) {
2022-02-22 00:08:45 +08:00
peers = append(peers, peer)
}
2022-02-19 00:43:49 +08:00
}
}
return peers, err
}
// GetPeersList - gets the peers of a given network
func GetPeersList(refnode *models.Node) ([]models.Node, error) {
var peers []models.Node
var err error
2022-02-22 00:08:45 +08:00
var isP2S bool
2022-02-19 00:43:49 +08:00
var networkName = refnode.Network
var excludeRelayed = refnode.IsRelay != "yes"
var relayedNodeAddr string
if refnode.IsRelayed == "yes" {
relayedNodeAddr = refnode.Address
}
2022-02-22 00:08:45 +08:00
2022-02-19 00:43:49 +08:00
network, err := GetNetwork(networkName)
if err != nil {
return peers, err
2022-02-21 22:45:42 +08:00
} else if network.IsPointToSite == "yes" && refnode.IsHub != "yes" {
2022-02-22 00:08:45 +08:00
isP2S = true
2022-02-19 00:43:49 +08:00
}
if relayedNodeAddr == "" {
2022-03-11 01:37:52 +08:00
peers, err = GetNodePeers(networkName, refnode.ID, excludeRelayed, isP2S)
2022-02-19 00:43:49 +08:00
} else {
var relayNode models.Node
relayNode, err = GetNodeRelay(networkName, relayedNodeAddr)
if relayNode.Address != "" {
var peerNode = setPeerInfo(&relayNode)
network, err := GetNetwork(networkName)
if err == nil {
peerNode.AllowedIPs = append(peerNode.AllowedIPs, network.AddressRange)
var _, egressNetworkNodes, err = getNetworkEgressAndNodes(networkName)
if err == nil {
for _, egress := range egressNetworkNodes {
if egress.Address != relayedNodeAddr {
peerNode.AllowedIPs = append(peerNode.AllowedIPs, egress.EgressGatewayRanges...)
}
}
}
} else {
peerNode.AllowedIPs = append(peerNode.AllowedIPs, peerNode.RelayAddrs...)
}
2022-03-11 01:37:52 +08:00
nodepeers, err := GetNodePeers(networkName, refnode.ID, false, isP2S)
2022-02-19 00:43:49 +08:00
if err == nil && peerNode.UDPHolePunch == "yes" {
for _, nodepeer := range nodepeers {
if nodepeer.Address == peerNode.Address {
// peerNode.Endpoint = nodepeer.Endpoint
peerNode.ListenPort = nodepeer.ListenPort
}
}
}
2022-02-22 00:11:46 +08:00
if !isP2S || peerNode.IsHub == "yes" {
peers = append(peers, peerNode)
}
2022-02-19 00:43:49 +08:00
}
}
return peers, err
}
2022-01-26 07:15:27 +08:00
// GetPeerUpdate - gets a wireguard peer config for each peer of a node
func GetPeerUpdate(node *models.Node) (models.PeerUpdate, error) {
var peerUpdate models.PeerUpdate
var peers []wgtypes.PeerConfig
2022-01-31 00:51:39 +08:00
var serverNodeAddresses = []models.ServerAddr{}
currentPeers, err := GetPeers(node)
if err != nil {
return models.PeerUpdate{}, err
}
2022-01-31 04:18:15 +08:00
// begin translating netclient logic
/*
Go through netclient code and put below
*/
// #1 Set Keepalive values: set_keepalive
// #2 Set local address: set_local - could be a LOT BETTER and fix some bugs with additional logic
// #3 Set allowedips: set_allowedips
2022-03-14 23:34:25 +08:00
var dns string
2022-01-31 00:51:39 +08:00
for _, peer := range currentPeers {
if peer.ID == node.ID {
//skip yourself
continue
}
2022-03-15 01:55:38 +08:00
dns = dns + fmt.Sprintf("%s %s.%s\n", peer.Address, peer.Name, peer.Network)
pubkey, err := wgtypes.ParseKey(peer.PublicKey)
if err != nil {
return models.PeerUpdate{}, err
}
if node.Endpoint == peer.Endpoint {
//peer is on same network
2022-01-31 04:18:15 +08:00
// set_local
if node.LocalAddress != peer.LocalAddress && peer.LocalAddress != "" {
peer.Endpoint = peer.LocalAddress
} else {
continue
}
}
endpoint := peer.Endpoint + ":" + strconv.FormatInt(int64(peer.ListenPort), 10)
address, err := net.ResolveUDPAddr("udp", endpoint)
if err != nil {
return models.PeerUpdate{}, err
}
2022-01-31 04:18:15 +08:00
// set_allowedips
allowedips := GetAllowedIPs(node, &peer)
var keepalive time.Duration
if node.PersistentKeepalive != 0 {
2022-01-31 04:18:15 +08:00
// set_keepalive
keepalive, _ = time.ParseDuration(strconv.FormatInt(int64(node.PersistentKeepalive), 10) + "s")
}
var peerData = wgtypes.PeerConfig{
PublicKey: pubkey,
Endpoint: address,
ReplaceAllowedIPs: true,
AllowedIPs: allowedips,
PersistentKeepaliveInterval: &keepalive,
}
peers = append(peers, peerData)
2022-01-26 11:14:31 +08:00
if peer.IsServer == "yes" {
serverNodeAddresses = append(serverNodeAddresses, models.ServerAddr{IsLeader: IsLeader(&peer), Address: peer.Address})
2022-01-26 11:14:31 +08:00
}
}
2022-01-31 04:18:15 +08:00
if node.IsIngressGateway == "yes" {
extPeers, err := getExtPeers(node)
if err == nil {
peers = append(peers, extPeers...)
} else {
log.Println("ERROR RETRIEVING EXTERNAL PEERS", err)
}
}
peerUpdate.Network = node.Network
peerUpdate.Peers = peers
2022-01-26 11:14:31 +08:00
peerUpdate.ServerAddrs = serverNodeAddresses
2022-01-31 04:18:15 +08:00
/*
End translation of netclient code
*/
2022-03-15 02:59:41 +08:00
peerUpdate.DNS = dns
return peerUpdate, nil
}
2022-01-31 04:18:15 +08:00
func getExtPeers(node *models.Node) ([]wgtypes.PeerConfig, error) {
var peers []wgtypes.PeerConfig
extPeers, err := GetExtPeersList(node)
if err != nil {
return peers, err
}
for _, extPeer := range extPeers {
pubkey, err := wgtypes.ParseKey(extPeer.PublicKey)
if err != nil {
logger.Log(1, "error parsing ext pub key:", err.Error())
continue
}
if node.PublicKey == extPeer.PublicKey {
continue
}
var peer wgtypes.PeerConfig
var peeraddr = net.IPNet{
IP: net.ParseIP(extPeer.Address),
Mask: net.CIDRMask(32, 32),
}
var allowedips []net.IPNet
allowedips = append(allowedips, peeraddr)
if extPeer.Address6 != "" {
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)
}
return peers, nil
}
2022-01-26 07:15:27 +08:00
// GetAllowedIPs - calculates the wireguard allowedip field for a peer of a node based on the peer and node settings
func GetAllowedIPs(node, peer *models.Node) []net.IPNet {
var allowedips []net.IPNet
var peeraddr = net.IPNet{
IP: net.ParseIP(peer.Address),
Mask: net.CIDRMask(32, 32),
}
dualstack := false
allowedips = append(allowedips, peeraddr)
// handle manually set peers
2022-01-31 04:18:15 +08:00
for _, allowedIp := range peer.AllowedIPs {
if _, ipnet, err := net.ParseCIDR(allowedIp); err == nil {
nodeEndpointArr := strings.Split(node.Endpoint, ":")
2022-01-31 04:18:15 +08:00
if !ipnet.Contains(net.IP(nodeEndpointArr[0])) && ipnet.IP.String() != peer.Address { // don't need to add an allowed ip that already exists..
allowedips = append(allowedips, *ipnet)
}
2022-01-31 04:18:15 +08:00
} else if appendip := net.ParseIP(allowedIp); appendip != nil && allowedIp != peer.Address {
ipnet := net.IPNet{
IP: net.ParseIP(allowedIp),
Mask: net.CIDRMask(32, 32),
}
allowedips = append(allowedips, ipnet)
}
}
// handle egress gateway peers
2022-01-31 04:18:15 +08:00
if peer.IsEgressGateway == "yes" {
//hasGateway = true
2022-01-31 04:18:15 +08:00
ranges := peer.EgressGatewayRanges
for _, iprange := range ranges { // go through each cidr for egress gateway
_, ipnet, err := net.ParseCIDR(iprange) // confirming it's valid cidr
if err != nil {
ncutils.PrintLog("could not parse gateway IP range. Not adding "+iprange, 1)
continue // if can't parse CIDR
}
2022-01-31 04:18:15 +08:00
nodeEndpointArr := strings.Split(peer.Endpoint, ":") // getting the public ip of node
if ipnet.Contains(net.ParseIP(nodeEndpointArr[0])) { // ensuring egress gateway range does not contain endpoint of node
ncutils.PrintLog("egress IP range of "+iprange+" overlaps with "+node.Endpoint+", omitting", 2)
continue // skip adding egress range if overlaps with node's ip
}
2022-01-31 04:18:15 +08:00
// TODO: Could put in a lot of great logic to avoid conflicts / bad routes
if ipnet.Contains(net.ParseIP(node.LocalAddress)) { // ensuring egress gateway range does not contain public ip of node
ncutils.PrintLog("egress IP range of "+iprange+" overlaps with "+node.LocalAddress+", omitting", 2)
continue // skip adding egress range if overlaps with node's local ip
}
if err != nil {
log.Println("ERROR ENCOUNTERED SETTING GATEWAY")
} else {
allowedips = append(allowedips, *ipnet)
}
}
}
2022-01-31 04:18:15 +08:00
if peer.Address6 != "" && dualstack {
var addr6 = net.IPNet{
2022-01-31 04:18:15 +08:00
IP: net.ParseIP(peer.Address6),
Mask: net.CIDRMask(128, 128),
}
allowedips = append(allowedips, addr6)
}
return allowedips
}