extpeers.go 28 KB

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