extpeers.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. package logic
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net"
  6. "reflect"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/gravitl/netmaker/database"
  11. "github.com/gravitl/netmaker/logger"
  12. "github.com/gravitl/netmaker/logic/acls"
  13. "github.com/gravitl/netmaker/models"
  14. "github.com/gravitl/netmaker/servercfg"
  15. "golang.org/x/exp/slog"
  16. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  17. )
  18. var (
  19. extClientCacheMutex = &sync.RWMutex{}
  20. extClientCacheMap = make(map[string]models.ExtClient)
  21. )
  22. func getAllExtClientsFromCache() (extClients []models.ExtClient) {
  23. extClientCacheMutex.RLock()
  24. for _, extclient := range extClientCacheMap {
  25. extClients = append(extClients, extclient)
  26. }
  27. extClientCacheMutex.RUnlock()
  28. return
  29. }
  30. func deleteExtClientFromCache(key string) {
  31. extClientCacheMutex.Lock()
  32. delete(extClientCacheMap, key)
  33. extClientCacheMutex.Unlock()
  34. }
  35. func getExtClientFromCache(key string) (extclient models.ExtClient, ok bool) {
  36. extClientCacheMutex.RLock()
  37. extclient, ok = extClientCacheMap[key]
  38. extClientCacheMutex.RUnlock()
  39. return
  40. }
  41. func storeExtClientInCache(key string, extclient models.ExtClient) {
  42. extClientCacheMutex.Lock()
  43. extClientCacheMap[key] = extclient
  44. extClientCacheMutex.Unlock()
  45. }
  46. // ExtClient.GetEgressRangesOnNetwork - returns the egress ranges on network of ext client
  47. func GetEgressRangesOnNetwork(client *models.ExtClient) ([]string, error) {
  48. var result []string
  49. networkNodes, err := GetNetworkNodes(client.Network)
  50. if err != nil {
  51. return []string{}, err
  52. }
  53. for _, currentNode := range networkNodes {
  54. if currentNode.Network != client.Network {
  55. continue
  56. }
  57. if currentNode.IsEgressGateway { // add the egress gateway range(s) to the result
  58. if len(currentNode.EgressGatewayRanges) > 0 {
  59. result = append(result, currentNode.EgressGatewayRanges...)
  60. }
  61. }
  62. }
  63. extclients := GetGwExtclients(client.IngressGatewayID, client.Network)
  64. for _, extclient := range extclients {
  65. if extclient.ClientID == client.ClientID {
  66. continue
  67. }
  68. result = append(result, extclient.ExtraAllowedIPs...)
  69. }
  70. return result, nil
  71. }
  72. // DeleteExtClient - deletes an existing ext client
  73. func DeleteExtClient(network string, clientid string) error {
  74. key, err := GetRecordKey(clientid, network)
  75. if err != nil {
  76. return err
  77. }
  78. extClient, err := GetExtClient(clientid, network)
  79. if err != nil {
  80. return err
  81. }
  82. err = database.DeleteRecord(database.EXT_CLIENT_TABLE_NAME, key)
  83. if err != nil {
  84. return err
  85. }
  86. //recycle ip address
  87. if extClient.Address != "" {
  88. RemoveIpFromAllocatedIpMap(network, extClient.Address)
  89. }
  90. if extClient.Address6 != "" {
  91. RemoveIpFromAllocatedIpMap(network, extClient.Address6)
  92. }
  93. if servercfg.CacheEnabled() {
  94. deleteExtClientFromCache(key)
  95. }
  96. return nil
  97. }
  98. // DeleteExtClientAndCleanup - deletes an existing ext client and update ACLs
  99. func DeleteExtClientAndCleanup(extClient models.ExtClient) error {
  100. //delete extClient record
  101. err := DeleteExtClient(extClient.Network, extClient.ClientID)
  102. if err != nil {
  103. slog.Error("DeleteExtClientAndCleanup-remove extClient record: ", "Error", err.Error())
  104. return err
  105. }
  106. //update ACLs
  107. var networkAcls acls.ACLContainer
  108. networkAcls, err = networkAcls.Get(acls.ContainerID(extClient.Network))
  109. if err != nil {
  110. slog.Error("DeleteExtClientAndCleanup-update network acls: ", "Error", err.Error())
  111. return err
  112. }
  113. for objId := range networkAcls {
  114. delete(networkAcls[objId], acls.AclID(extClient.ClientID))
  115. }
  116. delete(networkAcls, acls.AclID(extClient.ClientID))
  117. if _, err = networkAcls.Save(acls.ContainerID(extClient.Network)); err != nil {
  118. slog.Error("DeleteExtClientAndCleanup-update network acls:", "Error", err.Error())
  119. return err
  120. }
  121. return nil
  122. }
  123. //TODO - enforce extclient-to-extclient on ingress gw
  124. /* 1. fetch all non-user static nodes
  125. a. check against each user node, if allowed add rule
  126. */
  127. // GetNetworkExtClients - gets the ext clients of given network
  128. func GetNetworkExtClients(network string) ([]models.ExtClient, error) {
  129. var extclients []models.ExtClient
  130. if servercfg.CacheEnabled() {
  131. allextclients := getAllExtClientsFromCache()
  132. if len(allextclients) != 0 {
  133. for _, extclient := range allextclients {
  134. if extclient.Network == network {
  135. extclients = append(extclients, extclient)
  136. }
  137. }
  138. return extclients, nil
  139. }
  140. }
  141. records, err := database.FetchRecords(database.EXT_CLIENT_TABLE_NAME)
  142. if err != nil {
  143. if database.IsEmptyRecord(err) {
  144. return extclients, nil
  145. }
  146. return extclients, err
  147. }
  148. for _, value := range records {
  149. var extclient models.ExtClient
  150. err = json.Unmarshal([]byte(value), &extclient)
  151. if err != nil {
  152. continue
  153. }
  154. key, err := GetRecordKey(extclient.ClientID, extclient.Network)
  155. if err == nil {
  156. if servercfg.CacheEnabled() {
  157. storeExtClientInCache(key, extclient)
  158. }
  159. }
  160. if extclient.Network == network {
  161. extclients = append(extclients, extclient)
  162. }
  163. }
  164. return extclients, err
  165. }
  166. // GetExtClient - gets a single ext client on a network
  167. func GetExtClient(clientid string, network string) (models.ExtClient, error) {
  168. var extclient models.ExtClient
  169. key, err := GetRecordKey(clientid, network)
  170. if err != nil {
  171. return extclient, err
  172. }
  173. if servercfg.CacheEnabled() {
  174. if extclient, ok := getExtClientFromCache(key); ok {
  175. return extclient, nil
  176. }
  177. }
  178. data, err := database.FetchRecord(database.EXT_CLIENT_TABLE_NAME, key)
  179. if err != nil {
  180. return extclient, err
  181. }
  182. err = json.Unmarshal([]byte(data), &extclient)
  183. if servercfg.CacheEnabled() {
  184. storeExtClientInCache(key, extclient)
  185. }
  186. return extclient, err
  187. }
  188. // GetGwExtclients - return all ext clients attached to the passed gw id
  189. func GetGwExtclients(nodeID, network string) []models.ExtClient {
  190. gwClients := []models.ExtClient{}
  191. clients, err := GetNetworkExtClients(network)
  192. if err != nil {
  193. return gwClients
  194. }
  195. for _, client := range clients {
  196. if client.IngressGatewayID == nodeID {
  197. gwClients = append(gwClients, client)
  198. }
  199. }
  200. return gwClients
  201. }
  202. // GetExtClient - gets a single ext client on a network
  203. func GetExtClientByPubKey(publicKey string, network string) (*models.ExtClient, error) {
  204. netClients, err := GetNetworkExtClients(network)
  205. if err != nil {
  206. return nil, err
  207. }
  208. for i := range netClients {
  209. ec := netClients[i]
  210. if ec.PublicKey == publicKey {
  211. return &ec, nil
  212. }
  213. }
  214. return nil, fmt.Errorf("no client found")
  215. }
  216. // CreateExtClient - creates and saves an extclient
  217. func CreateExtClient(extclient *models.ExtClient) error {
  218. // lock because we may need unique IPs and having it concurrent makes parallel calls result in same "unique" IPs
  219. addressLock.Lock()
  220. defer addressLock.Unlock()
  221. if len(extclient.PublicKey) == 0 {
  222. privateKey, err := wgtypes.GeneratePrivateKey()
  223. if err != nil {
  224. return err
  225. }
  226. extclient.PrivateKey = privateKey.String()
  227. extclient.PublicKey = privateKey.PublicKey().String()
  228. } else if len(extclient.PrivateKey) == 0 && len(extclient.PublicKey) > 0 {
  229. extclient.PrivateKey = "[ENTER PRIVATE KEY]"
  230. }
  231. if extclient.ExtraAllowedIPs == nil {
  232. extclient.ExtraAllowedIPs = []string{}
  233. }
  234. parentNetwork, err := GetNetwork(extclient.Network)
  235. if err != nil {
  236. return err
  237. }
  238. if extclient.Address == "" {
  239. if parentNetwork.IsIPv4 == "yes" {
  240. newAddress, err := UniqueAddress(extclient.Network, true)
  241. if err != nil {
  242. return err
  243. }
  244. extclient.Address = newAddress.String()
  245. }
  246. }
  247. if extclient.Address6 == "" {
  248. if parentNetwork.IsIPv6 == "yes" {
  249. addr6, err := UniqueAddress6(extclient.Network, true)
  250. if err != nil {
  251. return err
  252. }
  253. extclient.Address6 = addr6.String()
  254. }
  255. }
  256. if extclient.ClientID == "" {
  257. extclient.ClientID = models.GenerateNodeName()
  258. }
  259. extclient.LastModified = time.Now().Unix()
  260. return SaveExtClient(extclient)
  261. }
  262. // SaveExtClient - saves an ext client to database
  263. func SaveExtClient(extclient *models.ExtClient) error {
  264. key, err := GetRecordKey(extclient.ClientID, extclient.Network)
  265. if err != nil {
  266. return err
  267. }
  268. data, err := json.Marshal(&extclient)
  269. if err != nil {
  270. return err
  271. }
  272. if err = database.Insert(key, string(data), database.EXT_CLIENT_TABLE_NAME); err != nil {
  273. return err
  274. }
  275. if servercfg.CacheEnabled() {
  276. storeExtClientInCache(key, *extclient)
  277. }
  278. if _, ok := allocatedIpMap[extclient.Network]; ok {
  279. if extclient.Address != "" {
  280. AddIpToAllocatedIpMap(extclient.Network, net.ParseIP(extclient.Address))
  281. }
  282. if extclient.Address6 != "" {
  283. AddIpToAllocatedIpMap(extclient.Network, net.ParseIP(extclient.Address6))
  284. }
  285. }
  286. return SetNetworkNodesLastModified(extclient.Network)
  287. }
  288. // UpdateExtClient - updates an ext client with new values
  289. func UpdateExtClient(old *models.ExtClient, update *models.CustomExtClient) models.ExtClient {
  290. new := *old
  291. new.ClientID = update.ClientID
  292. if update.PublicKey != "" && old.PublicKey != update.PublicKey {
  293. new.PublicKey = update.PublicKey
  294. }
  295. if update.DNS != old.DNS {
  296. new.DNS = update.DNS
  297. }
  298. if update.Enabled != old.Enabled {
  299. new.Enabled = update.Enabled
  300. }
  301. new.ExtraAllowedIPs = update.ExtraAllowedIPs
  302. if update.DeniedACLs != nil && !reflect.DeepEqual(old.DeniedACLs, update.DeniedACLs) {
  303. new.DeniedACLs = update.DeniedACLs
  304. }
  305. // replace any \r\n with \n in postup and postdown from HTTP request
  306. new.PostUp = strings.Replace(update.PostUp, "\r\n", "\n", -1)
  307. new.PostDown = strings.Replace(update.PostDown, "\r\n", "\n", -1)
  308. new.Tags = update.Tags
  309. return new
  310. }
  311. // GetExtClientsByID - gets the clients of attached gateway
  312. func GetExtClientsByID(nodeid, network string) ([]models.ExtClient, error) {
  313. var result []models.ExtClient
  314. currentClients, err := GetNetworkExtClients(network)
  315. if err != nil {
  316. return result, err
  317. }
  318. for i := range currentClients {
  319. if currentClients[i].IngressGatewayID == nodeid {
  320. result = append(result, currentClients[i])
  321. }
  322. }
  323. return result, nil
  324. }
  325. // GetAllExtClients - gets all ext clients from DB
  326. func GetAllExtClients() ([]models.ExtClient, error) {
  327. var clients = []models.ExtClient{}
  328. currentNetworks, err := GetNetworks()
  329. if err != nil && database.IsEmptyRecord(err) {
  330. return clients, nil
  331. } else if err != nil {
  332. return clients, err
  333. }
  334. for i := range currentNetworks {
  335. netName := currentNetworks[i].NetID
  336. netClients, err := GetNetworkExtClients(netName)
  337. if err != nil {
  338. continue
  339. }
  340. clients = append(clients, netClients...)
  341. }
  342. return clients, nil
  343. }
  344. // ToggleExtClientConnectivity - enables or disables an ext client
  345. func ToggleExtClientConnectivity(client *models.ExtClient, enable bool) (models.ExtClient, error) {
  346. update := models.CustomExtClient{
  347. Enabled: enable,
  348. ClientID: client.ClientID,
  349. PublicKey: client.PublicKey,
  350. DNS: client.DNS,
  351. ExtraAllowedIPs: client.ExtraAllowedIPs,
  352. DeniedACLs: client.DeniedACLs,
  353. RemoteAccessClientID: client.RemoteAccessClientID,
  354. }
  355. // update in DB
  356. newClient := UpdateExtClient(client, &update)
  357. if err := DeleteExtClient(client.Network, client.ClientID); err != nil {
  358. slog.Error("failed to delete ext client during update", "id", client.ClientID, "network", client.Network, "error", err)
  359. return newClient, err
  360. }
  361. if err := SaveExtClient(&newClient); err != nil {
  362. slog.Error("failed to save updated ext client during update", "id", newClient.ClientID, "network", newClient.Network, "error", err)
  363. return newClient, err
  364. }
  365. return newClient, nil
  366. }
  367. func GetStaticNodeIps(node models.Node) (ips []net.IP) {
  368. defaultUserPolicy, _ := GetDefaultPolicy(models.NetworkID(node.Network), models.UserPolicy)
  369. defaultDevicePolicy, _ := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  370. extclients := GetStaticNodesByNetwork(models.NetworkID(node.Network), false)
  371. for _, extclient := range extclients {
  372. if extclient.IsUserNode && defaultUserPolicy.Enabled {
  373. continue
  374. }
  375. if !extclient.IsUserNode && defaultDevicePolicy.Enabled {
  376. continue
  377. }
  378. if extclient.StaticNode.Address != "" {
  379. ips = append(ips, extclient.StaticNode.AddressIPNet4().IP)
  380. }
  381. if extclient.StaticNode.Address6 != "" {
  382. ips = append(ips, extclient.StaticNode.AddressIPNet6().IP)
  383. }
  384. }
  385. return
  386. }
  387. func GetFwRulesOnIngressGateway(node models.Node) (rules []models.FwRule) {
  388. // fetch user access to static clients via policies
  389. defaultUserPolicy, _ := GetDefaultPolicy(models.NetworkID(node.Network), models.UserPolicy)
  390. defaultDevicePolicy, _ := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  391. nodes, _ := GetNetworkNodes(node.Network)
  392. nodes = append(nodes, GetStaticNodesByNetwork(models.NetworkID(node.Network), true)...)
  393. //fmt.Printf("=====> NODES: %+v \n\n", nodes)
  394. userNodes := GetStaticUserNodesByNetwork(models.NetworkID(node.Network))
  395. //fmt.Printf("=====> USER NODES %+v \n\n", userNodes)
  396. for _, userNodeI := range userNodes {
  397. for _, peer := range nodes {
  398. if peer.IsUserNode {
  399. continue
  400. }
  401. if IsUserAllowedToCommunicate(userNodeI.StaticNode.OwnerID, peer) {
  402. if peer.IsStatic {
  403. if userNodeI.StaticNode.Address != "" {
  404. if !defaultUserPolicy.Enabled {
  405. rules = append(rules, models.FwRule{
  406. SrcIp: userNodeI.StaticNode.AddressIPNet4().IP,
  407. DstIP: peer.StaticNode.AddressIPNet4().IP,
  408. Allow: true,
  409. })
  410. }
  411. rules = append(rules, models.FwRule{
  412. SrcIp: peer.StaticNode.AddressIPNet4().IP,
  413. DstIP: userNodeI.StaticNode.AddressIPNet4().IP,
  414. Allow: true,
  415. })
  416. }
  417. if userNodeI.StaticNode.Address6 != "" {
  418. if !defaultUserPolicy.Enabled {
  419. rules = append(rules, models.FwRule{
  420. SrcIp: userNodeI.StaticNode.AddressIPNet6().IP,
  421. DstIP: peer.StaticNode.AddressIPNet6().IP,
  422. Allow: true,
  423. })
  424. }
  425. rules = append(rules, models.FwRule{
  426. SrcIp: peer.StaticNode.AddressIPNet6().IP,
  427. DstIP: userNodeI.StaticNode.AddressIPNet6().IP,
  428. Allow: true,
  429. })
  430. }
  431. } else {
  432. if userNodeI.StaticNode.Address != "" {
  433. if !defaultUserPolicy.Enabled {
  434. rules = append(rules, models.FwRule{
  435. SrcIp: userNodeI.StaticNode.AddressIPNet4().IP,
  436. DstIP: peer.Address.IP,
  437. Allow: true,
  438. })
  439. }
  440. }
  441. if userNodeI.StaticNode.Address6 != "" {
  442. rules = append(rules, models.FwRule{
  443. SrcIp: userNodeI.StaticNode.AddressIPNet6().IP,
  444. DstIP: peer.Address6.IP,
  445. Allow: true,
  446. })
  447. }
  448. }
  449. }
  450. }
  451. }
  452. if defaultDevicePolicy.Enabled {
  453. return
  454. }
  455. for _, nodeI := range nodes {
  456. if !nodeI.IsStatic || nodeI.IsUserNode {
  457. continue
  458. }
  459. for _, peer := range nodes {
  460. if peer.StaticNode.ClientID == nodeI.StaticNode.ClientID || peer.IsUserNode {
  461. continue
  462. }
  463. if IsNodeAllowedToCommunicate(nodeI, peer) {
  464. if peer.IsStatic {
  465. if nodeI.StaticNode.Address != "" {
  466. rules = append(rules, models.FwRule{
  467. SrcIp: nodeI.StaticNode.AddressIPNet4().IP,
  468. DstIP: peer.StaticNode.AddressIPNet4().IP,
  469. Allow: true,
  470. })
  471. }
  472. if nodeI.StaticNode.Address6 != "" {
  473. rules = append(rules, models.FwRule{
  474. SrcIp: nodeI.StaticNode.AddressIPNet6().IP,
  475. DstIP: peer.StaticNode.AddressIPNet6().IP,
  476. Allow: true,
  477. })
  478. }
  479. } else {
  480. if nodeI.StaticNode.Address != "" {
  481. rules = append(rules, models.FwRule{
  482. SrcIp: nodeI.StaticNode.AddressIPNet4().IP,
  483. DstIP: peer.Address.IP,
  484. Allow: true,
  485. })
  486. }
  487. if nodeI.StaticNode.Address6 != "" {
  488. rules = append(rules, models.FwRule{
  489. SrcIp: nodeI.StaticNode.AddressIPNet6().IP,
  490. DstIP: peer.Address6.IP,
  491. Allow: true,
  492. })
  493. }
  494. }
  495. }
  496. }
  497. }
  498. return
  499. }
  500. func GetExtPeers(node, peer *models.Node) ([]wgtypes.PeerConfig, []models.IDandAddr, []models.EgressNetworkRoutes, error) {
  501. var peers []wgtypes.PeerConfig
  502. var idsAndAddr []models.IDandAddr
  503. var egressRoutes []models.EgressNetworkRoutes
  504. extPeers, err := GetNetworkExtClients(node.Network)
  505. if err != nil {
  506. return peers, idsAndAddr, egressRoutes, err
  507. }
  508. host, err := GetHost(node.HostID.String())
  509. if err != nil {
  510. return peers, idsAndAddr, egressRoutes, err
  511. }
  512. for _, extPeer := range extPeers {
  513. extPeer := extPeer
  514. if !IsClientNodeAllowed(&extPeer, peer.ID.String()) {
  515. continue
  516. }
  517. if extPeer.RemoteAccessClientID == "" {
  518. if !IsNodeAllowedToCommunicate(extPeer.ConvertToStaticNode(), *peer) {
  519. continue
  520. }
  521. } else {
  522. if !IsUserAllowedToCommunicate(extPeer.OwnerID, *peer) {
  523. continue
  524. }
  525. }
  526. pubkey, err := wgtypes.ParseKey(extPeer.PublicKey)
  527. if err != nil {
  528. logger.Log(1, "error parsing ext pub key:", err.Error())
  529. continue
  530. }
  531. if host.PublicKey.String() == extPeer.PublicKey ||
  532. extPeer.IngressGatewayID != node.ID.String() || !extPeer.Enabled {
  533. continue
  534. }
  535. var allowedips []net.IPNet
  536. var peer wgtypes.PeerConfig
  537. if extPeer.Address != "" {
  538. var peeraddr = net.IPNet{
  539. IP: net.ParseIP(extPeer.Address),
  540. Mask: net.CIDRMask(32, 32),
  541. }
  542. if peeraddr.IP != nil && peeraddr.Mask != nil {
  543. allowedips = append(allowedips, peeraddr)
  544. }
  545. }
  546. if extPeer.Address6 != "" {
  547. var addr6 = net.IPNet{
  548. IP: net.ParseIP(extPeer.Address6),
  549. Mask: net.CIDRMask(128, 128),
  550. }
  551. if addr6.IP != nil && addr6.Mask != nil {
  552. allowedips = append(allowedips, addr6)
  553. }
  554. }
  555. for _, extraAllowedIP := range extPeer.ExtraAllowedIPs {
  556. _, cidr, err := net.ParseCIDR(extraAllowedIP)
  557. if err == nil {
  558. allowedips = append(allowedips, *cidr)
  559. }
  560. }
  561. egressRoutes = append(egressRoutes, getExtPeerEgressRoute(*node, extPeer)...)
  562. primaryAddr := extPeer.Address
  563. if primaryAddr == "" {
  564. primaryAddr = extPeer.Address6
  565. }
  566. peer = wgtypes.PeerConfig{
  567. PublicKey: pubkey,
  568. ReplaceAllowedIPs: true,
  569. AllowedIPs: allowedips,
  570. }
  571. peers = append(peers, peer)
  572. idsAndAddr = append(idsAndAddr, models.IDandAddr{
  573. ID: peer.PublicKey.String(),
  574. Name: extPeer.ClientID,
  575. Address: primaryAddr,
  576. IsExtClient: true,
  577. })
  578. }
  579. return peers, idsAndAddr, egressRoutes, nil
  580. }
  581. func getExtPeerEgressRoute(node models.Node, extPeer models.ExtClient) (egressRoutes []models.EgressNetworkRoutes) {
  582. egressRoutes = append(egressRoutes, models.EgressNetworkRoutes{
  583. EgressGwAddr: extPeer.AddressIPNet4(),
  584. EgressGwAddr6: extPeer.AddressIPNet6(),
  585. NodeAddr: node.Address,
  586. NodeAddr6: node.Address6,
  587. EgressRanges: extPeer.ExtraAllowedIPs,
  588. })
  589. return
  590. }
  591. func getExtpeersExtraRoutes(node models.Node, network string) (egressRoutes []models.EgressNetworkRoutes) {
  592. extPeers, err := GetNetworkExtClients(network)
  593. if err != nil {
  594. return
  595. }
  596. for _, extPeer := range extPeers {
  597. if len(extPeer.ExtraAllowedIPs) == 0 {
  598. continue
  599. }
  600. if !IsNodeAllowedToCommunicate(extPeer.ConvertToStaticNode(), node) {
  601. continue
  602. }
  603. egressRoutes = append(egressRoutes, getExtPeerEgressRoute(node, extPeer)...)
  604. }
  605. return
  606. }
  607. func GetExtclientAllowedIPs(client models.ExtClient) (allowedIPs []string) {
  608. gwnode, err := GetNodeByID(client.IngressGatewayID)
  609. if err != nil {
  610. logger.Log(0,
  611. fmt.Sprintf("failed to get ingress gateway node [%s] info: %v", client.IngressGatewayID, err))
  612. return
  613. }
  614. network, err := GetParentNetwork(client.Network)
  615. if err != nil {
  616. logger.Log(1, "Could not retrieve Ingress Gateway Network", client.Network)
  617. return
  618. }
  619. if IsInternetGw(gwnode) {
  620. egressrange := "0.0.0.0/0"
  621. if gwnode.Address6.IP != nil && client.Address6 != "" {
  622. egressrange += "," + "::/0"
  623. }
  624. allowedIPs = []string{egressrange}
  625. } else {
  626. allowedIPs = []string{network.AddressRange}
  627. if network.AddressRange6 != "" {
  628. allowedIPs = append(allowedIPs, network.AddressRange6)
  629. }
  630. if egressGatewayRanges, err := GetEgressRangesOnNetwork(&client); err == nil {
  631. allowedIPs = append(allowedIPs, egressGatewayRanges...)
  632. }
  633. }
  634. return
  635. }
  636. func GetStaticUserNodesByNetwork(network models.NetworkID) (staticNode []models.Node) {
  637. extClients, err := GetAllExtClients()
  638. if err != nil {
  639. return
  640. }
  641. for _, extI := range extClients {
  642. if extI.Network == network.String() {
  643. if extI.RemoteAccessClientID != "" {
  644. n := models.Node{
  645. IsStatic: true,
  646. StaticNode: extI,
  647. IsUserNode: extI.RemoteAccessClientID != "",
  648. }
  649. staticNode = append(staticNode, n)
  650. }
  651. }
  652. }
  653. return
  654. }
  655. func GetStaticNodesByNetwork(network models.NetworkID, onlyWg bool) (staticNode []models.Node) {
  656. extClients, err := GetAllExtClients()
  657. if err != nil {
  658. return
  659. }
  660. for _, extI := range extClients {
  661. if extI.Network == network.String() {
  662. if onlyWg && extI.RemoteAccessClientID != "" {
  663. continue
  664. }
  665. n := models.Node{
  666. IsStatic: true,
  667. StaticNode: extI,
  668. IsUserNode: extI.RemoteAccessClientID != "",
  669. }
  670. staticNode = append(staticNode, n)
  671. }
  672. }
  673. return
  674. }
  675. func GetStaticNodesByGw(gwNode models.Node) (staticNode []models.Node) {
  676. extClients, err := GetAllExtClients()
  677. if err != nil {
  678. return
  679. }
  680. for _, extI := range extClients {
  681. if extI.IngressGatewayID == gwNode.ID.String() {
  682. n := models.Node{
  683. IsStatic: true,
  684. StaticNode: extI,
  685. IsUserNode: extI.RemoteAccessClientID != "",
  686. }
  687. staticNode = append(staticNode, n)
  688. }
  689. }
  690. return
  691. }