peers.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. package logic
  2. import (
  3. "errors"
  4. "fmt"
  5. "log"
  6. "net"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/c-robinson/iplib"
  11. "github.com/gravitl/netmaker/database"
  12. "github.com/gravitl/netmaker/logger"
  13. "github.com/gravitl/netmaker/logic/acls/nodeacls"
  14. "github.com/gravitl/netmaker/models"
  15. "github.com/gravitl/netmaker/servercfg"
  16. "golang.org/x/exp/slices"
  17. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  18. )
  19. func GetPeersForProxy(node *models.Node) ([]wgtypes.PeerConfig, error) {
  20. var peers []wgtypes.PeerConfig
  21. var err error
  22. currentPeers, err := GetNetworkNodes(node.Network)
  23. if err != nil {
  24. return peers, err
  25. }
  26. for _, peer := range currentPeers {
  27. if peer.ID == node.ID {
  28. //skip yourself
  29. continue
  30. }
  31. log.Printf("----------> PEER: %s, Endpoint: %s, LocalPort: %d", peer.ID, peer.Endpoint, peer.LocalListenPort)
  32. pubkey, err := wgtypes.ParseKey(peer.PublicKey)
  33. if err != nil {
  34. logger.Log(1, "failed to parse node pub key: ", peer.ID)
  35. continue
  36. }
  37. endpoint, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", peer.Endpoint, peer.LocalListenPort))
  38. if err != nil {
  39. logger.Log(1, "failed to resolve udp addr for node: ", peer.ID, peer.Endpoint, err.Error())
  40. continue
  41. }
  42. allowedips := getNodeAllowedIPs(node, &peer)
  43. var keepalive time.Duration
  44. if node.PersistentKeepalive != 0 {
  45. // set_keepalive
  46. keepalive, _ = time.ParseDuration(strconv.FormatInt(int64(node.PersistentKeepalive), 10) + "s")
  47. }
  48. log.Printf("---------->##### PEER: %s, Endpoint: %s, LocalPort: %d", peer.ID, endpoint, peer.LocalListenPort)
  49. peers = append(peers, wgtypes.PeerConfig{
  50. PublicKey: pubkey,
  51. Endpoint: endpoint,
  52. AllowedIPs: allowedips,
  53. PersistentKeepaliveInterval: &keepalive,
  54. ReplaceAllowedIPs: true,
  55. })
  56. }
  57. return peers, nil
  58. }
  59. // GetPeerUpdate - gets a wireguard peer config for each peer of a node
  60. func GetPeerUpdate(node *models.Node) (models.PeerUpdate, error) {
  61. var peerUpdate models.PeerUpdate
  62. var peers []wgtypes.PeerConfig
  63. var serverNodeAddresses = []models.ServerAddr{}
  64. var isP2S bool
  65. network, err := GetNetwork(node.Network)
  66. if err != nil {
  67. return peerUpdate, err
  68. } else if network.IsPointToSite == "yes" && node.IsHub != "yes" {
  69. isP2S = true
  70. }
  71. var peerMap = make(models.PeerMap)
  72. var metrics *models.Metrics
  73. if servercfg.Is_EE {
  74. metrics, _ = GetMetrics(node.ID)
  75. }
  76. if metrics == nil {
  77. metrics = &models.Metrics{}
  78. }
  79. if metrics.FailoverPeers == nil {
  80. metrics.FailoverPeers = make(map[string]string)
  81. }
  82. // udppeers = the peers parsed from the local interface
  83. // gives us correct port to reach
  84. udppeers, errN := database.GetPeers(node.Network)
  85. if errN != nil {
  86. logger.Log(2, errN.Error())
  87. }
  88. currentPeers, err := GetNetworkNodes(node.Network)
  89. if err != nil {
  90. return models.PeerUpdate{}, err
  91. }
  92. // if node.IsRelayed == "yes" {
  93. // return GetPeerUpdateForRelayedNode(node, udppeers)
  94. // }
  95. // #1 Set Keepalive values: set_keepalive
  96. // #2 Set local address: set_local - could be a LOT BETTER and fix some bugs with additional logic
  97. // #3 Set allowedips: set_allowedips
  98. for _, peer := range currentPeers {
  99. if peer.ID == node.ID {
  100. //skip yourself
  101. continue
  102. }
  103. // on point to site networks -- get peers regularily if you are the hub --- otherwise the only peer is the hub
  104. if node.NetworkSettings.IsPointToSite == "yes" && node.IsHub == "no" && peer.IsHub == "no" {
  105. continue
  106. }
  107. if node.Connected != "yes" {
  108. //skip unconnected nodes
  109. continue
  110. }
  111. // if the node is not a server, set the endpoint
  112. var setEndpoint = !(node.IsServer == "yes")
  113. // if peer.IsRelayed == "yes" {
  114. // if !(node.IsRelay == "yes" && ncutils.StringSliceContains(node.RelayAddrs, peer.PrimaryAddress())) {
  115. // //skip -- will be added to relay
  116. // continue
  117. // } else if node.IsRelay == "yes" && ncutils.StringSliceContains(node.RelayAddrs, peer.PrimaryAddress()) {
  118. // // dont set peer endpoint if it's relayed by node
  119. // setEndpoint = false
  120. // }
  121. // }
  122. if !nodeacls.AreNodesAllowed(nodeacls.NetworkID(node.Network), nodeacls.NodeID(node.ID), nodeacls.NodeID(peer.ID)) {
  123. //skip if not permitted by acl
  124. continue
  125. }
  126. if isP2S && peer.IsHub != "yes" {
  127. continue
  128. }
  129. if len(metrics.FailoverPeers[peer.ID]) > 0 && IsFailoverPresent(node.Network) {
  130. logger.Log(2, "peer", peer.Name, peer.PrimaryAddress(), "was found to be in failover peers list for node", node.Name, node.PrimaryAddress())
  131. continue
  132. }
  133. pubkey, err := wgtypes.ParseKey(peer.PublicKey)
  134. if err != nil {
  135. return models.PeerUpdate{}, err
  136. }
  137. if node.Endpoint == peer.Endpoint {
  138. //peer is on same network
  139. // set_local
  140. if node.LocalAddress != peer.LocalAddress && peer.LocalAddress != "" {
  141. peer.Endpoint = peer.LocalAddress
  142. if peer.LocalListenPort != 0 {
  143. peer.ListenPort = peer.LocalListenPort
  144. }
  145. } else {
  146. continue
  147. }
  148. }
  149. // set address if setEndpoint is true
  150. // otherwise, will get inserted as empty value
  151. var address *net.UDPAddr
  152. // Sets ListenPort to UDP Hole Punching Port assuming:
  153. // - UDP Hole Punching is enabled
  154. // - udppeers retrieval did not return an error
  155. // - the endpoint is valid
  156. if setEndpoint {
  157. var setUDPPort = false
  158. if peer.UDPHolePunch == "yes" && errN == nil && CheckEndpoint(udppeers[peer.PublicKey]) {
  159. endpointstring := udppeers[peer.PublicKey]
  160. endpointarr := strings.Split(endpointstring, ":")
  161. if len(endpointarr) == 2 {
  162. port, err := strconv.Atoi(endpointarr[1])
  163. if err == nil {
  164. setUDPPort = true
  165. peer.ListenPort = int32(port)
  166. }
  167. }
  168. }
  169. // if udp hole punching is on, but udp hole punching did not set it, use the LocalListenPort instead
  170. // or, if port is for some reason zero use the LocalListenPort
  171. // but only do this if LocalListenPort is not zero
  172. if ((peer.UDPHolePunch == "yes" && !setUDPPort) || peer.ListenPort == 0) && peer.LocalListenPort != 0 {
  173. peer.ListenPort = peer.LocalListenPort
  174. }
  175. endpoint := peer.Endpoint + ":" + strconv.FormatInt(int64(peer.ListenPort), 10)
  176. address, err = net.ResolveUDPAddr("udp", endpoint)
  177. if err != nil {
  178. return models.PeerUpdate{}, err
  179. }
  180. }
  181. allowedips := GetAllowedIPs(node, &peer, metrics)
  182. var keepalive time.Duration
  183. if node.PersistentKeepalive != 0 {
  184. // set_keepalive
  185. keepalive, _ = time.ParseDuration(strconv.FormatInt(int64(node.PersistentKeepalive), 10) + "s")
  186. }
  187. var peerData = wgtypes.PeerConfig{
  188. PublicKey: pubkey,
  189. Endpoint: address,
  190. ReplaceAllowedIPs: true,
  191. AllowedIPs: allowedips,
  192. PersistentKeepaliveInterval: &keepalive,
  193. }
  194. peers = append(peers, peerData)
  195. peerMap[peer.PublicKey] = models.IDandAddr{
  196. Name: peer.Name,
  197. ID: peer.ID,
  198. Address: peer.PrimaryAddress(),
  199. IsServer: peer.IsServer,
  200. }
  201. if peer.IsServer == "yes" {
  202. serverNodeAddresses = append(serverNodeAddresses, models.ServerAddr{IsLeader: IsLeader(&peer), Address: peer.Address})
  203. }
  204. }
  205. if node.IsIngressGateway == "yes" {
  206. extPeers, idsAndAddr, err := getExtPeers(node)
  207. if err == nil {
  208. peers = append(peers, extPeers...)
  209. for i := range idsAndAddr {
  210. peerMap[idsAndAddr[i].ID] = idsAndAddr[i]
  211. }
  212. } else if !database.IsEmptyRecord(err) {
  213. logger.Log(1, "error retrieving external clients:", err.Error())
  214. }
  215. }
  216. peerUpdate.Network = node.Network
  217. peerUpdate.ServerVersion = servercfg.Version
  218. peerUpdate.Peers = peers
  219. peerUpdate.ServerAddrs = serverNodeAddresses
  220. peerUpdate.DNS = getPeerDNS(node.Network)
  221. peerUpdate.PeerIDs = peerMap
  222. if node.IsRelayed == "yes" {
  223. relayNode := FindRelay(node)
  224. relayEndpoint, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", relayNode.Endpoint, relayNode.LocalListenPort))
  225. if err != nil {
  226. logger.Log(1, "failed to resolve relay node endpoint: ", err.Error())
  227. }
  228. peerUpdate.IsRelayed = true
  229. peerUpdate.RelayTo = relayEndpoint
  230. }
  231. return peerUpdate, nil
  232. }
  233. func getExtPeers(node *models.Node) ([]wgtypes.PeerConfig, []models.IDandAddr, error) {
  234. var peers []wgtypes.PeerConfig
  235. var idsAndAddr []models.IDandAddr
  236. extPeers, err := GetExtPeersList(node)
  237. if err != nil {
  238. return peers, idsAndAddr, err
  239. }
  240. for _, extPeer := range extPeers {
  241. pubkey, err := wgtypes.ParseKey(extPeer.PublicKey)
  242. if err != nil {
  243. logger.Log(1, "error parsing ext pub key:", err.Error())
  244. continue
  245. }
  246. if node.PublicKey == extPeer.PublicKey {
  247. continue
  248. }
  249. var allowedips []net.IPNet
  250. var peer wgtypes.PeerConfig
  251. if extPeer.Address != "" {
  252. var peeraddr = net.IPNet{
  253. IP: net.ParseIP(extPeer.Address),
  254. Mask: net.CIDRMask(32, 32),
  255. }
  256. if peeraddr.IP != nil && peeraddr.Mask != nil {
  257. allowedips = append(allowedips, peeraddr)
  258. }
  259. }
  260. if extPeer.Address6 != "" {
  261. var addr6 = net.IPNet{
  262. IP: net.ParseIP(extPeer.Address6),
  263. Mask: net.CIDRMask(128, 128),
  264. }
  265. if addr6.IP != nil && addr6.Mask != nil {
  266. allowedips = append(allowedips, addr6)
  267. }
  268. }
  269. primaryAddr := extPeer.Address
  270. if primaryAddr == "" {
  271. primaryAddr = extPeer.Address6
  272. }
  273. peer = wgtypes.PeerConfig{
  274. PublicKey: pubkey,
  275. ReplaceAllowedIPs: true,
  276. AllowedIPs: allowedips,
  277. }
  278. peers = append(peers, peer)
  279. idsAndAddr = append(idsAndAddr, models.IDandAddr{
  280. ID: peer.PublicKey.String(),
  281. Address: primaryAddr,
  282. })
  283. }
  284. return peers, idsAndAddr, nil
  285. }
  286. // GetAllowedIPs - calculates the wireguard allowedip field for a peer of a node based on the peer and node settings
  287. func GetAllowedIPs(node, peer *models.Node, metrics *models.Metrics) []net.IPNet {
  288. var allowedips []net.IPNet
  289. allowedips = getNodeAllowedIPs(peer, node)
  290. // handle ingress gateway peers
  291. if peer.IsIngressGateway == "yes" {
  292. extPeers, _, err := getExtPeers(peer)
  293. if err != nil {
  294. logger.Log(2, "could not retrieve ext peers for ", peer.Name, err.Error())
  295. }
  296. for _, extPeer := range extPeers {
  297. allowedips = append(allowedips, extPeer.AllowedIPs...)
  298. }
  299. // if node is a failover node, add allowed ips from nodes it is handling
  300. if peer.Failover == "yes" && metrics.FailoverPeers != nil {
  301. // traverse through nodes that need handling
  302. logger.Log(3, "peer", peer.Name, "was found to be failover for", node.Name, "checking failover peers...")
  303. for k := range metrics.FailoverPeers {
  304. // if FailoverNode is me for this node, add allowedips
  305. if metrics.FailoverPeers[k] == peer.ID {
  306. // get original node so we can traverse the allowed ips
  307. nodeToFailover, err := GetNodeByID(k)
  308. if err == nil {
  309. failoverNodeMetrics, err := GetMetrics(nodeToFailover.ID)
  310. if err == nil && failoverNodeMetrics != nil {
  311. if len(failoverNodeMetrics.NodeName) > 0 {
  312. allowedips = append(allowedips, getNodeAllowedIPs(&nodeToFailover, peer)...)
  313. logger.Log(0, "failing over node", nodeToFailover.Name, nodeToFailover.PrimaryAddress(), "to failover node", peer.Name)
  314. }
  315. }
  316. }
  317. }
  318. }
  319. }
  320. }
  321. // handle relay gateway peers
  322. // if peer.IsRelay == "yes" {
  323. // for _, ip := range peer.RelayAddrs {
  324. // //find node ID of relayed peer
  325. // relayedPeer, err := findNode(ip)
  326. // if err != nil {
  327. // logger.Log(0, "failed to find node for ip ", ip, err.Error())
  328. // continue
  329. // }
  330. // if relayedPeer == nil {
  331. // continue
  332. // }
  333. // if relayedPeer.ID == node.ID {
  334. // //skip self
  335. // continue
  336. // }
  337. // //check if acl permits comms
  338. // if !nodeacls.AreNodesAllowed(nodeacls.NetworkID(node.Network), nodeacls.NodeID(node.ID), nodeacls.NodeID(relayedPeer.ID)) {
  339. // continue
  340. // }
  341. // if iplib.Version(net.ParseIP(ip)) == 4 {
  342. // relayAddr := net.IPNet{
  343. // IP: net.ParseIP(ip),
  344. // Mask: net.CIDRMask(32, 32),
  345. // }
  346. // allowedips = append(allowedips, relayAddr)
  347. // }
  348. // if iplib.Version(net.ParseIP(ip)) == 6 {
  349. // relayAddr := net.IPNet{
  350. // IP: net.ParseIP(ip),
  351. // Mask: net.CIDRMask(128, 128),
  352. // }
  353. // allowedips = append(allowedips, relayAddr)
  354. // }
  355. // relayedNode, err := findNode(ip)
  356. // if err != nil {
  357. // logger.Log(1, "unable to find node for relayed address", ip, err.Error())
  358. // continue
  359. // }
  360. // if relayedNode.IsEgressGateway == "yes" {
  361. // extAllowedIPs := getEgressIPs(node, relayedNode)
  362. // allowedips = append(allowedips, extAllowedIPs...)
  363. // }
  364. // if relayedNode.IsIngressGateway == "yes" {
  365. // extPeers, _, err := getExtPeers(relayedNode)
  366. // if err == nil {
  367. // for _, extPeer := range extPeers {
  368. // allowedips = append(allowedips, extPeer.AllowedIPs...)
  369. // }
  370. // } else {
  371. // logger.Log(0, "failed to retrieve extclients from relayed ingress", err.Error())
  372. // }
  373. // }
  374. // }
  375. // }
  376. return allowedips
  377. }
  378. func getPeerDNS(network string) string {
  379. var dns string
  380. if nodes, err := GetNetworkNodes(network); err == nil {
  381. for i := range nodes {
  382. dns = dns + fmt.Sprintf("%s %s.%s\n", nodes[i].Address, nodes[i].Name, nodes[i].Network)
  383. }
  384. }
  385. if customDNSEntries, err := GetCustomDNS(network); err == nil {
  386. for _, entry := range customDNSEntries {
  387. // TODO - filter entries based on ACLs / given peers vs nodes in network
  388. dns = dns + fmt.Sprintf("%s %s.%s\n", entry.Address, entry.Name, entry.Network)
  389. }
  390. }
  391. return dns
  392. }
  393. // GetPeerUpdateForRelayedNode - calculates peer update for a relayed node by getting the relay
  394. // copying the relay node's allowed ips and making appropriate substitutions
  395. func GetPeerUpdateForRelayedNode(node *models.Node, udppeers map[string]string) (models.PeerUpdate, error) {
  396. var peerUpdate models.PeerUpdate
  397. var peers []wgtypes.PeerConfig
  398. var serverNodeAddresses = []models.ServerAddr{}
  399. var allowedips []net.IPNet
  400. //find node that is relaying us
  401. relay := FindRelay(node)
  402. if relay == nil {
  403. return models.PeerUpdate{}, errors.New("not found")
  404. }
  405. //add relay to lists of allowed ip
  406. if relay.Address != "" {
  407. relayIP := net.IPNet{
  408. IP: net.ParseIP(relay.Address),
  409. Mask: net.CIDRMask(32, 32),
  410. }
  411. allowedips = append(allowedips, relayIP)
  412. }
  413. if relay.Address6 != "" {
  414. relayIP6 := net.IPNet{
  415. IP: net.ParseIP(relay.Address6),
  416. Mask: net.CIDRMask(128, 128),
  417. }
  418. allowedips = append(allowedips, relayIP6)
  419. }
  420. //get PeerUpdate for relayed node
  421. relayPeerUpdate, err := GetPeerUpdate(relay)
  422. if err != nil {
  423. return models.PeerUpdate{}, err
  424. }
  425. //add the relays allowed ips from all of the relay's peers
  426. for _, peer := range relayPeerUpdate.Peers {
  427. allowedips = append(allowedips, peer.AllowedIPs...)
  428. }
  429. //delete any ips not permitted by acl
  430. for i := len(allowedips) - 1; i >= 0; i-- {
  431. target, err := findNode(allowedips[i].IP.String())
  432. if err != nil {
  433. logger.Log(0, "failed to find node for ip", allowedips[i].IP.String(), err.Error())
  434. continue
  435. }
  436. if target == nil {
  437. logger.Log(0, "failed to find node for ip", allowedips[i].IP.String())
  438. continue
  439. }
  440. if !nodeacls.AreNodesAllowed(nodeacls.NetworkID(node.Network), nodeacls.NodeID(node.ID), nodeacls.NodeID(target.ID)) {
  441. logger.Log(0, "deleting node from relayednode per acl", node.Name, target.Name)
  442. allowedips = append(allowedips[:i], allowedips[i+1:]...)
  443. }
  444. }
  445. //delete self from allowed ips
  446. for i := len(allowedips) - 1; i >= 0; i-- {
  447. if allowedips[i].IP.String() == node.Address || allowedips[i].IP.String() == node.Address6 {
  448. allowedips = append(allowedips[:i], allowedips[i+1:]...)
  449. }
  450. }
  451. //delete egressrange from allowedip if we are egress gateway
  452. if node.IsEgressGateway == "yes" {
  453. for i := len(allowedips) - 1; i >= 0; i-- {
  454. if StringSliceContains(node.EgressGatewayRanges, allowedips[i].String()) {
  455. allowedips = append(allowedips[:i], allowedips[i+1:]...)
  456. }
  457. }
  458. }
  459. //delete extclients from allowedip if we are ingress gateway
  460. if node.IsIngressGateway == "yes" {
  461. for i := len(allowedips) - 1; i >= 0; i-- {
  462. if strings.Contains(node.IngressGatewayRange, allowedips[i].IP.String()) {
  463. allowedips = append(allowedips[:i], allowedips[i+1:]...)
  464. }
  465. }
  466. }
  467. //add egress range if relay is egress
  468. if relay.IsEgressGateway == "yes" {
  469. var ip *net.IPNet
  470. for _, cidr := range relay.EgressGatewayRanges {
  471. _, ip, err = net.ParseCIDR(cidr)
  472. if err != nil {
  473. continue
  474. }
  475. }
  476. allowedips = append(allowedips, *ip)
  477. }
  478. pubkey, err := wgtypes.ParseKey(relay.PublicKey)
  479. if err != nil {
  480. return models.PeerUpdate{}, err
  481. }
  482. var setUDPPort = false
  483. if relay.UDPHolePunch == "yes" && CheckEndpoint(udppeers[relay.PublicKey]) {
  484. endpointstring := udppeers[relay.PublicKey]
  485. endpointarr := strings.Split(endpointstring, ":")
  486. if len(endpointarr) == 2 {
  487. port, err := strconv.Atoi(endpointarr[1])
  488. if err == nil {
  489. setUDPPort = true
  490. relay.ListenPort = int32(port)
  491. }
  492. }
  493. }
  494. // if udp hole punching is on, but udp hole punching did not set it, use the LocalListenPort instead
  495. // or, if port is for some reason zero use the LocalListenPort
  496. // but only do this if LocalListenPort is not zero
  497. if ((relay.UDPHolePunch == "yes" && !setUDPPort) || relay.ListenPort == 0) && relay.LocalListenPort != 0 {
  498. relay.ListenPort = relay.LocalListenPort
  499. }
  500. endpoint := relay.Endpoint + ":" + strconv.FormatInt(int64(relay.ListenPort), 10)
  501. address, err := net.ResolveUDPAddr("udp", endpoint)
  502. if err != nil {
  503. return models.PeerUpdate{}, err
  504. }
  505. var keepalive time.Duration
  506. if node.PersistentKeepalive != 0 {
  507. // set_keepalive
  508. keepalive, _ = time.ParseDuration(strconv.FormatInt(int64(node.PersistentKeepalive), 10) + "s")
  509. }
  510. var peerData = wgtypes.PeerConfig{
  511. PublicKey: pubkey,
  512. Endpoint: address,
  513. ReplaceAllowedIPs: true,
  514. AllowedIPs: allowedips,
  515. PersistentKeepaliveInterval: &keepalive,
  516. }
  517. peers = append(peers, peerData)
  518. if relay.IsServer == "yes" {
  519. serverNodeAddresses = append(serverNodeAddresses, models.ServerAddr{IsLeader: IsLeader(relay), Address: relay.Address})
  520. }
  521. //if ingress add extclients
  522. if node.IsIngressGateway == "yes" {
  523. extPeers, _, err := getExtPeers(node)
  524. if err == nil {
  525. peers = append(peers, extPeers...)
  526. } else {
  527. logger.Log(2, "could not retrieve ext peers for ", node.Name, err.Error())
  528. }
  529. }
  530. peerUpdate.Network = node.Network
  531. peerUpdate.ServerVersion = servercfg.Version
  532. peerUpdate.Peers = peers
  533. peerUpdate.ServerAddrs = serverNodeAddresses
  534. peerUpdate.DNS = getPeerDNS(node.Network)
  535. return peerUpdate, nil
  536. }
  537. func getEgressIPs(node, peer *models.Node) []net.IPNet {
  538. //check for internet gateway
  539. internetGateway := false
  540. if slices.Contains(peer.EgressGatewayRanges, "0.0.0.0/0") || slices.Contains(peer.EgressGatewayRanges, "::/0") {
  541. internetGateway = true
  542. }
  543. allowedips := []net.IPNet{}
  544. for _, iprange := range peer.EgressGatewayRanges { // go through each cidr for egress gateway
  545. _, ipnet, err := net.ParseCIDR(iprange) // confirming it's valid cidr
  546. if err != nil {
  547. logger.Log(1, "could not parse gateway IP range. Not adding ", iprange)
  548. continue // if can't parse CIDR
  549. }
  550. nodeEndpointArr := strings.Split(peer.Endpoint, ":") // getting the public ip of node
  551. if ipnet.Contains(net.ParseIP(nodeEndpointArr[0])) && !internetGateway { // ensuring egress gateway range does not contain endpoint of node
  552. logger.Log(2, "egress IP range of ", iprange, " overlaps with ", node.Endpoint, ", omitting")
  553. continue // skip adding egress range if overlaps with node's ip
  554. }
  555. // TODO: Could put in a lot of great logic to avoid conflicts / bad routes
  556. if ipnet.Contains(net.ParseIP(node.LocalAddress)) && !internetGateway { // ensuring egress gateway range does not contain public ip of node
  557. logger.Log(2, "egress IP range of ", iprange, " overlaps with ", node.LocalAddress, ", omitting")
  558. continue // skip adding egress range if overlaps with node's local ip
  559. }
  560. if err != nil {
  561. logger.Log(1, "error encountered when setting egress range", err.Error())
  562. } else {
  563. allowedips = append(allowedips, *ipnet)
  564. }
  565. }
  566. return allowedips
  567. }
  568. func getNodeAllowedIPs(peer, node *models.Node) []net.IPNet {
  569. var allowedips = []net.IPNet{}
  570. if peer.Address != "" {
  571. var peeraddr = net.IPNet{
  572. IP: net.ParseIP(peer.Address),
  573. Mask: net.CIDRMask(32, 32),
  574. }
  575. allowedips = append(allowedips, peeraddr)
  576. }
  577. if peer.Address6 != "" {
  578. var addr6 = net.IPNet{
  579. IP: net.ParseIP(peer.Address6),
  580. Mask: net.CIDRMask(128, 128),
  581. }
  582. allowedips = append(allowedips, addr6)
  583. }
  584. // handle manually set peers
  585. for _, allowedIp := range peer.AllowedIPs {
  586. // parsing as a CIDR first. If valid CIDR, append
  587. if _, ipnet, err := net.ParseCIDR(allowedIp); err == nil {
  588. nodeEndpointArr := strings.Split(node.Endpoint, ":")
  589. if !ipnet.Contains(net.IP(nodeEndpointArr[0])) && ipnet.IP.String() != peer.Address { // don't need to add an allowed ip that already exists..
  590. allowedips = append(allowedips, *ipnet)
  591. }
  592. } else { // parsing as an IP second. If valid IP, check if ipv4 or ipv6, then append
  593. if iplib.Version(net.ParseIP(allowedIp)) == 4 && allowedIp != peer.Address {
  594. ipnet := net.IPNet{
  595. IP: net.ParseIP(allowedIp),
  596. Mask: net.CIDRMask(32, 32),
  597. }
  598. allowedips = append(allowedips, ipnet)
  599. } else if iplib.Version(net.ParseIP(allowedIp)) == 6 && allowedIp != peer.Address6 {
  600. ipnet := net.IPNet{
  601. IP: net.ParseIP(allowedIp),
  602. Mask: net.CIDRMask(128, 128),
  603. }
  604. allowedips = append(allowedips, ipnet)
  605. }
  606. }
  607. }
  608. // handle egress gateway peers
  609. if peer.IsEgressGateway == "yes" {
  610. //hasGateway = true
  611. egressIPs := getEgressIPs(node, peer)
  612. // remove internet gateway if server
  613. if node.IsServer == "yes" {
  614. for i := len(egressIPs) - 1; i >= 0; i-- {
  615. if egressIPs[i].String() == "0.0.0.0/0" || egressIPs[i].String() == "::/0" {
  616. egressIPs = append(egressIPs[:i], egressIPs[i+1:]...)
  617. }
  618. }
  619. }
  620. allowedips = append(allowedips, egressIPs...)
  621. }
  622. return allowedips
  623. }