extpeers.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  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, _ := GetNetworkExtClients(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(),
  407. DstIP: peer.StaticNode.AddressIPNet4(),
  408. Allow: true,
  409. })
  410. }
  411. rules = append(rules, models.FwRule{
  412. SrcIP: peer.StaticNode.AddressIPNet4(),
  413. DstIP: userNodeI.StaticNode.AddressIPNet4(),
  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(),
  421. DstIP: peer.StaticNode.AddressIPNet6(),
  422. Allow: true,
  423. })
  424. }
  425. rules = append(rules, models.FwRule{
  426. SrcIP: peer.StaticNode.AddressIPNet6(),
  427. DstIP: userNodeI.StaticNode.AddressIPNet6(),
  428. Allow: true,
  429. })
  430. }
  431. if len(peer.StaticNode.ExtraAllowedIPs) > 0 {
  432. for _, additionalAllowedIPNet := range peer.StaticNode.ExtraAllowedIPs {
  433. _, ipNet, err := net.ParseCIDR(additionalAllowedIPNet)
  434. if err != nil {
  435. continue
  436. }
  437. if ipNet.IP.To4() != nil {
  438. rules = append(rules, models.FwRule{
  439. SrcIP: userNodeI.StaticNode.AddressIPNet4(),
  440. DstIP: *ipNet,
  441. Allow: true,
  442. })
  443. } else {
  444. rules = append(rules, models.FwRule{
  445. SrcIP: userNodeI.StaticNode.AddressIPNet6(),
  446. DstIP: *ipNet,
  447. Allow: true,
  448. })
  449. }
  450. }
  451. }
  452. } else {
  453. if userNodeI.StaticNode.Address != "" {
  454. if !defaultUserPolicy.Enabled {
  455. rules = append(rules, models.FwRule{
  456. SrcIP: userNodeI.StaticNode.AddressIPNet4(),
  457. DstIP: net.IPNet{
  458. IP: peer.Address.IP,
  459. Mask: net.CIDRMask(32, 32),
  460. },
  461. Allow: true,
  462. })
  463. }
  464. }
  465. if userNodeI.StaticNode.Address6 != "" {
  466. rules = append(rules, models.FwRule{
  467. SrcIP: userNodeI.StaticNode.AddressIPNet6(),
  468. DstIP: net.IPNet{
  469. IP: peer.Address6.IP,
  470. Mask: net.CIDRMask(128, 128),
  471. },
  472. Allow: true,
  473. })
  474. }
  475. }
  476. }
  477. }
  478. }
  479. if defaultDevicePolicy.Enabled {
  480. return
  481. }
  482. for _, nodeI := range nodes {
  483. if !nodeI.IsStatic || nodeI.IsUserNode {
  484. continue
  485. }
  486. for _, peer := range nodes {
  487. if peer.StaticNode.ClientID == nodeI.StaticNode.ClientID || peer.IsUserNode {
  488. continue
  489. }
  490. if IsNodeAllowedToCommunicate(nodeI, peer) {
  491. if peer.IsStatic {
  492. if nodeI.StaticNode.Address != "" {
  493. rules = append(rules, models.FwRule{
  494. SrcIP: nodeI.StaticNode.AddressIPNet4(),
  495. DstIP: peer.StaticNode.AddressIPNet4(),
  496. Allow: true,
  497. })
  498. }
  499. if nodeI.StaticNode.Address6 != "" {
  500. rules = append(rules, models.FwRule{
  501. SrcIP: nodeI.StaticNode.AddressIPNet6(),
  502. DstIP: peer.StaticNode.AddressIPNet6(),
  503. Allow: true,
  504. })
  505. }
  506. if len(peer.StaticNode.ExtraAllowedIPs) > 0 {
  507. for _, additionalAllowedIPNet := range peer.StaticNode.ExtraAllowedIPs {
  508. _, ipNet, err := net.ParseCIDR(additionalAllowedIPNet)
  509. if err != nil {
  510. continue
  511. }
  512. if ipNet.IP.To4() != nil {
  513. rules = append(rules, models.FwRule{
  514. SrcIP: nodeI.StaticNode.AddressIPNet4(),
  515. DstIP: *ipNet,
  516. Allow: true,
  517. })
  518. } else {
  519. rules = append(rules, models.FwRule{
  520. SrcIP: nodeI.StaticNode.AddressIPNet6(),
  521. DstIP: *ipNet,
  522. Allow: true,
  523. })
  524. }
  525. }
  526. }
  527. } else {
  528. if nodeI.StaticNode.Address != "" {
  529. rules = append(rules, models.FwRule{
  530. SrcIP: nodeI.StaticNode.AddressIPNet4(),
  531. DstIP: net.IPNet{
  532. IP: peer.Address.IP,
  533. Mask: net.CIDRMask(32, 32),
  534. },
  535. Allow: true,
  536. })
  537. }
  538. if nodeI.StaticNode.Address6 != "" {
  539. rules = append(rules, models.FwRule{
  540. SrcIP: nodeI.StaticNode.AddressIPNet6(),
  541. DstIP: net.IPNet{
  542. IP: peer.Address6.IP,
  543. Mask: net.CIDRMask(128, 128),
  544. },
  545. Allow: true,
  546. })
  547. }
  548. }
  549. }
  550. }
  551. }
  552. return
  553. }
  554. func GetExtPeers(node, peer *models.Node) ([]wgtypes.PeerConfig, []models.IDandAddr, []models.EgressNetworkRoutes, error) {
  555. var peers []wgtypes.PeerConfig
  556. var idsAndAddr []models.IDandAddr
  557. var egressRoutes []models.EgressNetworkRoutes
  558. extPeers, err := GetNetworkExtClients(node.Network)
  559. if err != nil {
  560. return peers, idsAndAddr, egressRoutes, err
  561. }
  562. host, err := GetHost(node.HostID.String())
  563. if err != nil {
  564. return peers, idsAndAddr, egressRoutes, err
  565. }
  566. for _, extPeer := range extPeers {
  567. extPeer := extPeer
  568. if !IsClientNodeAllowed(&extPeer, peer.ID.String()) {
  569. continue
  570. }
  571. if extPeer.RemoteAccessClientID == "" {
  572. if !IsNodeAllowedToCommunicate(extPeer.ConvertToStaticNode(), *peer) {
  573. continue
  574. }
  575. } else {
  576. if !IsUserAllowedToCommunicate(extPeer.OwnerID, *peer) {
  577. continue
  578. }
  579. }
  580. pubkey, err := wgtypes.ParseKey(extPeer.PublicKey)
  581. if err != nil {
  582. logger.Log(1, "error parsing ext pub key:", err.Error())
  583. continue
  584. }
  585. if host.PublicKey.String() == extPeer.PublicKey ||
  586. extPeer.IngressGatewayID != node.ID.String() || !extPeer.Enabled {
  587. continue
  588. }
  589. var allowedips []net.IPNet
  590. var peer wgtypes.PeerConfig
  591. if extPeer.Address != "" {
  592. var peeraddr = net.IPNet{
  593. IP: net.ParseIP(extPeer.Address),
  594. Mask: net.CIDRMask(32, 32),
  595. }
  596. if peeraddr.IP != nil && peeraddr.Mask != nil {
  597. allowedips = append(allowedips, peeraddr)
  598. }
  599. }
  600. if extPeer.Address6 != "" {
  601. var addr6 = net.IPNet{
  602. IP: net.ParseIP(extPeer.Address6),
  603. Mask: net.CIDRMask(128, 128),
  604. }
  605. if addr6.IP != nil && addr6.Mask != nil {
  606. allowedips = append(allowedips, addr6)
  607. }
  608. }
  609. for _, extraAllowedIP := range extPeer.ExtraAllowedIPs {
  610. _, cidr, err := net.ParseCIDR(extraAllowedIP)
  611. if err == nil {
  612. allowedips = append(allowedips, *cidr)
  613. }
  614. }
  615. egressRoutes = append(egressRoutes, getExtPeerEgressRoute(*node, extPeer)...)
  616. primaryAddr := extPeer.Address
  617. if primaryAddr == "" {
  618. primaryAddr = extPeer.Address6
  619. }
  620. peer = wgtypes.PeerConfig{
  621. PublicKey: pubkey,
  622. ReplaceAllowedIPs: true,
  623. AllowedIPs: allowedips,
  624. }
  625. peers = append(peers, peer)
  626. idsAndAddr = append(idsAndAddr, models.IDandAddr{
  627. ID: peer.PublicKey.String(),
  628. Name: extPeer.ClientID,
  629. Address: primaryAddr,
  630. IsExtClient: true,
  631. })
  632. }
  633. return peers, idsAndAddr, egressRoutes, nil
  634. }
  635. func getExtPeerEgressRoute(node models.Node, extPeer models.ExtClient) (egressRoutes []models.EgressNetworkRoutes) {
  636. egressRoutes = append(egressRoutes, models.EgressNetworkRoutes{
  637. EgressGwAddr: extPeer.AddressIPNet4(),
  638. EgressGwAddr6: extPeer.AddressIPNet6(),
  639. NodeAddr: node.Address,
  640. NodeAddr6: node.Address6,
  641. EgressRanges: extPeer.ExtraAllowedIPs,
  642. })
  643. return
  644. }
  645. func getExtpeerEgressRanges(node models.Node) (ranges, ranges6 []net.IPNet) {
  646. extPeers, err := GetNetworkExtClients(node.Network)
  647. if err != nil {
  648. return
  649. }
  650. for _, extPeer := range extPeers {
  651. if len(extPeer.ExtraAllowedIPs) == 0 {
  652. continue
  653. }
  654. if !IsNodeAllowedToCommunicate(extPeer.ConvertToStaticNode(), node) {
  655. continue
  656. }
  657. for _, allowedRange := range extPeer.ExtraAllowedIPs {
  658. _, ipnet, err := net.ParseCIDR(allowedRange)
  659. if err == nil {
  660. if ipnet.IP.To4() != nil {
  661. ranges = append(ranges, *ipnet)
  662. } else {
  663. ranges6 = append(ranges6, *ipnet)
  664. }
  665. }
  666. }
  667. }
  668. return
  669. }
  670. func getExtpeersExtraRoutes(node models.Node) (egressRoutes []models.EgressNetworkRoutes) {
  671. extPeers, err := GetNetworkExtClients(node.Network)
  672. if err != nil {
  673. return
  674. }
  675. for _, extPeer := range extPeers {
  676. if len(extPeer.ExtraAllowedIPs) == 0 {
  677. continue
  678. }
  679. if !IsNodeAllowedToCommunicate(extPeer.ConvertToStaticNode(), node) {
  680. continue
  681. }
  682. egressRoutes = append(egressRoutes, getExtPeerEgressRoute(node, extPeer)...)
  683. }
  684. return
  685. }
  686. func GetExtclientAllowedIPs(client models.ExtClient) (allowedIPs []string) {
  687. gwnode, err := GetNodeByID(client.IngressGatewayID)
  688. if err != nil {
  689. logger.Log(0,
  690. fmt.Sprintf("failed to get ingress gateway node [%s] info: %v", client.IngressGatewayID, err))
  691. return
  692. }
  693. network, err := GetParentNetwork(client.Network)
  694. if err != nil {
  695. logger.Log(1, "Could not retrieve Ingress Gateway Network", client.Network)
  696. return
  697. }
  698. if IsInternetGw(gwnode) {
  699. egressrange := "0.0.0.0/0"
  700. if gwnode.Address6.IP != nil && client.Address6 != "" {
  701. egressrange += "," + "::/0"
  702. }
  703. allowedIPs = []string{egressrange}
  704. } else {
  705. allowedIPs = []string{network.AddressRange}
  706. if network.AddressRange6 != "" {
  707. allowedIPs = append(allowedIPs, network.AddressRange6)
  708. }
  709. if egressGatewayRanges, err := GetEgressRangesOnNetwork(&client); err == nil {
  710. allowedIPs = append(allowedIPs, egressGatewayRanges...)
  711. }
  712. }
  713. return
  714. }
  715. func GetStaticUserNodesByNetwork(network models.NetworkID) (staticNode []models.Node) {
  716. extClients, err := GetAllExtClients()
  717. if err != nil {
  718. return
  719. }
  720. for _, extI := range extClients {
  721. if extI.Network == network.String() {
  722. if extI.RemoteAccessClientID != "" {
  723. n := models.Node{
  724. IsStatic: true,
  725. StaticNode: extI,
  726. IsUserNode: extI.RemoteAccessClientID != "",
  727. }
  728. staticNode = append(staticNode, n)
  729. }
  730. }
  731. }
  732. return
  733. }
  734. func GetStaticNodesByNetwork(network models.NetworkID, onlyWg bool) (staticNode []models.Node) {
  735. extClients, err := GetAllExtClients()
  736. if err != nil {
  737. return
  738. }
  739. for _, extI := range extClients {
  740. if extI.Network == network.String() {
  741. if onlyWg && extI.RemoteAccessClientID != "" {
  742. continue
  743. }
  744. n := models.Node{
  745. IsStatic: true,
  746. StaticNode: extI,
  747. IsUserNode: extI.RemoteAccessClientID != "",
  748. }
  749. staticNode = append(staticNode, n)
  750. }
  751. }
  752. return
  753. }
  754. func GetStaticNodesByGw(gwNode models.Node) (staticNode []models.Node) {
  755. extClients, err := GetAllExtClients()
  756. if err != nil {
  757. return
  758. }
  759. for _, extI := range extClients {
  760. if extI.IngressGatewayID == gwNode.ID.String() {
  761. n := models.Node{
  762. IsStatic: true,
  763. StaticNode: extI,
  764. IsUserNode: extI.RemoteAccessClientID != "",
  765. }
  766. staticNode = append(staticNode, n)
  767. }
  768. }
  769. return
  770. }