peers.go 23 KB

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