peers.go 24 KB

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