peers.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. package logic
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "net/netip"
  7. "github.com/gravitl/netmaker/database"
  8. "github.com/gravitl/netmaker/logger"
  9. "github.com/gravitl/netmaker/logic/acls/nodeacls"
  10. "github.com/gravitl/netmaker/models"
  11. "github.com/gravitl/netmaker/servercfg"
  12. "golang.org/x/exp/slices"
  13. "golang.org/x/exp/slog"
  14. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  15. )
  16. var (
  17. // ResetFailOver - function to reset failOvered peers on this node
  18. ResetFailOver = func(failOverNode *models.Node) error {
  19. return nil
  20. }
  21. // ResetFailedOverPeer - removes failed over node from network peers
  22. ResetFailedOverPeer = func(failedOverNode *models.Node) error {
  23. return nil
  24. }
  25. // GetFailOverPeerIps - gets failover peerips
  26. GetFailOverPeerIps = func(peer, node *models.Node) []net.IPNet {
  27. return []net.IPNet{}
  28. }
  29. // CreateFailOver - creates failover in a network
  30. CreateFailOver = func(node models.Node) error {
  31. return nil
  32. }
  33. // SetDefaulGw
  34. SetDefaultGw = func(node models.Node, peerUpdate models.HostPeerUpdate) models.HostPeerUpdate {
  35. return peerUpdate
  36. }
  37. SetDefaultGwForRelayedUpdate = func(relayed, relay models.Node, peerUpdate models.HostPeerUpdate) models.HostPeerUpdate {
  38. return peerUpdate
  39. }
  40. // UnsetInternetGw
  41. UnsetInternetGw = func(node *models.Node) {
  42. node.IsInternetGateway = false
  43. }
  44. // SetInternetGw
  45. SetInternetGw = func(node *models.Node, req models.InetNodeReq) {
  46. node.IsInternetGateway = true
  47. }
  48. // GetAllowedIpForInetNodeClient
  49. GetAllowedIpForInetNodeClient = func(node, peer *models.Node) []net.IPNet {
  50. return []net.IPNet{}
  51. }
  52. )
  53. // GetPeerUpdateForHost - gets the consolidated peer update for the host from all networks
  54. func GetPeerUpdateForHost(network string, host *models.Host, allNodes []models.Node,
  55. deletedNode *models.Node, deletedClients []models.ExtClient) (models.HostPeerUpdate, error) {
  56. if host == nil {
  57. return models.HostPeerUpdate{}, errors.New("host is nil")
  58. }
  59. // track which nodes are deleted
  60. // after peer calculation, if peer not in list, add delete config of peer
  61. hostPeerUpdate := models.HostPeerUpdate{
  62. Host: *host,
  63. Server: servercfg.GetServer(),
  64. ServerVersion: servercfg.GetVersion(),
  65. ServerAddrs: []models.ServerAddr{},
  66. FwUpdate: models.FwUpdate{
  67. EgressInfo: make(map[string]models.EgressInfo),
  68. },
  69. PeerIDs: make(models.PeerMap, 0),
  70. Peers: []wgtypes.PeerConfig{},
  71. NodePeers: []wgtypes.PeerConfig{},
  72. HostNetworkInfo: models.HostInfoMap{},
  73. }
  74. slog.Debug("peer update for host", "hostId", host.ID.String())
  75. peerIndexMap := make(map[string]int)
  76. for _, nodeID := range host.Nodes {
  77. nodeID := nodeID
  78. node, err := GetNodeByID(nodeID)
  79. if err != nil {
  80. continue
  81. }
  82. if !node.Connected || node.PendingDelete || node.Action == models.NODE_DELETE {
  83. continue
  84. }
  85. if host.OS == models.OS_Types.IoT {
  86. hostPeerUpdate.NodeAddrs = append(hostPeerUpdate.NodeAddrs, node.PrimaryAddressIPNet())
  87. if node.IsRelayed {
  88. relayNode, err := GetNodeByID(node.RelayedBy)
  89. if err != nil {
  90. continue
  91. }
  92. relayHost, err := GetHost(relayNode.HostID.String())
  93. if err != nil {
  94. continue
  95. }
  96. relayPeer := wgtypes.PeerConfig{
  97. PublicKey: relayHost.PublicKey,
  98. PersistentKeepaliveInterval: &relayHost.PersistentKeepalive,
  99. ReplaceAllowedIPs: true,
  100. AllowedIPs: GetAllowedIPs(&node, &relayNode, nil),
  101. }
  102. uselocal := false
  103. if host.EndpointIP.String() == relayHost.EndpointIP.String() {
  104. // peer is on same network
  105. // set to localaddress
  106. uselocal = true
  107. if node.LocalAddress.IP == nil {
  108. // use public endpint
  109. uselocal = false
  110. }
  111. if node.LocalAddress.String() == relayNode.LocalAddress.String() {
  112. uselocal = false
  113. }
  114. }
  115. relayPeer.Endpoint = &net.UDPAddr{
  116. IP: relayHost.EndpointIP,
  117. Port: GetPeerListenPort(relayHost),
  118. }
  119. if uselocal {
  120. relayPeer.Endpoint.IP = relayNode.LocalAddress.IP
  121. relayPeer.Endpoint.Port = relayHost.ListenPort
  122. }
  123. hostPeerUpdate.Peers = append(hostPeerUpdate.Peers, relayPeer)
  124. } else if deletedNode != nil && deletedNode.IsRelay {
  125. relayHost, err := GetHost(deletedNode.HostID.String())
  126. if err != nil {
  127. continue
  128. }
  129. relayPeer := wgtypes.PeerConfig{
  130. PublicKey: relayHost.PublicKey,
  131. Remove: true,
  132. }
  133. hostPeerUpdate.Peers = append(hostPeerUpdate.Peers, relayPeer)
  134. }
  135. continue
  136. }
  137. hostPeerUpdate = SetDefaultGw(node, hostPeerUpdate)
  138. if !hostPeerUpdate.IsInternetGw {
  139. hostPeerUpdate.IsInternetGw = IsInternetGw(node)
  140. }
  141. currentPeers := GetNetworkNodesMemory(allNodes, node.Network)
  142. for _, peer := range currentPeers {
  143. peer := peer
  144. if peer.ID.String() == node.ID.String() {
  145. logger.Log(2, "peer update, skipping self")
  146. // skip yourself
  147. continue
  148. }
  149. peerHost, err := GetHost(peer.HostID.String())
  150. if err != nil {
  151. logger.Log(1, "no peer host", peer.HostID.String(), err.Error())
  152. continue
  153. }
  154. peerConfig := wgtypes.PeerConfig{
  155. PublicKey: peerHost.PublicKey,
  156. PersistentKeepaliveInterval: &peerHost.PersistentKeepalive,
  157. ReplaceAllowedIPs: true,
  158. }
  159. if peer.IsEgressGateway {
  160. hostPeerUpdate.EgressRoutes = append(hostPeerUpdate.EgressRoutes, models.EgressNetworkRoutes{
  161. NodeAddr: node.PrimaryAddressIPNet(),
  162. EgressRanges: peer.EgressGatewayRanges,
  163. })
  164. }
  165. if peer.IsIngressGateway {
  166. hostPeerUpdate.EgressRoutes = append(hostPeerUpdate.EgressRoutes, getExtpeersExtraRoutes(peer.Network)...)
  167. }
  168. _, isFailOverPeer := node.FailOverPeers[peer.ID.String()]
  169. if servercfg.IsPro {
  170. if (node.IsRelayed && node.RelayedBy != peer.ID.String()) ||
  171. (peer.IsRelayed && peer.RelayedBy != node.ID.String()) || isFailOverPeer {
  172. // if node is relayed and peer is not the relay, set remove to true
  173. if _, ok := peerIndexMap[peerHost.PublicKey.String()]; ok {
  174. continue
  175. }
  176. peerConfig.Remove = true
  177. hostPeerUpdate.Peers = append(hostPeerUpdate.Peers, peerConfig)
  178. peerIndexMap[peerHost.PublicKey.String()] = len(hostPeerUpdate.Peers) - 1
  179. continue
  180. }
  181. if node.IsRelayed && node.RelayedBy == peer.ID.String() {
  182. hostPeerUpdate = SetDefaultGwForRelayedUpdate(node, peer, hostPeerUpdate)
  183. }
  184. }
  185. uselocal := false
  186. if host.EndpointIP.String() == peerHost.EndpointIP.String() {
  187. // peer is on same network
  188. // set to localaddress
  189. uselocal = true
  190. if node.LocalAddress.IP == nil {
  191. // use public endpint
  192. uselocal = false
  193. }
  194. if node.LocalAddress.String() == peer.LocalAddress.String() {
  195. uselocal = false
  196. }
  197. }
  198. peerConfig.Endpoint = &net.UDPAddr{
  199. IP: peerHost.EndpointIP,
  200. Port: GetPeerListenPort(peerHost),
  201. }
  202. if uselocal {
  203. peerConfig.Endpoint.IP = peer.LocalAddress.IP
  204. peerConfig.Endpoint.Port = peerHost.ListenPort
  205. }
  206. allowedips := GetAllowedIPs(&node, &peer, nil)
  207. if peer.Action != models.NODE_DELETE &&
  208. !peer.PendingDelete &&
  209. peer.Connected &&
  210. nodeacls.AreNodesAllowed(nodeacls.NetworkID(node.Network), nodeacls.NodeID(node.ID.String()), nodeacls.NodeID(peer.ID.String())) &&
  211. (deletedNode == nil || (deletedNode != nil && peer.ID.String() != deletedNode.ID.String())) {
  212. peerConfig.AllowedIPs = allowedips // only append allowed IPs if valid connection
  213. }
  214. var nodePeer wgtypes.PeerConfig
  215. if _, ok := peerIndexMap[peerHost.PublicKey.String()]; !ok {
  216. hostPeerUpdate.Peers = append(hostPeerUpdate.Peers, peerConfig)
  217. peerIndexMap[peerHost.PublicKey.String()] = len(hostPeerUpdate.Peers) - 1
  218. hostPeerUpdate.HostNetworkInfo[peerHost.PublicKey.String()] = models.HostNetworkInfo{
  219. Interfaces: peerHost.Interfaces,
  220. ListenPort: peerHost.ListenPort,
  221. IsStatic: peerHost.IsStatic,
  222. }
  223. nodePeer = peerConfig
  224. } else {
  225. peerAllowedIPs := hostPeerUpdate.Peers[peerIndexMap[peerHost.PublicKey.String()]].AllowedIPs
  226. peerAllowedIPs = append(peerAllowedIPs, peerConfig.AllowedIPs...)
  227. hostPeerUpdate.Peers[peerIndexMap[peerHost.PublicKey.String()]].AllowedIPs = peerAllowedIPs
  228. hostPeerUpdate.Peers[peerIndexMap[peerHost.PublicKey.String()]].Remove = false
  229. hostPeerUpdate.HostNetworkInfo[peerHost.PublicKey.String()] = models.HostNetworkInfo{
  230. Interfaces: peerHost.Interfaces,
  231. ListenPort: peerHost.ListenPort,
  232. IsStatic: peerHost.IsStatic,
  233. }
  234. nodePeer = hostPeerUpdate.Peers[peerIndexMap[peerHost.PublicKey.String()]]
  235. }
  236. if node.Network == network && !peerConfig.Remove && len(peerConfig.AllowedIPs) > 0 { // add to peers map for metrics
  237. hostPeerUpdate.PeerIDs[peerHost.PublicKey.String()] = models.IDandAddr{
  238. ID: peer.ID.String(),
  239. HostID: peerHost.ID.String(),
  240. Address: peer.PrimaryAddress(),
  241. Name: peerHost.Name,
  242. Network: peer.Network,
  243. ListenPort: peerHost.ListenPort,
  244. }
  245. hostPeerUpdate.NodePeers = append(hostPeerUpdate.NodePeers, nodePeer)
  246. }
  247. }
  248. var extPeers []wgtypes.PeerConfig
  249. var extPeerIDAndAddrs []models.IDandAddr
  250. var egressRoutes []models.EgressNetworkRoutes
  251. if node.IsIngressGateway {
  252. extPeers, extPeerIDAndAddrs, egressRoutes, err = getExtPeers(&node, &node)
  253. if err == nil {
  254. hostPeerUpdate.EgressRoutes = append(hostPeerUpdate.EgressRoutes, egressRoutes...)
  255. hostPeerUpdate.Peers = append(hostPeerUpdate.Peers, extPeers...)
  256. for _, extPeerIdAndAddr := range extPeerIDAndAddrs {
  257. extPeerIdAndAddr := extPeerIdAndAddr
  258. if node.Network == network {
  259. hostPeerUpdate.PeerIDs[extPeerIdAndAddr.ID] = extPeerIdAndAddr
  260. hostPeerUpdate.NodePeers = append(hostPeerUpdate.NodePeers, extPeers...)
  261. }
  262. }
  263. } else if !database.IsEmptyRecord(err) {
  264. logger.Log(1, "error retrieving external clients:", err.Error())
  265. }
  266. }
  267. if node.IsEgressGateway && node.EgressGatewayRequest.NatEnabled == "yes" && len(node.EgressGatewayRequest.Ranges) > 0 {
  268. hostPeerUpdate.FwUpdate.IsEgressGw = true
  269. hostPeerUpdate.FwUpdate.EgressInfo[node.ID.String()] = models.EgressInfo{
  270. EgressID: node.ID.String(),
  271. Network: node.PrimaryNetworkRange(),
  272. EgressGwAddr: net.IPNet{
  273. IP: net.ParseIP(node.PrimaryAddress()),
  274. Mask: getCIDRMaskFromAddr(node.PrimaryAddress()),
  275. },
  276. EgressGWCfg: node.EgressGatewayRequest,
  277. }
  278. }
  279. if IsInternetGw(node) {
  280. hostPeerUpdate.FwUpdate.IsEgressGw = true
  281. egressrange := []string{"0.0.0.0/0"}
  282. if node.Address6.IP != nil {
  283. egressrange = append(egressrange, "::/0")
  284. }
  285. hostPeerUpdate.FwUpdate.EgressInfo[fmt.Sprintf("%s-%s", node.ID.String(), "inet")] = models.EgressInfo{
  286. EgressID: fmt.Sprintf("%s-%s", node.ID.String(), "inet"),
  287. Network: node.PrimaryAddressIPNet(),
  288. EgressGwAddr: net.IPNet{
  289. IP: net.ParseIP(node.PrimaryAddress()),
  290. Mask: getCIDRMaskFromAddr(node.PrimaryAddress()),
  291. },
  292. EgressGWCfg: models.EgressGatewayRequest{
  293. NodeID: fmt.Sprintf("%s-%s", node.ID.String(), "inet"),
  294. NetID: node.Network,
  295. NatEnabled: "yes",
  296. Ranges: egressrange,
  297. },
  298. }
  299. }
  300. }
  301. // == post peer calculations ==
  302. // indicate removal if no allowed IPs were calculated
  303. for i := range hostPeerUpdate.Peers {
  304. peer := hostPeerUpdate.Peers[i]
  305. if len(peer.AllowedIPs) == 0 {
  306. peer.Remove = true
  307. }
  308. hostPeerUpdate.Peers[i] = peer
  309. }
  310. if deletedNode != nil && host.OS != models.OS_Types.IoT {
  311. peerHost, err := GetHost(deletedNode.HostID.String())
  312. if err == nil && host.ID != peerHost.ID {
  313. if _, ok := peerIndexMap[peerHost.PublicKey.String()]; !ok {
  314. hostPeerUpdate.Peers = append(hostPeerUpdate.Peers, wgtypes.PeerConfig{
  315. PublicKey: peerHost.PublicKey,
  316. Remove: true,
  317. })
  318. }
  319. }
  320. }
  321. for i := range hostPeerUpdate.NodePeers {
  322. peer := hostPeerUpdate.NodePeers[i]
  323. if len(peer.AllowedIPs) == 0 {
  324. peer.Remove = true
  325. }
  326. hostPeerUpdate.NodePeers[i] = peer
  327. }
  328. if len(deletedClients) > 0 {
  329. for i := range deletedClients {
  330. deletedClient := deletedClients[i]
  331. key, err := wgtypes.ParseKey(deletedClient.PublicKey)
  332. if err == nil {
  333. hostPeerUpdate.Peers = append(hostPeerUpdate.Peers, wgtypes.PeerConfig{
  334. PublicKey: key,
  335. Remove: true,
  336. })
  337. }
  338. }
  339. }
  340. return hostPeerUpdate, nil
  341. }
  342. // GetPeerListenPort - given a host, retrieve it's appropriate listening port
  343. func GetPeerListenPort(host *models.Host) int {
  344. peerPort := host.ListenPort
  345. if host.WgPublicListenPort != 0 {
  346. peerPort = host.WgPublicListenPort
  347. }
  348. return peerPort
  349. }
  350. // GetAllowedIPs - calculates the wireguard allowedip field for a peer of a node based on the peer and node settings
  351. func GetAllowedIPs(node, peer *models.Node, metrics *models.Metrics) []net.IPNet {
  352. var allowedips []net.IPNet
  353. if peer.IsInternetGateway && node.InternetGwID == peer.ID.String() {
  354. allowedips = append(allowedips, GetAllowedIpForInetNodeClient(node, peer)...)
  355. return allowedips
  356. }
  357. if node.IsRelayed && node.RelayedBy == peer.ID.String() {
  358. allowedips = append(allowedips, GetAllowedIpsForRelayed(node, peer)...)
  359. if peer.InternetGwID != "" {
  360. return allowedips
  361. }
  362. }
  363. allowedips = append(allowedips, getNodeAllowedIPs(peer, node)...)
  364. // handle ingress gateway peers
  365. if peer.IsIngressGateway {
  366. extPeers, _, _, err := getExtPeers(peer, node)
  367. if err != nil {
  368. logger.Log(2, "could not retrieve ext peers for ", peer.ID.String(), err.Error())
  369. }
  370. for _, extPeer := range extPeers {
  371. allowedips = append(allowedips, extPeer.AllowedIPs...)
  372. }
  373. }
  374. return allowedips
  375. }
  376. func GetEgressIPs(peer *models.Node) []net.IPNet {
  377. peerHost, err := GetHost(peer.HostID.String())
  378. if err != nil {
  379. logger.Log(0, "error retrieving host for peer", peer.ID.String(), err.Error())
  380. }
  381. // check for internet gateway
  382. internetGateway := false
  383. if slices.Contains(peer.EgressGatewayRanges, "0.0.0.0/0") || slices.Contains(peer.EgressGatewayRanges, "::/0") {
  384. internetGateway = true
  385. }
  386. allowedips := []net.IPNet{}
  387. for _, iprange := range peer.EgressGatewayRanges { // go through each cidr for egress gateway
  388. _, ipnet, err := net.ParseCIDR(iprange) // confirming it's valid cidr
  389. if err != nil {
  390. logger.Log(1, "could not parse gateway IP range. Not adding ", iprange)
  391. continue // if can't parse CIDR
  392. }
  393. // getting the public ip of node
  394. if ipnet.Contains(peerHost.EndpointIP) && !internetGateway { // ensuring egress gateway range does not contain endpoint of node
  395. logger.Log(2, "egress IP range of ", iprange, " overlaps with ", peerHost.EndpointIP.String(), ", omitting")
  396. continue // skip adding egress range if overlaps with node's ip
  397. }
  398. // TODO: Could put in a lot of great logic to avoid conflicts / bad routes
  399. if ipnet.Contains(peer.LocalAddress.IP) && !internetGateway { // ensuring egress gateway range does not contain public ip of node
  400. logger.Log(2, "egress IP range of ", iprange, " overlaps with ", peer.LocalAddress.String(), ", omitting")
  401. continue // skip adding egress range if overlaps with node's local ip
  402. }
  403. if err != nil {
  404. logger.Log(1, "error encountered when setting egress range", err.Error())
  405. } else {
  406. allowedips = append(allowedips, *ipnet)
  407. }
  408. }
  409. return allowedips
  410. }
  411. func getNodeAllowedIPs(peer, node *models.Node) []net.IPNet {
  412. var allowedips = []net.IPNet{}
  413. if peer.Address.IP != nil {
  414. allowed := net.IPNet{
  415. IP: peer.Address.IP,
  416. Mask: net.CIDRMask(32, 32),
  417. }
  418. allowedips = append(allowedips, allowed)
  419. }
  420. if peer.Address6.IP != nil {
  421. allowed := net.IPNet{
  422. IP: peer.Address6.IP,
  423. Mask: net.CIDRMask(128, 128),
  424. }
  425. allowedips = append(allowedips, allowed)
  426. }
  427. // handle egress gateway peers
  428. if peer.IsEgressGateway {
  429. // hasGateway = true
  430. egressIPs := GetEgressIPs(peer)
  431. allowedips = append(allowedips, egressIPs...)
  432. }
  433. if peer.IsRelay {
  434. allowedips = append(allowedips, RelayedAllowedIPs(peer, node)...)
  435. }
  436. if peer.IsFailOver {
  437. allowedips = append(allowedips, GetFailOverPeerIps(peer, node)...)
  438. }
  439. return allowedips
  440. }
  441. func getCIDRMaskFromAddr(addr string) net.IPMask {
  442. cidr := net.CIDRMask(32, 32)
  443. ipAddr, err := netip.ParseAddr(addr)
  444. if err != nil {
  445. return cidr
  446. }
  447. if ipAddr.Is6() {
  448. cidr = net.CIDRMask(128, 128)
  449. }
  450. return cidr
  451. }