extpeers.go 22 KB

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