peers.go 23 KB

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