netmaker/logic/peers.go

718 lines
23 KiB
Go
Raw Normal View History

package logic
import (
"context"
2022-06-14 22:36:30 +08:00
"errors"
2022-03-14 23:34:25 +08:00
"fmt"
"net"
2023-02-02 00:05:14 +08:00
"net/netip"
"github.com/gravitl/netmaker/database"
2022-01-31 04:18:15 +08:00
"github.com/gravitl/netmaker/logger"
"github.com/gravitl/netmaker/logic/acls/nodeacls"
"github.com/gravitl/netmaker/models"
"github.com/gravitl/netmaker/servercfg"
"golang.org/x/exp/slices"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
var (
// PeerUpdateCtx context to send to host peer updates
PeerUpdateCtx context.Context
// PeerUpdateStop - the cancel for PeerUpdateCtx
PeerUpdateStop context.CancelFunc
)
2023-01-10 22:22:54 +08:00
// GetProxyUpdateForHost - gets the proxy update for host
2023-03-08 00:00:21 +08:00
func GetProxyUpdateForHost(ctx context.Context, host *models.Host) (models.ProxyManagerPayload, error) {
2023-01-28 03:51:06 +08:00
proxyPayload := models.ProxyManagerPayload{
Action: models.ProxyUpdate,
2023-01-09 11:41:39 +08:00
}
2023-01-28 03:51:06 +08:00
peerConfMap := make(map[string]models.PeerConf)
if host.IsRelayed {
relayHost, err := GetHost(host.RelayedBy)
if err == nil {
2023-02-14 00:09:21 +08:00
relayEndpoint, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", relayHost.EndpointIP, GetPeerListenPort(relayHost)))
if err != nil {
logger.Log(1, "failed to resolve relay node endpoint: ", err.Error())
}
proxyPayload.IsRelayed = true
proxyPayload.RelayedTo = relayEndpoint
} else {
logger.Log(0, "couldn't find relay host for: ", host.ID.String())
}
}
if host.IsRelay {
relayedHosts := GetRelayedHosts(host)
2023-01-28 03:51:06 +08:00
relayPeersMap := make(map[string]models.RelayedConf)
for _, relayedHost := range relayedHosts {
2023-01-26 02:21:18 +08:00
relayedHost := relayedHost
2023-03-14 03:06:07 +08:00
payload, err := GetPeerUpdateForHost(ctx, "", &relayedHost, nil, nil)
if err == nil {
2023-02-14 00:09:21 +08:00
relayedEndpoint, udpErr := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", relayedHost.EndpointIP, GetPeerListenPort(&relayedHost)))
if udpErr == nil {
2023-01-28 03:51:06 +08:00
relayPeersMap[relayedHost.PublicKey.String()] = models.RelayedConf{
RelayedPeerEndpoint: relayedEndpoint,
RelayedPeerPubKey: relayedHost.PublicKey.String(),
2023-02-22 02:28:53 +08:00
Peers: payload.Peers,
}
}
2023-01-08 21:20:02 +08:00
}
}
proxyPayload.IsRelay = true
proxyPayload.RelayedPeerConf = relayPeersMap
2023-01-08 21:20:02 +08:00
}
var ingressStatus bool
2023-01-08 21:20:02 +08:00
for _, nodeID := range host.Nodes {
node, err := GetNodeByID(nodeID)
if err != nil {
continue
}
if !node.Connected || node.PendingDelete || node.Action == models.NODE_DELETE {
continue
}
2023-01-08 21:20:02 +08:00
currentPeers, err := GetNetworkNodes(node.Network)
2023-01-09 10:42:26 +08:00
if err != nil {
2023-01-08 21:20:02 +08:00
continue
}
for _, peer := range currentPeers {
if peer.ID == node.ID {
//skip yourself
continue
}
if !peer.Connected || peer.PendingDelete || peer.Action == models.NODE_DELETE {
continue
}
2023-01-09 10:42:26 +08:00
peerHost, err := GetHost(peer.HostID.String())
2023-01-08 21:20:02 +08:00
if err != nil {
continue
}
2023-01-28 03:51:06 +08:00
var currPeerConf models.PeerConf
2023-01-10 12:48:03 +08:00
var found bool
if currPeerConf, found = peerConfMap[peerHost.PublicKey.String()]; !found {
2023-01-28 03:51:06 +08:00
currPeerConf = models.PeerConf{
2023-01-18 13:44:31 +08:00
Proxy: peerHost.ProxyEnabled,
2023-02-14 00:09:21 +08:00
PublicListenPort: int32(GetPeerListenPort(peerHost)),
2023-03-13 17:13:45 +08:00
ProxyListenPort: GetProxyListenPort(peerHost),
2023-03-22 16:05:51 +08:00
ShouldUseTurn: peerHost.ShouldUseTurn,
TurnRelayAddr: peerHost.TurnRelayAddr,
2023-01-08 21:20:02 +08:00
}
2023-01-09 10:42:26 +08:00
}
2023-01-08 21:20:02 +08:00
2023-01-10 12:48:03 +08:00
if peerHost.IsRelayed && peerHost.RelayedBy != host.ID.String() {
relayHost, err := GetHost(peerHost.RelayedBy)
if err == nil {
2023-02-14 00:09:21 +08:00
relayTo, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", relayHost.EndpointIP, GetPeerListenPort(relayHost)))
2023-01-10 12:48:03 +08:00
if err == nil {
currPeerConf.IsRelayed = true
currPeerConf.RelayedTo = relayTo
2023-01-08 21:20:02 +08:00
}
}
}
2023-01-10 12:48:03 +08:00
peerConfMap[peerHost.PublicKey.String()] = currPeerConf
2023-01-08 21:20:02 +08:00
}
if node.IsIngressGateway {
ingressStatus = true
_, peerConfMap, err = getExtPeersForProxy(&node, peerConfMap)
if err == nil {
} else if !database.IsEmptyRecord(err) {
logger.Log(1, "error retrieving external clients:", err.Error())
}
}
2023-01-08 21:20:02 +08:00
}
proxyPayload.IsIngress = ingressStatus
2023-01-08 21:20:02 +08:00
proxyPayload.PeerMap = peerConfMap
return proxyPayload, nil
}
// ResetPeerUpdateContext - kills any current peer updates and resets the context
func ResetPeerUpdateContext() {
if PeerUpdateCtx != nil && PeerUpdateStop != nil {
PeerUpdateStop() // tell any current peer updates to stop
}
PeerUpdateCtx, PeerUpdateStop = context.WithCancel(context.Background())
}
2023-01-06 20:48:25 +08:00
// GetPeerUpdateForHost - gets the consolidated peer update for the host from all networks
2023-03-14 03:06:07 +08:00
func GetPeerUpdateForHost(ctx context.Context, network string, host *models.Host, deletedNode *models.Node, deletedClient *models.ExtClient) (models.HostPeerUpdate, error) {
if host == nil {
return models.HostPeerUpdate{}, errors.New("host is nil")
}
allNodes, err := GetAllNodes()
if err != nil {
return models.HostPeerUpdate{}, err
}
2023-02-24 03:32:57 +08:00
// track which nodes are deleted
// after peer calculation, if peer not in list, add delete config of peer
2023-01-04 12:34:17 +08:00
hostPeerUpdate := models.HostPeerUpdate{
Host: *host,
2023-01-31 16:48:37 +08:00
Server: servercfg.GetServer(),
2023-02-21 23:31:37 +08:00
HostPeerIDs: make(models.HostPeerMap, 0),
ServerVersion: servercfg.GetVersion(),
ServerAddrs: []models.ServerAddr{},
2023-01-31 15:10:23 +08:00
IngressInfo: models.IngressInfo{
2023-01-31 16:48:37 +08:00
ExtPeers: make(map[string]models.ExtClientInfo),
2023-01-31 15:10:23 +08:00
},
EgressInfo: make(map[string]models.EgressInfo),
PeerIDs: make(models.PeerMap, 0),
Peers: []wgtypes.PeerConfig{},
NodePeers: []wgtypes.PeerConfig{},
HostNetworkInfo: models.HostInfoMap{},
2023-01-04 12:34:17 +08:00
}
2023-02-28 08:12:07 +08:00
logger.Log(1, "peer update for host", host.ID.String())
2023-01-04 12:34:17 +08:00
peerIndexMap := make(map[string]int)
for _, nodeID := range host.Nodes {
2023-02-28 08:12:07 +08:00
nodeID := nodeID
2023-01-04 12:34:17 +08:00
node, err := GetNodeByID(nodeID)
if err != nil {
continue
}
2023-02-24 03:32:57 +08:00
if !node.Connected || node.PendingDelete || node.Action == models.NODE_DELETE {
continue
}
currentPeers := GetNetworkNodesMemory(allNodes, node.Network)
2023-02-02 14:22:20 +08:00
var nodePeerMap map[string]models.PeerRouteInfo
if node.IsIngressGateway || node.IsEgressGateway {
nodePeerMap = make(map[string]models.PeerRouteInfo)
2023-01-31 16:37:22 +08:00
}
2023-01-04 12:34:17 +08:00
for _, peer := range currentPeers {
select {
case <-ctx.Done():
logger.Log(2, "cancelled peer update for host", host.Name, host.ID.String())
return models.HostPeerUpdate{}, fmt.Errorf("peer update cancelled")
default:
peer := peer
if peer.ID.String() == node.ID.String() {
logger.Log(2, "peer update, skipping self")
//skip yourself
continue
2023-01-04 12:34:17 +08:00
}
var peerConfig wgtypes.PeerConfig
peerHost, err := GetHost(peer.HostID.String())
if err != nil {
logger.Log(1, "no peer host", peer.HostID.String(), err.Error())
return models.HostPeerUpdate{}, err
2023-01-04 12:34:17 +08:00
}
2023-01-09 10:42:26 +08:00
peerConfig.PublicKey = peerHost.PublicKey
peerConfig.PersistentKeepaliveInterval = &peer.PersistentKeepalive
peerConfig.ReplaceAllowedIPs = true
uselocal := false
if host.EndpointIP.String() == peerHost.EndpointIP.String() {
// peer is on same network
// set to localaddress
uselocal = true
if node.LocalAddress.IP == nil {
// use public endpint
uselocal = false
}
if node.LocalAddress.String() == peer.LocalAddress.String() {
uselocal = false
2023-01-04 12:34:17 +08:00
}
}
peerConfig.Endpoint = &net.UDPAddr{
IP: peerHost.EndpointIP,
2023-03-28 18:04:27 +08:00
Port: peerHost.ListenPort,
}
if uselocal {
peerConfig.Endpoint.IP = peer.LocalAddress.IP
}
allowedips := GetAllowedIPs(&node, &peer, nil)
if peer.IsIngressGateway {
for _, entry := range peer.IngressGatewayRange {
_, cidr, err := net.ParseCIDR(string(entry))
if err == nil {
allowedips = append(allowedips, *cidr)
}
}
}
if peer.IsEgressGateway {
allowedips = append(allowedips, getEgressIPs(&node, &peer)...)
2023-02-14 00:09:21 +08:00
}
if peer.Action != models.NODE_DELETE &&
!peer.PendingDelete &&
peer.Connected &&
nodeacls.AreNodesAllowed(nodeacls.NetworkID(node.Network), nodeacls.NodeID(node.ID.String()), nodeacls.NodeID(peer.ID.String())) &&
(deletedNode == nil || (deletedNode != nil && peer.ID.String() != deletedNode.ID.String())) {
peerConfig.AllowedIPs = allowedips // only append allowed IPs if valid connection
2023-02-01 14:28:11 +08:00
}
if node.IsIngressGateway || node.IsEgressGateway {
if peer.IsIngressGateway {
_, extPeerIDAndAddrs, err := getExtPeers(&peer)
if err == nil {
for _, extPeerIdAndAddr := range extPeerIDAndAddrs {
extPeerIdAndAddr := extPeerIdAndAddr
nodePeerMap[extPeerIdAndAddr.ID] = models.PeerRouteInfo{
PeerAddr: net.IPNet{
IP: net.ParseIP(extPeerIdAndAddr.Address),
Mask: getCIDRMaskFromAddr(extPeerIdAndAddr.Address),
},
PeerKey: extPeerIdAndAddr.ID,
Allow: true,
2023-03-14 03:06:07 +08:00
ID: extPeerIdAndAddr.ID,
}
}
}
}
if node.IsIngressGateway && peer.IsEgressGateway {
hostPeerUpdate.IngressInfo.EgressRanges = append(hostPeerUpdate.IngressInfo.EgressRanges,
peer.EgressGatewayRanges...)
}
nodePeerMap[peerHost.PublicKey.String()] = models.PeerRouteInfo{
2023-02-10 01:58:50 +08:00
PeerAddr: net.IPNet{
IP: net.ParseIP(peer.PrimaryAddress()),
Mask: getCIDRMaskFromAddr(peer.PrimaryAddress()),
2023-02-10 01:58:50 +08:00
},
PeerKey: peerHost.PublicKey.String(),
2023-02-10 01:58:50 +08:00
Allow: true,
2023-03-14 03:06:07 +08:00
ID: peer.ID.String(),
2023-02-10 01:58:50 +08:00
}
}
peerProxyPort := GetProxyListenPort(peerHost)
var nodePeer wgtypes.PeerConfig
if _, ok := hostPeerUpdate.HostPeerIDs[peerHost.PublicKey.String()]; !ok {
hostPeerUpdate.HostPeerIDs[peerHost.PublicKey.String()] = make(map[string]models.IDandAddr)
hostPeerUpdate.Peers = append(hostPeerUpdate.Peers, peerConfig)
peerIndexMap[peerHost.PublicKey.String()] = len(hostPeerUpdate.Peers) - 1
hostPeerUpdate.HostPeerIDs[peerHost.PublicKey.String()][peer.ID.String()] = models.IDandAddr{
2023-03-13 20:56:09 +08:00
ID: peer.ID.String(),
Address: peer.PrimaryAddress(),
Name: peerHost.Name,
Network: peer.Network,
ProxyListenPort: peerProxyPort,
}
hostPeerUpdate.HostNetworkInfo[peerHost.PublicKey.String()] = models.HostNetworkInfo{
Interfaces: peerHost.Interfaces,
ProxyListenPort: peerProxyPort,
}
nodePeer = peerConfig
} else {
peerAllowedIPs := hostPeerUpdate.Peers[peerIndexMap[peerHost.PublicKey.String()]].AllowedIPs
peerAllowedIPs = append(peerAllowedIPs, allowedips...)
hostPeerUpdate.Peers[peerIndexMap[peerHost.PublicKey.String()]].AllowedIPs = peerAllowedIPs
hostPeerUpdate.HostPeerIDs[peerHost.PublicKey.String()][peer.ID.String()] = models.IDandAddr{
2023-03-13 20:56:09 +08:00
ID: peer.ID.String(),
Address: peer.PrimaryAddress(),
Name: peerHost.Name,
Network: peer.Network,
ProxyListenPort: GetProxyListenPort(peerHost),
2023-01-31 17:33:15 +08:00
}
hostPeerUpdate.HostNetworkInfo[peerHost.PublicKey.String()] = models.HostNetworkInfo{
Interfaces: peerHost.Interfaces,
ProxyListenPort: peerProxyPort,
}
nodePeer = hostPeerUpdate.Peers[peerIndexMap[peerHost.PublicKey.String()]]
}
if node.Network == network { // add to peers map for metrics
hostPeerUpdate.PeerIDs[peerHost.PublicKey.String()] = models.IDandAddr{
ID: peer.ID.String(),
Address: peer.PrimaryAddress(),
Name: peerHost.Name,
Network: peer.Network,
ProxyListenPort: peerHost.ProxyListenPort,
2023-02-22 00:15:06 +08:00
}
hostPeerUpdate.NodePeers = append(hostPeerUpdate.NodePeers, nodePeer)
}
}
var extPeers []wgtypes.PeerConfig
var extPeerIDAndAddrs []models.IDandAddr
if node.IsIngressGateway {
extPeers, extPeerIDAndAddrs, err = getExtPeers(&node)
if err == nil {
for _, extPeerIdAndAddr := range extPeerIDAndAddrs {
extPeerIdAndAddr := extPeerIdAndAddr
nodePeerMap[extPeerIdAndAddr.ID] = models.PeerRouteInfo{
PeerAddr: net.IPNet{
IP: net.ParseIP(extPeerIdAndAddr.Address),
Mask: getCIDRMaskFromAddr(extPeerIdAndAddr.Address),
},
PeerKey: extPeerIdAndAddr.ID,
Allow: true,
2023-03-14 03:06:07 +08:00
ID: extPeerIdAndAddr.ID,
}
}
hostPeerUpdate.Peers = append(hostPeerUpdate.Peers, extPeers...)
for _, extPeerIdAndAddr := range extPeerIDAndAddrs {
extPeerIdAndAddr := extPeerIdAndAddr
hostPeerUpdate.HostPeerIDs[extPeerIdAndAddr.ID] = make(map[string]models.IDandAddr)
hostPeerUpdate.HostPeerIDs[extPeerIdAndAddr.ID][extPeerIdAndAddr.ID] = models.IDandAddr{
ID: extPeerIdAndAddr.ID,
Address: extPeerIdAndAddr.Address,
Name: extPeerIdAndAddr.Name,
Network: node.Network,
}
2023-03-14 03:06:07 +08:00
hostPeerUpdate.IngressInfo.ExtPeers[extPeerIdAndAddr.ID] = models.ExtClientInfo{
Masquerade: true,
IngGwAddr: net.IPNet{
IP: net.ParseIP(node.PrimaryAddress()),
Mask: getCIDRMaskFromAddr(node.PrimaryAddress()),
},
Network: node.PrimaryNetworkRange(),
ExtPeerAddr: net.IPNet{
IP: net.ParseIP(extPeerIdAndAddr.Address),
Mask: getCIDRMaskFromAddr(extPeerIdAndAddr.Address),
},
ExtPeerKey: extPeerIdAndAddr.ID,
2023-03-14 03:06:07 +08:00
Peers: filterNodeMapForClientACLs(extPeerIdAndAddr.ID, node.Network, nodePeerMap),
}
if node.Network == network {
hostPeerUpdate.PeerIDs[extPeerIdAndAddr.ID] = extPeerIdAndAddr
hostPeerUpdate.NodePeers = append(hostPeerUpdate.NodePeers, extPeers...)
}
}
} else if !database.IsEmptyRecord(err) {
logger.Log(1, "error retrieving external clients:", err.Error())
}
}
if node.IsEgressGateway {
hostPeerUpdate.EgressInfo[node.ID.String()] = models.EgressInfo{
EgressID: node.ID.String(),
Network: node.PrimaryNetworkRange(),
EgressGwAddr: net.IPNet{
IP: net.ParseIP(node.PrimaryAddress()),
Mask: getCIDRMaskFromAddr(node.PrimaryAddress()),
},
GwPeers: nodePeerMap,
EgressGWCfg: node.EgressGatewayRequest,
}
2023-02-02 14:22:20 +08:00
}
}
2023-01-04 12:34:17 +08:00
}
// == post peer calculations ==
// indicate removal if no allowed IPs were calculated
for i := range hostPeerUpdate.Peers {
peer := hostPeerUpdate.Peers[i]
if len(peer.AllowedIPs) == 0 {
peer.Remove = true
}
hostPeerUpdate.Peers[i] = peer
}
2023-01-04 12:34:17 +08:00
for i := range hostPeerUpdate.NodePeers {
peer := hostPeerUpdate.NodePeers[i]
if len(peer.AllowedIPs) == 0 {
peer.Remove = true
2023-02-24 03:32:57 +08:00
}
hostPeerUpdate.NodePeers[i] = peer
2023-02-24 03:32:57 +08:00
}
2023-03-14 03:06:07 +08:00
if deletedClient != nil {
key, err := wgtypes.ParseKey(deletedClient.PublicKey)
if err == nil {
hostPeerUpdate.Peers = append(hostPeerUpdate.Peers, wgtypes.PeerConfig{
PublicKey: key,
Remove: true,
})
}
}
2023-01-04 12:34:17 +08:00
return hostPeerUpdate, nil
}
// GetPeerListenPort - given a host, retrieve it's appropriate listening port
2023-02-14 00:09:21 +08:00
func GetPeerListenPort(host *models.Host) int {
2023-01-18 13:44:31 +08:00
peerPort := host.ListenPort
if host.ProxyEnabled {
2023-01-18 14:30:26 +08:00
if host.PublicListenPort != 0 {
peerPort = host.PublicListenPort
2023-01-18 13:44:31 +08:00
} else if host.ProxyListenPort != 0 {
peerPort = host.ProxyListenPort
}
}
return peerPort
}
// GetProxyListenPort - fetches the proxy listen port
func GetProxyListenPort(host *models.Host) int {
proxyPort := host.ProxyListenPort
if host.PublicListenPort != 0 {
proxyPort = host.PublicListenPort
}
return proxyPort
}
2023-01-25 19:35:45 +08:00
func getExtPeers(node *models.Node) ([]wgtypes.PeerConfig, []models.IDandAddr, error) {
2022-01-31 04:18:15 +08:00
var peers []wgtypes.PeerConfig
2022-09-14 03:25:56 +08:00
var idsAndAddr []models.IDandAddr
2022-11-09 11:16:16 +08:00
extPeers, err := GetNetworkExtClients(node.Network)
2022-01-31 04:18:15 +08:00
if err != nil {
2022-09-14 03:25:56 +08:00
return peers, idsAndAddr, err
2022-01-31 04:18:15 +08:00
}
host, err := GetHost(node.HostID.String())
if err != nil {
return peers, idsAndAddr, err
}
2022-01-31 04:18:15 +08:00
for _, extPeer := range extPeers {
2023-03-14 03:06:07 +08:00
extPeer := extPeer
2022-01-31 04:18:15 +08:00
pubkey, err := wgtypes.ParseKey(extPeer.PublicKey)
if err != nil {
logger.Log(1, "error parsing ext pub key:", err.Error())
continue
}
if host.PublicKey.String() == extPeer.PublicKey ||
extPeer.IngressGatewayID != node.ID.String() || !extPeer.Enabled {
2022-01-31 04:18:15 +08:00
continue
}
2022-04-23 01:04:34 +08:00
var allowedips []net.IPNet
2022-01-31 04:18:15 +08:00
var peer wgtypes.PeerConfig
2023-01-25 19:35:45 +08:00
if extPeer.Address != "" {
2022-04-23 01:04:34 +08:00
var peeraddr = net.IPNet{
IP: net.ParseIP(extPeer.Address),
Mask: net.CIDRMask(32, 32),
}
if peeraddr.IP != nil && peeraddr.Mask != nil {
allowedips = append(allowedips, peeraddr)
}
2022-01-31 04:18:15 +08:00
}
2023-01-25 19:35:45 +08:00
if extPeer.Address6 != "" {
2022-01-31 04:18:15 +08:00
var addr6 = net.IPNet{
IP: net.ParseIP(extPeer.Address6),
Mask: net.CIDRMask(128, 128),
}
2022-04-23 01:04:34 +08:00
if addr6.IP != nil && addr6.Mask != nil {
allowedips = append(allowedips, addr6)
}
2022-01-31 04:18:15 +08:00
}
2022-09-14 03:25:56 +08:00
primaryAddr := extPeer.Address
if primaryAddr == "" {
primaryAddr = extPeer.Address6
}
2022-01-31 04:18:15 +08:00
peer = wgtypes.PeerConfig{
PublicKey: pubkey,
ReplaceAllowedIPs: true,
AllowedIPs: allowedips,
}
peers = append(peers, peer)
2022-09-14 03:25:56 +08:00
idsAndAddr = append(idsAndAddr, models.IDandAddr{
ID: peer.PublicKey.String(),
Name: extPeer.ClientID,
2022-09-14 03:25:56 +08:00
Address: primaryAddr,
})
2022-01-31 04:18:15 +08:00
}
2022-09-14 03:25:56 +08:00
return peers, idsAndAddr, nil
2022-01-31 04:18:15 +08:00
}
2023-01-28 03:51:06 +08:00
func getExtPeersForProxy(node *models.Node, proxyPeerConf map[string]models.PeerConf) ([]wgtypes.PeerConfig, map[string]models.PeerConf, error) {
2022-11-09 11:16:16 +08:00
var peers []wgtypes.PeerConfig
host, err := GetHost(node.HostID.String())
if err != nil {
logger.Log(0, "error retrieving host for node", node.ID.String(), err.Error())
}
2022-11-09 11:16:16 +08:00
extPeers, err := GetNetworkExtClients(node.Network)
if err != nil {
return peers, proxyPeerConf, 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 host.PublicKey.String() == extPeer.PublicKey ||
extPeer.IngressGatewayID != node.ID.String() || !extPeer.Enabled {
2022-11-09 11:16:16 +08:00
continue
}
var allowedips []net.IPNet
var peer wgtypes.PeerConfig
if extPeer.Address != "" {
var peeraddr = net.IPNet{
IP: net.ParseIP(extPeer.Address),
Mask: net.CIDRMask(32, 32),
}
if peeraddr.IP != nil && peeraddr.Mask != nil {
allowedips = append(allowedips, peeraddr)
}
}
if extPeer.Address6 != "" {
var addr6 = net.IPNet{
IP: net.ParseIP(extPeer.Address6),
Mask: net.CIDRMask(128, 128),
}
if addr6.IP != nil && addr6.Mask != nil {
allowedips = append(allowedips, addr6)
}
}
peer = wgtypes.PeerConfig{
PublicKey: pubkey,
ReplaceAllowedIPs: true,
AllowedIPs: allowedips,
}
2023-01-28 03:51:06 +08:00
extConf := models.PeerConf{
2023-01-25 19:35:45 +08:00
IsExtClient: true,
Address: net.ParseIP(extPeer.Address),
2022-11-09 11:16:16 +08:00
}
proxyPeerConf[peer.PublicKey.String()] = extConf
peers = append(peers, peer)
}
return peers, proxyPeerConf, 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, metrics *models.Metrics) []net.IPNet {
var allowedips []net.IPNet
allowedips = getNodeAllowedIPs(peer, node)
2022-06-14 22:36:30 +08:00
// handle ingress gateway peers
if peer.IsIngressGateway {
2023-01-25 19:35:45 +08:00
extPeers, _, err := getExtPeers(peer)
2022-11-15 21:07:58 +08:00
if err != nil {
logger.Log(2, "could not retrieve ext peers for ", peer.ID.String(), err.Error())
2022-11-15 21:07:58 +08:00
}
for _, extPeer := range extPeers {
allowedips = append(allowedips, extPeer.AllowedIPs...)
}
// if node is a failover node, add allowed ips from nodes it is handling
if metrics != nil && peer.Failover && metrics.FailoverPeers != nil {
2022-11-15 21:07:58 +08:00
// traverse through nodes that need handling
logger.Log(3, "peer", peer.ID.String(), "was found to be failover for", node.ID.String(), "checking failover peers...")
2022-11-15 21:07:58 +08:00
for k := range metrics.FailoverPeers {
// if FailoverNode is me for this node, add allowedips
if metrics.FailoverPeers[k] == peer.ID.String() {
2022-11-15 21:07:58 +08:00
// get original node so we can traverse the allowed ips
nodeToFailover, err := GetNodeByID(k)
if err == nil {
failoverNodeMetrics, err := GetMetrics(nodeToFailover.ID.String())
2022-11-15 21:07:58 +08:00
if err == nil && failoverNodeMetrics != nil {
if len(failoverNodeMetrics.NodeName) > 0 {
allowedips = append(allowedips, getNodeAllowedIPs(&nodeToFailover, peer)...)
logger.Log(0, "failing over node", nodeToFailover.ID.String(), nodeToFailover.PrimaryAddress(), "to failover node", peer.ID.String())
2022-11-15 21:07:58 +08:00
}
}
}
}
}
}
}
return allowedips
}
func getEgressIPs(node, peer *models.Node) []net.IPNet {
host, err := GetHost(node.HostID.String())
if err != nil {
logger.Log(0, "error retrieving host for node", node.ID.String(), err.Error())
}
peerHost, err := GetHost(peer.HostID.String())
2022-12-22 19:42:33 +08:00
if err != nil {
logger.Log(0, "error retrieving host for peer", peer.ID.String(), err.Error())
}
//check for internet gateway
internetGateway := false
if slices.Contains(peer.EgressGatewayRanges, "0.0.0.0/0") || slices.Contains(peer.EgressGatewayRanges, "::/0") {
internetGateway = true
}
allowedips := []net.IPNet{}
for _, iprange := range peer.EgressGatewayRanges { // go through each cidr for egress gateway
_, ipnet, err := net.ParseCIDR(iprange) // confirming it's valid cidr
if err != nil {
logger.Log(1, "could not parse gateway IP range. Not adding ", iprange)
continue // if can't parse CIDR
}
2023-02-02 14:22:20 +08:00
// getting the public ip of node
if ipnet.Contains(peerHost.EndpointIP) && !internetGateway { // ensuring egress gateway range does not contain endpoint of node
2022-12-22 19:42:33 +08:00
logger.Log(2, "egress IP range of ", iprange, " overlaps with ", host.EndpointIP.String(), ", omitting")
continue // skip adding egress range if overlaps with node's ip
}
// TODO: Could put in a lot of great logic to avoid conflicts / bad routes
2023-02-02 14:22:20 +08:00
if ipnet.Contains(node.LocalAddress.IP) && !internetGateway { // ensuring egress gateway range does not contain public ip of node
2022-12-24 03:07:16 +08:00
logger.Log(2, "egress IP range of ", iprange, " overlaps with ", node.LocalAddress.String(), ", omitting")
continue // skip adding egress range if overlaps with node's local ip
}
if err != nil {
logger.Log(1, "error encountered when setting egress range", err.Error())
} else {
allowedips = append(allowedips, *ipnet)
}
}
return allowedips
}
func getNodeAllowedIPs(peer, node *models.Node) []net.IPNet {
var allowedips = []net.IPNet{}
if peer.Address.IP != nil {
2022-12-27 19:15:29 +08:00
allowed := net.IPNet{
IP: peer.Address.IP,
Mask: net.CIDRMask(32, 32),
}
allowedips = append(allowedips, allowed)
}
if peer.Address6.IP != nil {
2022-12-27 19:15:29 +08:00
allowed := net.IPNet{
IP: peer.Address6.IP,
Mask: net.CIDRMask(128, 128),
}
allowedips = append(allowedips, allowed)
}
// handle egress gateway peers
if peer.IsEgressGateway {
//hasGateway = true
egressIPs := getEgressIPs(node, peer)
allowedips = append(allowedips, egressIPs...)
}
return allowedips
}
2023-02-02 00:05:14 +08:00
func getCIDRMaskFromAddr(addr string) net.IPMask {
cidr := net.CIDRMask(32, 32)
ipAddr, err := netip.ParseAddr(addr)
if err != nil {
return cidr
}
if ipAddr.Is6() {
cidr = net.CIDRMask(128, 128)
}
return cidr
}
2023-03-14 03:06:07 +08:00
// accounts for ext client ACLs
func filterNodeMapForClientACLs(publicKey, network string, nodePeerMap map[string]models.PeerRouteInfo) map[string]models.PeerRouteInfo {
if !isEE {
return nodePeerMap
}
if nodePeerMap == nil {
return map[string]models.PeerRouteInfo{}
}
if len(publicKey) == 0 || len(network) == 0 {
return nodePeerMap
}
client, err := GetExtClientByPubKey(publicKey, network)
if err != nil {
return nodePeerMap
}
for k := range nodePeerMap {
currNodePeer := nodePeerMap[k]
if _, ok := client.ACLs[currNodePeer.ID]; ok {
delete(nodePeerMap, k)
}
}
return nodePeerMap
}