peers.go 19 KB

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