extpeers.go 25 KB

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