peers.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. package logic
  2. import (
  3. "errors"
  4. "fmt"
  5. "log"
  6. "net"
  7. "net/netip"
  8. "github.com/gravitl/netmaker/database"
  9. "github.com/gravitl/netmaker/logger"
  10. "github.com/gravitl/netmaker/logic/acls/nodeacls"
  11. "github.com/gravitl/netmaker/models"
  12. "github.com/gravitl/netmaker/servercfg"
  13. "golang.org/x/exp/slices"
  14. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  15. )
  16. // GetProxyUpdateForHost - gets the proxy update for host
  17. func GetProxyUpdateForHost(host *models.Host) (models.ProxyManagerPayload, error) {
  18. proxyPayload := models.ProxyManagerPayload{
  19. Action: models.ProxyUpdate,
  20. }
  21. peerConfMap := make(map[string]models.PeerConf)
  22. if host.IsRelayed {
  23. relayHost, err := GetHost(host.RelayedBy)
  24. if err == nil {
  25. relayEndpoint, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", relayHost.EndpointIP, GetPeerListenPort(relayHost)))
  26. if err != nil {
  27. logger.Log(1, "failed to resolve relay node endpoint: ", err.Error())
  28. }
  29. proxyPayload.IsRelayed = true
  30. proxyPayload.RelayedTo = relayEndpoint
  31. } else {
  32. logger.Log(0, "couldn't find relay host for: ", host.ID.String())
  33. }
  34. }
  35. if host.IsRelay {
  36. relayedHosts := GetRelayedHosts(host)
  37. relayPeersMap := make(map[string]models.RelayedConf)
  38. for _, relayedHost := range relayedHosts {
  39. relayedHost := relayedHost
  40. payload, err := GetPeerUpdateForHost("", &relayedHost, nil)
  41. if err == nil {
  42. relayedEndpoint, udpErr := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", relayedHost.EndpointIP, GetPeerListenPort(&relayedHost)))
  43. if udpErr == nil {
  44. relayPeersMap[relayedHost.PublicKey.String()] = models.RelayedConf{
  45. RelayedPeerEndpoint: relayedEndpoint,
  46. RelayedPeerPubKey: relayedHost.PublicKey.String(),
  47. Peers: payload.Peers,
  48. }
  49. }
  50. }
  51. }
  52. proxyPayload.IsRelay = true
  53. proxyPayload.RelayedPeerConf = relayPeersMap
  54. }
  55. var ingressStatus bool
  56. for _, nodeID := range host.Nodes {
  57. node, err := GetNodeByID(nodeID)
  58. if err != nil {
  59. continue
  60. }
  61. currentPeers, err := GetNetworkNodes(node.Network)
  62. if err != nil {
  63. continue
  64. }
  65. for _, peer := range currentPeers {
  66. if peer.ID == node.ID {
  67. //skip yourself
  68. continue
  69. }
  70. peerHost, err := GetHost(peer.HostID.String())
  71. if err != nil {
  72. continue
  73. }
  74. var currPeerConf models.PeerConf
  75. var found bool
  76. if currPeerConf, found = peerConfMap[peerHost.PublicKey.String()]; !found {
  77. currPeerConf = models.PeerConf{
  78. Proxy: peerHost.ProxyEnabled,
  79. PublicListenPort: int32(GetPeerListenPort(peerHost)),
  80. }
  81. }
  82. if peerHost.IsRelayed && peerHost.RelayedBy != host.ID.String() {
  83. relayHost, err := GetHost(peerHost.RelayedBy)
  84. if err == nil {
  85. relayTo, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", relayHost.EndpointIP, GetPeerListenPort(relayHost)))
  86. if err == nil {
  87. currPeerConf.IsRelayed = true
  88. currPeerConf.RelayedTo = relayTo
  89. }
  90. }
  91. }
  92. peerConfMap[peerHost.PublicKey.String()] = currPeerConf
  93. }
  94. if node.IsIngressGateway {
  95. ingressStatus = true
  96. _, peerConfMap, err = getExtPeersForProxy(&node, peerConfMap)
  97. if err == nil {
  98. } else if !database.IsEmptyRecord(err) {
  99. logger.Log(1, "error retrieving external clients:", err.Error())
  100. }
  101. }
  102. }
  103. proxyPayload.IsIngress = ingressStatus
  104. proxyPayload.PeerMap = peerConfMap
  105. return proxyPayload, nil
  106. }
  107. // GetPeerUpdateForHost - gets the consolidated peer update for the host from all networks
  108. func GetPeerUpdateForHost(network string, host *models.Host, deletedNode *models.Node) (models.HostPeerUpdate, error) {
  109. if host == nil {
  110. return models.HostPeerUpdate{}, errors.New("host is nil")
  111. }
  112. // track which nodes are deleted
  113. // after peer calculation, if peer not in list, add delete config of peer
  114. hostPeerUpdate := models.HostPeerUpdate{
  115. Host: *host,
  116. Server: servercfg.GetServer(),
  117. HostPeerIDs: make(models.HostPeerMap, 0),
  118. ServerVersion: servercfg.GetVersion(),
  119. ServerAddrs: []models.ServerAddr{},
  120. IngressInfo: models.IngressInfo{
  121. ExtPeers: make(map[string]models.ExtClientInfo),
  122. },
  123. EgressInfo: make(map[string]models.EgressInfo),
  124. PeerIDs: make(models.PeerMap, 0),
  125. Peers: []wgtypes.PeerConfig{},
  126. NodePeers: []wgtypes.PeerConfig{},
  127. }
  128. var deletedNodes = []models.Node{} // used to track deleted nodes
  129. if deletedNode != nil {
  130. deletedNodes = append(deletedNodes, *deletedNode)
  131. }
  132. logger.Log(1, "peer update for host", host.ID.String())
  133. peerIndexMap := make(map[string]int)
  134. for _, nodeID := range host.Nodes {
  135. nodeID := nodeID
  136. node, err := GetNodeByID(nodeID)
  137. if err != nil {
  138. continue
  139. }
  140. if !node.Connected || node.PendingDelete || node.Action == models.NODE_DELETE {
  141. continue
  142. }
  143. currentPeers, err := GetNetworkNodes(node.Network)
  144. if err != nil {
  145. log.Println("no network nodes")
  146. return models.HostPeerUpdate{}, err
  147. }
  148. var nodePeerMap map[string]models.PeerRouteInfo
  149. if node.IsIngressGateway || node.IsEgressGateway {
  150. nodePeerMap = make(map[string]models.PeerRouteInfo)
  151. }
  152. for _, peer := range currentPeers {
  153. peer := peer
  154. if peer.ID.String() == node.ID.String() {
  155. logger.Log(2, "peer update, skipping self")
  156. //skip yourself
  157. continue
  158. }
  159. if peer.Action == models.NODE_DELETE || peer.PendingDelete {
  160. deletedNodes = append(deletedNodes, peer) // track deleted node for peer update
  161. continue
  162. }
  163. var peerConfig wgtypes.PeerConfig
  164. peerHost, err := GetHost(peer.HostID.String())
  165. if err != nil {
  166. logger.Log(1, "no peer host", peer.HostID.String(), err.Error())
  167. return models.HostPeerUpdate{}, err
  168. }
  169. if !peer.Connected {
  170. logger.Log(2, "peer update, skipping unconnected node", peer.ID.String())
  171. //skip unconnected nodes
  172. continue
  173. }
  174. if !nodeacls.AreNodesAllowed(nodeacls.NetworkID(node.Network), nodeacls.NodeID(node.ID.String()), nodeacls.NodeID(peer.ID.String())) {
  175. logger.Log(2, "peer update, skipping node for acl")
  176. //skip if not permitted by acl
  177. continue
  178. }
  179. peerConfig.PublicKey = peerHost.PublicKey
  180. peerConfig.PersistentKeepaliveInterval = &peer.PersistentKeepalive
  181. peerConfig.ReplaceAllowedIPs = true
  182. uselocal := false
  183. if host.EndpointIP.String() == peerHost.EndpointIP.String() {
  184. //peer is on same network
  185. // set to localaddress
  186. uselocal = true
  187. if node.LocalAddress.IP == nil {
  188. // use public endpint
  189. uselocal = false
  190. }
  191. if node.LocalAddress.String() == peer.LocalAddress.String() {
  192. uselocal = false
  193. }
  194. }
  195. peerConfig.Endpoint = &net.UDPAddr{
  196. IP: peerHost.EndpointIP,
  197. Port: GetPeerListenPort(peerHost),
  198. }
  199. if uselocal {
  200. peerConfig.Endpoint.IP = peer.LocalAddress.IP
  201. }
  202. allowedips := GetAllowedIPs(&node, &peer, nil)
  203. if peer.IsIngressGateway {
  204. for _, entry := range peer.IngressGatewayRange {
  205. _, cidr, err := net.ParseCIDR(string(entry))
  206. if err == nil {
  207. allowedips = append(allowedips, *cidr)
  208. }
  209. }
  210. }
  211. if peer.IsEgressGateway {
  212. allowedips = append(allowedips, getEgressIPs(&node, &peer)...)
  213. }
  214. peerConfig.AllowedIPs = allowedips
  215. if node.IsIngressGateway || node.IsEgressGateway {
  216. if peer.IsIngressGateway {
  217. _, extPeerIDAndAddrs, err := getExtPeers(&peer)
  218. if err == nil {
  219. for _, extPeerIdAndAddr := range extPeerIDAndAddrs {
  220. extPeerIdAndAddr := extPeerIdAndAddr
  221. nodePeerMap[extPeerIdAndAddr.ID] = models.PeerRouteInfo{
  222. PeerAddr: net.IPNet{
  223. IP: net.ParseIP(extPeerIdAndAddr.Address),
  224. Mask: getCIDRMaskFromAddr(extPeerIdAndAddr.Address),
  225. },
  226. PeerKey: extPeerIdAndAddr.ID,
  227. Allow: true,
  228. }
  229. }
  230. }
  231. }
  232. if node.IsIngressGateway && peer.IsEgressGateway {
  233. hostPeerUpdate.IngressInfo.EgressRanges = append(hostPeerUpdate.IngressInfo.EgressRanges,
  234. peer.EgressGatewayRanges...)
  235. }
  236. nodePeerMap[peerHost.PublicKey.String()] = models.PeerRouteInfo{
  237. PeerAddr: net.IPNet{
  238. IP: net.ParseIP(peer.PrimaryAddress()),
  239. Mask: getCIDRMaskFromAddr(peer.PrimaryAddress()),
  240. },
  241. PeerKey: peerHost.PublicKey.String(),
  242. Allow: true,
  243. }
  244. }
  245. var nodePeer wgtypes.PeerConfig
  246. if _, ok := hostPeerUpdate.HostPeerIDs[peerHost.PublicKey.String()]; !ok {
  247. hostPeerUpdate.HostPeerIDs[peerHost.PublicKey.String()] = make(map[string]models.IDandAddr)
  248. hostPeerUpdate.Peers = append(hostPeerUpdate.Peers, peerConfig)
  249. peerIndexMap[peerHost.PublicKey.String()] = len(hostPeerUpdate.Peers) - 1
  250. hostPeerUpdate.HostPeerIDs[peerHost.PublicKey.String()][peer.ID.String()] = models.IDandAddr{
  251. ID: peer.ID.String(),
  252. Address: peer.PrimaryAddress(),
  253. Name: peerHost.Name,
  254. Network: peer.Network,
  255. }
  256. nodePeer = peerConfig
  257. } else {
  258. peerAllowedIPs := hostPeerUpdate.Peers[peerIndexMap[peerHost.PublicKey.String()]].AllowedIPs
  259. peerAllowedIPs = append(peerAllowedIPs, allowedips...)
  260. hostPeerUpdate.Peers[peerIndexMap[peerHost.PublicKey.String()]].AllowedIPs = peerAllowedIPs
  261. hostPeerUpdate.HostPeerIDs[peerHost.PublicKey.String()][peer.ID.String()] = models.IDandAddr{
  262. ID: peer.ID.String(),
  263. Address: peer.PrimaryAddress(),
  264. Name: peerHost.Name,
  265. Network: peer.Network,
  266. }
  267. nodePeer = hostPeerUpdate.Peers[peerIndexMap[peerHost.PublicKey.String()]]
  268. }
  269. if node.Network == network { // add to peers map for metrics
  270. hostPeerUpdate.PeerIDs[peerHost.PublicKey.String()] = models.IDandAddr{
  271. ID: peer.ID.String(),
  272. Address: peer.PrimaryAddress(),
  273. Name: peerHost.Name,
  274. Network: peer.Network,
  275. }
  276. hostPeerUpdate.NodePeers = append(hostPeerUpdate.NodePeers, nodePeer)
  277. }
  278. }
  279. var extPeers []wgtypes.PeerConfig
  280. var extPeerIDAndAddrs []models.IDandAddr
  281. if node.IsIngressGateway {
  282. extPeers, extPeerIDAndAddrs, err = getExtPeers(&node)
  283. if err == nil {
  284. for _, extPeerIdAndAddr := range extPeerIDAndAddrs {
  285. extPeerIdAndAddr := extPeerIdAndAddr
  286. nodePeerMap[extPeerIdAndAddr.ID] = models.PeerRouteInfo{
  287. PeerAddr: net.IPNet{
  288. IP: net.ParseIP(extPeerIdAndAddr.Address),
  289. Mask: getCIDRMaskFromAddr(extPeerIdAndAddr.Address),
  290. },
  291. PeerKey: extPeerIdAndAddr.ID,
  292. Allow: true,
  293. }
  294. }
  295. hostPeerUpdate.Peers = append(hostPeerUpdate.Peers, extPeers...)
  296. for _, extPeerIdAndAddr := range extPeerIDAndAddrs {
  297. extPeerIdAndAddr := extPeerIdAndAddr
  298. hostPeerUpdate.HostPeerIDs[extPeerIdAndAddr.ID] = make(map[string]models.IDandAddr)
  299. hostPeerUpdate.HostPeerIDs[extPeerIdAndAddr.ID][extPeerIdAndAddr.ID] = models.IDandAddr{
  300. ID: extPeerIdAndAddr.ID,
  301. Address: extPeerIdAndAddr.Address,
  302. Name: extPeerIdAndAddr.Name,
  303. Network: node.Network,
  304. }
  305. hostPeerUpdate.IngressInfo.ExtPeers[extPeerIdAndAddr.ID] = models.ExtClientInfo{
  306. Masquerade: true,
  307. IngGwAddr: net.IPNet{
  308. IP: net.ParseIP(node.PrimaryAddress()),
  309. Mask: getCIDRMaskFromAddr(node.PrimaryAddress()),
  310. },
  311. Network: node.PrimaryNetworkRange(),
  312. ExtPeerAddr: net.IPNet{
  313. IP: net.ParseIP(extPeerIdAndAddr.Address),
  314. Mask: getCIDRMaskFromAddr(extPeerIdAndAddr.Address),
  315. },
  316. ExtPeerKey: extPeerIdAndAddr.ID,
  317. Peers: nodePeerMap,
  318. }
  319. if node.Network == network {
  320. hostPeerUpdate.PeerIDs[extPeerIdAndAddr.ID] = extPeerIdAndAddr
  321. hostPeerUpdate.NodePeers = append(hostPeerUpdate.NodePeers, extPeers...)
  322. }
  323. }
  324. } else if !database.IsEmptyRecord(err) {
  325. logger.Log(1, "error retrieving external clients:", err.Error())
  326. }
  327. }
  328. if node.IsEgressGateway {
  329. hostPeerUpdate.EgressInfo[node.ID.String()] = models.EgressInfo{
  330. EgressID: node.ID.String(),
  331. Network: node.PrimaryNetworkRange(),
  332. EgressGwAddr: net.IPNet{
  333. IP: net.ParseIP(node.PrimaryAddress()),
  334. Mask: getCIDRMaskFromAddr(node.PrimaryAddress()),
  335. },
  336. GwPeers: nodePeerMap,
  337. EgressGWCfg: node.EgressGatewayRequest,
  338. }
  339. }
  340. }
  341. // run through delete nodes
  342. if len(deletedNodes) > 0 {
  343. for i := range deletedNodes {
  344. delNode := deletedNodes[i]
  345. delHost, err := GetHost(delNode.HostID.String())
  346. if err != nil {
  347. continue
  348. }
  349. if _, ok := hostPeerUpdate.HostPeerIDs[delHost.PublicKey.String()]; !ok {
  350. var peerConfig = wgtypes.PeerConfig{}
  351. peerConfig.PublicKey = delHost.PublicKey
  352. peerConfig.Endpoint = &net.UDPAddr{
  353. IP: delHost.EndpointIP,
  354. Port: GetPeerListenPort(delHost),
  355. }
  356. peerConfig.Remove = true
  357. peerConfig.AllowedIPs = []net.IPNet{delNode.Address, delNode.Address6}
  358. hostPeerUpdate.Peers = append(hostPeerUpdate.Peers, peerConfig)
  359. }
  360. }
  361. }
  362. return hostPeerUpdate, nil
  363. }
  364. // GetPeerListenPort - given a host, retrieve it's appropriate listening port
  365. func GetPeerListenPort(host *models.Host) int {
  366. peerPort := host.ListenPort
  367. if host.ProxyEnabled {
  368. if host.PublicListenPort != 0 {
  369. peerPort = host.PublicListenPort
  370. } else if host.ProxyListenPort != 0 {
  371. peerPort = host.ProxyListenPort
  372. }
  373. }
  374. return peerPort
  375. }
  376. func getExtPeers(node *models.Node) ([]wgtypes.PeerConfig, []models.IDandAddr, error) {
  377. var peers []wgtypes.PeerConfig
  378. var idsAndAddr []models.IDandAddr
  379. extPeers, err := GetNetworkExtClients(node.Network)
  380. if err != nil {
  381. return peers, idsAndAddr, err
  382. }
  383. host, err := GetHost(node.HostID.String())
  384. if err != nil {
  385. return peers, idsAndAddr, err
  386. }
  387. for _, extPeer := range extPeers {
  388. pubkey, err := wgtypes.ParseKey(extPeer.PublicKey)
  389. if err != nil {
  390. logger.Log(1, "error parsing ext pub key:", err.Error())
  391. continue
  392. }
  393. if host.PublicKey.String() == extPeer.PublicKey ||
  394. extPeer.IngressGatewayID != node.ID.String() || !extPeer.Enabled {
  395. continue
  396. }
  397. var allowedips []net.IPNet
  398. var peer wgtypes.PeerConfig
  399. if extPeer.Address != "" {
  400. var peeraddr = net.IPNet{
  401. IP: net.ParseIP(extPeer.Address),
  402. Mask: net.CIDRMask(32, 32),
  403. }
  404. if peeraddr.IP != nil && peeraddr.Mask != nil {
  405. allowedips = append(allowedips, peeraddr)
  406. }
  407. }
  408. if extPeer.Address6 != "" {
  409. var addr6 = net.IPNet{
  410. IP: net.ParseIP(extPeer.Address6),
  411. Mask: net.CIDRMask(128, 128),
  412. }
  413. if addr6.IP != nil && addr6.Mask != nil {
  414. allowedips = append(allowedips, addr6)
  415. }
  416. }
  417. primaryAddr := extPeer.Address
  418. if primaryAddr == "" {
  419. primaryAddr = extPeer.Address6
  420. }
  421. peer = wgtypes.PeerConfig{
  422. PublicKey: pubkey,
  423. ReplaceAllowedIPs: true,
  424. AllowedIPs: allowedips,
  425. }
  426. peers = append(peers, peer)
  427. idsAndAddr = append(idsAndAddr, models.IDandAddr{
  428. ID: peer.PublicKey.String(),
  429. Name: extPeer.ClientID,
  430. Address: primaryAddr,
  431. })
  432. }
  433. return peers, idsAndAddr, nil
  434. }
  435. func getExtPeersForProxy(node *models.Node, proxyPeerConf map[string]models.PeerConf) ([]wgtypes.PeerConfig, map[string]models.PeerConf, error) {
  436. var peers []wgtypes.PeerConfig
  437. host, err := GetHost(node.HostID.String())
  438. if err != nil {
  439. logger.Log(0, "error retrieving host for node", node.ID.String(), err.Error())
  440. }
  441. extPeers, err := GetNetworkExtClients(node.Network)
  442. if err != nil {
  443. return peers, proxyPeerConf, err
  444. }
  445. for _, extPeer := range extPeers {
  446. pubkey, err := wgtypes.ParseKey(extPeer.PublicKey)
  447. if err != nil {
  448. logger.Log(1, "error parsing ext pub key:", err.Error())
  449. continue
  450. }
  451. if host.PublicKey.String() == extPeer.PublicKey ||
  452. extPeer.IngressGatewayID != node.ID.String() || !extPeer.Enabled {
  453. continue
  454. }
  455. var allowedips []net.IPNet
  456. var peer wgtypes.PeerConfig
  457. if extPeer.Address != "" {
  458. var peeraddr = net.IPNet{
  459. IP: net.ParseIP(extPeer.Address),
  460. Mask: net.CIDRMask(32, 32),
  461. }
  462. if peeraddr.IP != nil && peeraddr.Mask != nil {
  463. allowedips = append(allowedips, peeraddr)
  464. }
  465. }
  466. if extPeer.Address6 != "" {
  467. var addr6 = net.IPNet{
  468. IP: net.ParseIP(extPeer.Address6),
  469. Mask: net.CIDRMask(128, 128),
  470. }
  471. if addr6.IP != nil && addr6.Mask != nil {
  472. allowedips = append(allowedips, addr6)
  473. }
  474. }
  475. peer = wgtypes.PeerConfig{
  476. PublicKey: pubkey,
  477. ReplaceAllowedIPs: true,
  478. AllowedIPs: allowedips,
  479. }
  480. extConf := models.PeerConf{
  481. IsExtClient: true,
  482. Address: net.ParseIP(extPeer.Address),
  483. }
  484. proxyPeerConf[peer.PublicKey.String()] = extConf
  485. peers = append(peers, peer)
  486. }
  487. return peers, proxyPeerConf, nil
  488. }
  489. // GetAllowedIPs - calculates the wireguard allowedip field for a peer of a node based on the peer and node settings
  490. func GetAllowedIPs(node, peer *models.Node, metrics *models.Metrics) []net.IPNet {
  491. var allowedips []net.IPNet
  492. allowedips = getNodeAllowedIPs(peer, node)
  493. // handle ingress gateway peers
  494. if peer.IsIngressGateway {
  495. extPeers, _, err := getExtPeers(peer)
  496. if err != nil {
  497. logger.Log(2, "could not retrieve ext peers for ", peer.ID.String(), err.Error())
  498. }
  499. for _, extPeer := range extPeers {
  500. allowedips = append(allowedips, extPeer.AllowedIPs...)
  501. }
  502. // if node is a failover node, add allowed ips from nodes it is handling
  503. if metrics != nil && peer.Failover && metrics.FailoverPeers != nil {
  504. // traverse through nodes that need handling
  505. logger.Log(3, "peer", peer.ID.String(), "was found to be failover for", node.ID.String(), "checking failover peers...")
  506. for k := range metrics.FailoverPeers {
  507. // if FailoverNode is me for this node, add allowedips
  508. if metrics.FailoverPeers[k] == peer.ID.String() {
  509. // get original node so we can traverse the allowed ips
  510. nodeToFailover, err := GetNodeByID(k)
  511. if err == nil {
  512. failoverNodeMetrics, err := GetMetrics(nodeToFailover.ID.String())
  513. if err == nil && failoverNodeMetrics != nil {
  514. if len(failoverNodeMetrics.NodeName) > 0 {
  515. allowedips = append(allowedips, getNodeAllowedIPs(&nodeToFailover, peer)...)
  516. logger.Log(0, "failing over node", nodeToFailover.ID.String(), nodeToFailover.PrimaryAddress(), "to failover node", peer.ID.String())
  517. }
  518. }
  519. }
  520. }
  521. }
  522. }
  523. }
  524. return allowedips
  525. }
  526. func getEgressIPs(node, peer *models.Node) []net.IPNet {
  527. host, err := GetHost(node.HostID.String())
  528. if err != nil {
  529. logger.Log(0, "error retrieving host for node", node.ID.String(), err.Error())
  530. }
  531. peerHost, err := GetHost(peer.HostID.String())
  532. if err != nil {
  533. logger.Log(0, "error retrieving host for peer", peer.ID.String(), err.Error())
  534. }
  535. //check for internet gateway
  536. internetGateway := false
  537. if slices.Contains(peer.EgressGatewayRanges, "0.0.0.0/0") || slices.Contains(peer.EgressGatewayRanges, "::/0") {
  538. internetGateway = true
  539. }
  540. allowedips := []net.IPNet{}
  541. for _, iprange := range peer.EgressGatewayRanges { // go through each cidr for egress gateway
  542. _, ipnet, err := net.ParseCIDR(iprange) // confirming it's valid cidr
  543. if err != nil {
  544. logger.Log(1, "could not parse gateway IP range. Not adding ", iprange)
  545. continue // if can't parse CIDR
  546. }
  547. // getting the public ip of node
  548. if ipnet.Contains(peerHost.EndpointIP) && !internetGateway { // ensuring egress gateway range does not contain endpoint of node
  549. logger.Log(2, "egress IP range of ", iprange, " overlaps with ", host.EndpointIP.String(), ", omitting")
  550. continue // skip adding egress range if overlaps with node's ip
  551. }
  552. // TODO: Could put in a lot of great logic to avoid conflicts / bad routes
  553. if ipnet.Contains(node.LocalAddress.IP) && !internetGateway { // ensuring egress gateway range does not contain public ip of node
  554. logger.Log(2, "egress IP range of ", iprange, " overlaps with ", node.LocalAddress.String(), ", omitting")
  555. continue // skip adding egress range if overlaps with node's local ip
  556. }
  557. if err != nil {
  558. logger.Log(1, "error encountered when setting egress range", err.Error())
  559. } else {
  560. allowedips = append(allowedips, *ipnet)
  561. }
  562. }
  563. return allowedips
  564. }
  565. func getNodeAllowedIPs(peer, node *models.Node) []net.IPNet {
  566. var allowedips = []net.IPNet{}
  567. if peer.Address.IP != nil {
  568. allowed := net.IPNet{
  569. IP: peer.Address.IP,
  570. Mask: net.CIDRMask(32, 32),
  571. }
  572. allowedips = append(allowedips, allowed)
  573. }
  574. if peer.Address6.IP != nil {
  575. allowed := net.IPNet{
  576. IP: peer.Address6.IP,
  577. Mask: net.CIDRMask(128, 128),
  578. }
  579. allowedips = append(allowedips, allowed)
  580. }
  581. // handle egress gateway peers
  582. if peer.IsEgressGateway {
  583. //hasGateway = true
  584. egressIPs := getEgressIPs(node, peer)
  585. allowedips = append(allowedips, egressIPs...)
  586. }
  587. return allowedips
  588. }
  589. func getCIDRMaskFromAddr(addr string) net.IPMask {
  590. cidr := net.CIDRMask(32, 32)
  591. ipAddr, err := netip.ParseAddr(addr)
  592. if err != nil {
  593. return cidr
  594. }
  595. if ipAddr.Is6() {
  596. cidr = net.CIDRMask(128, 128)
  597. }
  598. return cidr
  599. }