peers.go 25 KB

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