acls.go 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918
  1. package logic
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "maps"
  7. "net"
  8. "sort"
  9. "sync"
  10. "time"
  11. "github.com/google/uuid"
  12. "github.com/gravitl/netmaker/database"
  13. "github.com/gravitl/netmaker/models"
  14. "github.com/gravitl/netmaker/servercfg"
  15. )
  16. var (
  17. aclCacheMutex = &sync.RWMutex{}
  18. aclCacheMap = make(map[string]models.Acl)
  19. )
  20. func MigrateAclPolicies() {
  21. acls := ListAcls()
  22. for _, acl := range acls {
  23. if acl.Proto.String() == "" {
  24. acl.Proto = models.ALL
  25. acl.ServiceType = models.Any
  26. acl.Port = []string{}
  27. UpsertAcl(acl)
  28. }
  29. }
  30. }
  31. // CreateDefaultAclNetworkPolicies - create default acl network policies
  32. func CreateDefaultAclNetworkPolicies(netID models.NetworkID) {
  33. if netID.String() == "" {
  34. return
  35. }
  36. _, _ = ListAclsByNetwork(netID)
  37. if !IsAclExists(fmt.Sprintf("%s.%s", netID, "all-nodes")) {
  38. defaultDeviceAcl := models.Acl{
  39. ID: fmt.Sprintf("%s.%s", netID, "all-nodes"),
  40. Name: "All Nodes",
  41. MetaData: "This Policy allows all nodes in the network to communicate with each other",
  42. Default: true,
  43. NetworkID: netID,
  44. Proto: models.ALL,
  45. ServiceType: models.Any,
  46. Port: []string{},
  47. RuleType: models.DevicePolicy,
  48. Src: []models.AclPolicyTag{
  49. {
  50. ID: models.NodeTagID,
  51. Value: "*",
  52. }},
  53. Dst: []models.AclPolicyTag{
  54. {
  55. ID: models.NodeTagID,
  56. Value: "*",
  57. }},
  58. AllowedDirection: models.TrafficDirectionBi,
  59. Enabled: true,
  60. CreatedBy: "auto",
  61. CreatedAt: time.Now().UTC(),
  62. }
  63. InsertAcl(defaultDeviceAcl)
  64. }
  65. if !IsAclExists(fmt.Sprintf("%s.%s", netID, "all-users")) {
  66. defaultUserAcl := models.Acl{
  67. ID: fmt.Sprintf("%s.%s", netID, "all-users"),
  68. Default: true,
  69. Name: "All Users",
  70. MetaData: "This policy gives access to everything in the network for an user",
  71. NetworkID: netID,
  72. Proto: models.ALL,
  73. ServiceType: models.Any,
  74. Port: []string{},
  75. RuleType: models.UserPolicy,
  76. Src: []models.AclPolicyTag{
  77. {
  78. ID: models.UserAclID,
  79. Value: "*",
  80. },
  81. },
  82. Dst: []models.AclPolicyTag{{
  83. ID: models.NodeTagID,
  84. Value: "*",
  85. }},
  86. AllowedDirection: models.TrafficDirectionUni,
  87. Enabled: true,
  88. CreatedBy: "auto",
  89. CreatedAt: time.Now().UTC(),
  90. }
  91. InsertAcl(defaultUserAcl)
  92. }
  93. if !IsAclExists(fmt.Sprintf("%s.%s", netID, "all-gateways")) {
  94. defaultUserAcl := models.Acl{
  95. ID: fmt.Sprintf("%s.%s", netID, "all-gateways"),
  96. Default: true,
  97. Name: "All Gateways",
  98. NetworkID: netID,
  99. Proto: models.ALL,
  100. ServiceType: models.Any,
  101. Port: []string{},
  102. RuleType: models.DevicePolicy,
  103. Src: []models.AclPolicyTag{
  104. {
  105. ID: models.NodeTagID,
  106. Value: fmt.Sprintf("%s.%s", netID, models.GwTagName),
  107. },
  108. },
  109. Dst: []models.AclPolicyTag{
  110. {
  111. ID: models.NodeTagID,
  112. Value: "*",
  113. },
  114. },
  115. AllowedDirection: models.TrafficDirectionBi,
  116. Enabled: true,
  117. CreatedBy: "auto",
  118. CreatedAt: time.Now().UTC(),
  119. }
  120. InsertAcl(defaultUserAcl)
  121. }
  122. CreateDefaultUserPolicies(netID)
  123. }
  124. // DeleteNetworkPolicies - deletes all default network acl policies
  125. func DeleteNetworkPolicies(netId models.NetworkID) {
  126. acls, _ := ListAclsByNetwork(netId)
  127. for _, acl := range acls {
  128. if acl.NetworkID == netId {
  129. DeleteAcl(acl)
  130. }
  131. }
  132. }
  133. // ValidateCreateAclReq - validates create req for acl
  134. func ValidateCreateAclReq(req models.Acl) error {
  135. // check if acl network exists
  136. _, err := GetNetwork(req.NetworkID.String())
  137. if err != nil {
  138. return errors.New("failed to get network details for " + req.NetworkID.String())
  139. }
  140. // err = CheckIDSyntax(req.Name)
  141. // if err != nil {
  142. // return err
  143. // }
  144. return nil
  145. }
  146. func listAclFromCache() (acls []models.Acl) {
  147. aclCacheMutex.RLock()
  148. defer aclCacheMutex.RUnlock()
  149. for _, acl := range aclCacheMap {
  150. acls = append(acls, acl)
  151. }
  152. return
  153. }
  154. func storeAclInCache(a models.Acl) {
  155. aclCacheMutex.Lock()
  156. defer aclCacheMutex.Unlock()
  157. aclCacheMap[a.ID] = a
  158. }
  159. func removeAclFromCache(a models.Acl) {
  160. aclCacheMutex.Lock()
  161. defer aclCacheMutex.Unlock()
  162. delete(aclCacheMap, a.ID)
  163. }
  164. func getAclFromCache(aID string) (a models.Acl, ok bool) {
  165. aclCacheMutex.RLock()
  166. defer aclCacheMutex.RUnlock()
  167. a, ok = aclCacheMap[aID]
  168. return
  169. }
  170. // InsertAcl - creates acl policy
  171. func InsertAcl(a models.Acl) error {
  172. d, err := json.Marshal(a)
  173. if err != nil {
  174. return err
  175. }
  176. err = database.Insert(a.ID, string(d), database.ACLS_TABLE_NAME)
  177. if err == nil && servercfg.CacheEnabled() {
  178. storeAclInCache(a)
  179. }
  180. return err
  181. }
  182. // GetAcl - gets acl info by id
  183. func GetAcl(aID string) (models.Acl, error) {
  184. a := models.Acl{}
  185. if servercfg.CacheEnabled() {
  186. var ok bool
  187. a, ok = getAclFromCache(aID)
  188. if ok {
  189. return a, nil
  190. }
  191. }
  192. d, err := database.FetchRecord(database.ACLS_TABLE_NAME, aID)
  193. if err != nil {
  194. return a, err
  195. }
  196. err = json.Unmarshal([]byte(d), &a)
  197. if err != nil {
  198. return a, err
  199. }
  200. if servercfg.CacheEnabled() {
  201. storeAclInCache(a)
  202. }
  203. return a, nil
  204. }
  205. // IsAclExists - checks if acl exists
  206. func IsAclExists(aclID string) bool {
  207. _, err := GetAcl(aclID)
  208. return err == nil
  209. }
  210. func GetEgressRanges(netID models.NetworkID) (map[string][]string, map[string]struct{}, error) {
  211. resultMap := make(map[string]struct{})
  212. nodeEgressMap := make(map[string][]string)
  213. networkNodes, err := GetNetworkNodes(netID.String())
  214. if err != nil {
  215. return nil, nil, err
  216. }
  217. for _, currentNode := range networkNodes {
  218. if currentNode.Network != netID.String() {
  219. continue
  220. }
  221. if currentNode.IsEgressGateway { // add the egress gateway range(s) to the result
  222. if len(currentNode.EgressGatewayRanges) > 0 {
  223. nodeEgressMap[currentNode.ID.String()] = currentNode.EgressGatewayRanges
  224. for _, egressRangeI := range currentNode.EgressGatewayRanges {
  225. resultMap[egressRangeI] = struct{}{}
  226. }
  227. }
  228. }
  229. }
  230. extclients, _ := GetNetworkExtClients(netID.String())
  231. for _, extclient := range extclients {
  232. if len(extclient.ExtraAllowedIPs) > 0 {
  233. nodeEgressMap[extclient.ClientID] = extclient.ExtraAllowedIPs
  234. for _, extraAllowedIP := range extclient.ExtraAllowedIPs {
  235. resultMap[extraAllowedIP] = struct{}{}
  236. }
  237. }
  238. }
  239. return nodeEgressMap, resultMap, nil
  240. }
  241. func checkIfAclTagisValid(t models.AclPolicyTag, netID models.NetworkID, policyType models.AclPolicyType, isSrc bool) bool {
  242. switch t.ID {
  243. case models.NodeTagID:
  244. if policyType == models.UserPolicy && isSrc {
  245. return false
  246. }
  247. // check if tag is valid
  248. _, err := GetTag(models.TagID(t.Value))
  249. if err != nil {
  250. return false
  251. }
  252. case models.NodeID:
  253. if policyType == models.UserPolicy && isSrc {
  254. return false
  255. }
  256. _, nodeErr := GetNodeByID(t.Value)
  257. if nodeErr != nil {
  258. _, staticNodeErr := GetExtClient(t.Value, netID.String())
  259. if staticNodeErr != nil {
  260. return false
  261. }
  262. }
  263. case models.EgressRange:
  264. if isSrc {
  265. return false
  266. }
  267. // _, rangesMap, err := GetEgressRanges(netID)
  268. // if err != nil {
  269. // return false
  270. // }
  271. // if _, ok := rangesMap[t.Value]; !ok {
  272. // return false
  273. // }
  274. case models.UserAclID:
  275. if policyType == models.DevicePolicy {
  276. return false
  277. }
  278. if !isSrc {
  279. return false
  280. }
  281. _, err := GetUser(t.Value)
  282. if err != nil {
  283. return false
  284. }
  285. case models.UserGroupAclID:
  286. if policyType == models.DevicePolicy {
  287. return false
  288. }
  289. if !isSrc {
  290. return false
  291. }
  292. err := IsGroupValid(models.UserGroupID(t.Value))
  293. if err != nil {
  294. return false
  295. }
  296. // check if group belongs to this network
  297. netGrps := GetUserGroupsInNetwork(netID)
  298. if _, ok := netGrps[models.UserGroupID(t.Value)]; !ok {
  299. return false
  300. }
  301. default:
  302. return false
  303. }
  304. return true
  305. }
  306. // IsAclPolicyValid - validates if acl policy is valid
  307. func IsAclPolicyValid(acl models.Acl) bool {
  308. //check if src and dst are valid
  309. if acl.AllowedDirection != models.TrafficDirectionBi &&
  310. acl.AllowedDirection != models.TrafficDirectionUni {
  311. return false
  312. }
  313. switch acl.RuleType {
  314. case models.UserPolicy:
  315. // src list should only contain users
  316. for _, srcI := range acl.Src {
  317. if srcI.Value == "*" {
  318. continue
  319. }
  320. // check if user group is valid
  321. if !checkIfAclTagisValid(srcI, acl.NetworkID, acl.RuleType, true) {
  322. return false
  323. }
  324. }
  325. for _, dstI := range acl.Dst {
  326. if dstI.Value == "*" {
  327. continue
  328. }
  329. // check if user group is valid
  330. if !checkIfAclTagisValid(dstI, acl.NetworkID, acl.RuleType, false) {
  331. return false
  332. }
  333. }
  334. case models.DevicePolicy:
  335. for _, srcI := range acl.Src {
  336. if srcI.Value == "*" {
  337. continue
  338. }
  339. // check if user group is valid
  340. if !checkIfAclTagisValid(srcI, acl.NetworkID, acl.RuleType, true) {
  341. return false
  342. }
  343. }
  344. for _, dstI := range acl.Dst {
  345. if dstI.Value == "*" {
  346. continue
  347. }
  348. // check if user group is valid
  349. if !checkIfAclTagisValid(dstI, acl.NetworkID, acl.RuleType, false) {
  350. return false
  351. }
  352. }
  353. }
  354. return true
  355. }
  356. // UpdateAcl - updates allowed fields on acls and commits to DB
  357. func UpdateAcl(newAcl, acl models.Acl) error {
  358. if !acl.Default {
  359. acl.Name = newAcl.Name
  360. acl.Src = newAcl.Src
  361. acl.Dst = newAcl.Dst
  362. acl.AllowedDirection = newAcl.AllowedDirection
  363. acl.Port = newAcl.Port
  364. acl.Proto = newAcl.Proto
  365. acl.ServiceType = newAcl.ServiceType
  366. }
  367. if newAcl.ServiceType == models.Any {
  368. acl.Port = []string{}
  369. acl.Proto = models.ALL
  370. }
  371. acl.Enabled = newAcl.Enabled
  372. d, err := json.Marshal(acl)
  373. if err != nil {
  374. return err
  375. }
  376. err = database.Insert(acl.ID, string(d), database.ACLS_TABLE_NAME)
  377. if err == nil && servercfg.CacheEnabled() {
  378. storeAclInCache(acl)
  379. }
  380. return err
  381. }
  382. // UpsertAcl - upserts acl
  383. func UpsertAcl(acl models.Acl) error {
  384. d, err := json.Marshal(acl)
  385. if err != nil {
  386. return err
  387. }
  388. err = database.Insert(acl.ID, string(d), database.ACLS_TABLE_NAME)
  389. if err == nil && servercfg.CacheEnabled() {
  390. storeAclInCache(acl)
  391. }
  392. return err
  393. }
  394. // DeleteAcl - deletes acl policy
  395. func DeleteAcl(a models.Acl) error {
  396. err := database.DeleteRecord(database.ACLS_TABLE_NAME, a.ID)
  397. if err == nil && servercfg.CacheEnabled() {
  398. removeAclFromCache(a)
  399. }
  400. return err
  401. }
  402. // GetDefaultPolicy - fetches default policy in the network by ruleType
  403. func GetDefaultPolicy(netID models.NetworkID, ruleType models.AclPolicyType) (models.Acl, error) {
  404. aclID := "all-users"
  405. if ruleType == models.DevicePolicy {
  406. aclID = "all-nodes"
  407. }
  408. acl, err := GetAcl(fmt.Sprintf("%s.%s", netID, aclID))
  409. if err != nil {
  410. return models.Acl{}, errors.New("default rule not found")
  411. }
  412. if acl.Enabled {
  413. return acl, nil
  414. }
  415. // check if there are any custom all policies
  416. srcMap := make(map[string]struct{})
  417. dstMap := make(map[string]struct{})
  418. defer func() {
  419. srcMap = nil
  420. dstMap = nil
  421. }()
  422. policies, _ := ListAclsByNetwork(netID)
  423. for _, policy := range policies {
  424. if !policy.Enabled {
  425. continue
  426. }
  427. if policy.RuleType == ruleType {
  428. dstMap = convAclTagToValueMap(policy.Dst)
  429. srcMap = convAclTagToValueMap(policy.Src)
  430. if _, ok := srcMap["*"]; ok {
  431. if _, ok := dstMap["*"]; ok {
  432. return policy, nil
  433. }
  434. }
  435. }
  436. }
  437. return acl, nil
  438. }
  439. func ListAcls() (acls []models.Acl) {
  440. if servercfg.CacheEnabled() && len(aclCacheMap) > 0 {
  441. return listAclFromCache()
  442. }
  443. data, err := database.FetchRecords(database.ACLS_TABLE_NAME)
  444. if err != nil && !database.IsEmptyRecord(err) {
  445. return []models.Acl{}
  446. }
  447. for _, dataI := range data {
  448. acl := models.Acl{}
  449. err := json.Unmarshal([]byte(dataI), &acl)
  450. if err != nil {
  451. continue
  452. }
  453. acls = append(acls, acl)
  454. if servercfg.CacheEnabled() {
  455. storeAclInCache(acl)
  456. }
  457. }
  458. return
  459. }
  460. // ListUserPolicies - lists all acl policies enforced on an user
  461. func ListUserPolicies(u models.User) []models.Acl {
  462. allAcls := ListAcls()
  463. userAcls := []models.Acl{}
  464. for _, acl := range allAcls {
  465. if acl.RuleType == models.UserPolicy {
  466. srcMap := convAclTagToValueMap(acl.Src)
  467. if _, ok := srcMap[u.UserName]; ok {
  468. userAcls = append(userAcls, acl)
  469. } else {
  470. // check for user groups
  471. for gID := range u.UserGroups {
  472. if _, ok := srcMap[gID.String()]; ok {
  473. userAcls = append(userAcls, acl)
  474. break
  475. }
  476. }
  477. }
  478. }
  479. }
  480. return userAcls
  481. }
  482. // listPoliciesOfUser - lists all user acl policies applied to user in an network
  483. func listPoliciesOfUser(user models.User, netID models.NetworkID) []models.Acl {
  484. allAcls := ListAcls()
  485. userAcls := []models.Acl{}
  486. for _, acl := range allAcls {
  487. if acl.NetworkID == netID && acl.RuleType == models.UserPolicy {
  488. srcMap := convAclTagToValueMap(acl.Src)
  489. if _, ok := srcMap[user.UserName]; ok {
  490. userAcls = append(userAcls, acl)
  491. continue
  492. }
  493. for netRole := range user.NetworkRoles {
  494. if _, ok := srcMap[netRole.String()]; ok {
  495. userAcls = append(userAcls, acl)
  496. continue
  497. }
  498. }
  499. for userG := range user.UserGroups {
  500. if _, ok := srcMap[userG.String()]; ok {
  501. userAcls = append(userAcls, acl)
  502. continue
  503. }
  504. }
  505. }
  506. }
  507. return userAcls
  508. }
  509. // listDevicePolicies - lists all device policies in a network
  510. func listDevicePolicies(netID models.NetworkID) []models.Acl {
  511. allAcls := ListAcls()
  512. deviceAcls := []models.Acl{}
  513. for _, acl := range allAcls {
  514. if acl.NetworkID == netID && acl.RuleType == models.DevicePolicy {
  515. deviceAcls = append(deviceAcls, acl)
  516. }
  517. }
  518. return deviceAcls
  519. }
  520. // listUserPolicies - lists all user policies in a network
  521. func listUserPolicies(netID models.NetworkID) []models.Acl {
  522. allAcls := ListAcls()
  523. deviceAcls := []models.Acl{}
  524. for _, acl := range allAcls {
  525. if acl.NetworkID == netID && acl.RuleType == models.UserPolicy {
  526. deviceAcls = append(deviceAcls, acl)
  527. }
  528. }
  529. return deviceAcls
  530. }
  531. // ListAcls - lists all acl policies
  532. func ListAclsByNetwork(netID models.NetworkID) ([]models.Acl, error) {
  533. allAcls := ListAcls()
  534. netAcls := []models.Acl{}
  535. for _, acl := range allAcls {
  536. if acl.NetworkID == netID {
  537. netAcls = append(netAcls, acl)
  538. }
  539. }
  540. return netAcls, nil
  541. }
  542. func convAclTagToValueMap(acltags []models.AclPolicyTag) map[string]struct{} {
  543. aclValueMap := make(map[string]struct{})
  544. for _, aclTagI := range acltags {
  545. aclValueMap[aclTagI.Value] = struct{}{}
  546. }
  547. return aclValueMap
  548. }
  549. // IsUserAllowedToCommunicate - check if user is allowed to communicate with peer
  550. func IsUserAllowedToCommunicate(userName string, peer models.Node) (bool, []models.Acl) {
  551. var peerId string
  552. if peer.IsStatic {
  553. peerId = peer.StaticNode.ClientID
  554. peer = peer.StaticNode.ConvertToStaticNode()
  555. } else {
  556. peerId = peer.ID.String()
  557. }
  558. var peerTags map[models.TagID]struct{}
  559. if peer.Mutex != nil {
  560. peer.Mutex.Lock()
  561. peerTags = maps.Clone(peer.Tags)
  562. peer.Mutex.Unlock()
  563. } else {
  564. peerTags = peer.Tags
  565. }
  566. peerTags[models.TagID(peerId)] = struct{}{}
  567. acl, _ := GetDefaultPolicy(models.NetworkID(peer.Network), models.UserPolicy)
  568. if acl.Enabled {
  569. return true, []models.Acl{acl}
  570. }
  571. user, err := GetUser(userName)
  572. if err != nil {
  573. return false, []models.Acl{}
  574. }
  575. allowedPolicies := []models.Acl{}
  576. policies := listPoliciesOfUser(*user, models.NetworkID(peer.Network))
  577. for _, policy := range policies {
  578. if !policy.Enabled {
  579. continue
  580. }
  581. dstMap := convAclTagToValueMap(policy.Dst)
  582. if _, ok := dstMap["*"]; ok {
  583. allowedPolicies = append(allowedPolicies, policy)
  584. continue
  585. }
  586. if _, ok := dstMap[peer.ID.String()]; ok {
  587. allowedPolicies = append(allowedPolicies, policy)
  588. continue
  589. }
  590. for tagID := range peerTags {
  591. if _, ok := dstMap[tagID.String()]; ok {
  592. allowedPolicies = append(allowedPolicies, policy)
  593. break
  594. }
  595. }
  596. }
  597. if len(allowedPolicies) > 0 {
  598. return true, allowedPolicies
  599. }
  600. return false, []models.Acl{}
  601. }
  602. // IsPeerAllowed - checks if peer needs to be added to the interface
  603. func IsPeerAllowed(node, peer models.Node, checkDefaultPolicy bool) bool {
  604. var nodeId, peerId string
  605. if peer.IsFailOver && node.FailedOverBy != uuid.Nil && node.FailedOverBy == peer.ID {
  606. return true
  607. }
  608. if node.IsFailOver && peer.FailedOverBy != uuid.Nil && peer.FailedOverBy == node.ID {
  609. return true
  610. }
  611. if node.IsStatic {
  612. nodeId = node.StaticNode.ClientID
  613. node = node.StaticNode.ConvertToStaticNode()
  614. } else {
  615. nodeId = node.ID.String()
  616. }
  617. if peer.IsStatic {
  618. peerId = peer.StaticNode.ClientID
  619. peer = peer.StaticNode.ConvertToStaticNode()
  620. } else {
  621. peerId = peer.ID.String()
  622. }
  623. var nodeTags, peerTags map[models.TagID]struct{}
  624. if node.Mutex != nil {
  625. node.Mutex.Lock()
  626. nodeTags = maps.Clone(node.Tags)
  627. node.Mutex.Unlock()
  628. } else {
  629. nodeTags = node.Tags
  630. }
  631. if peer.Mutex != nil {
  632. peer.Mutex.Lock()
  633. peerTags = maps.Clone(peer.Tags)
  634. peer.Mutex.Unlock()
  635. } else {
  636. peerTags = peer.Tags
  637. }
  638. if nodeTags == nil {
  639. nodeTags = make(map[models.TagID]struct{})
  640. }
  641. if peerTags == nil {
  642. peerTags = make(map[models.TagID]struct{})
  643. }
  644. nodeTags[models.TagID(nodeId)] = struct{}{}
  645. peerTags[models.TagID(peerId)] = struct{}{}
  646. if checkDefaultPolicy {
  647. // check default policy if all allowed return true
  648. defaultPolicy, err := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  649. if err == nil {
  650. if defaultPolicy.Enabled {
  651. return true
  652. }
  653. }
  654. }
  655. // list device policies
  656. policies := listDevicePolicies(models.NetworkID(peer.Network))
  657. srcMap := make(map[string]struct{})
  658. dstMap := make(map[string]struct{})
  659. defer func() {
  660. srcMap = nil
  661. dstMap = nil
  662. }()
  663. for _, policy := range policies {
  664. if !policy.Enabled {
  665. continue
  666. }
  667. srcMap = convAclTagToValueMap(policy.Src)
  668. dstMap = convAclTagToValueMap(policy.Dst)
  669. if checkTagGroupPolicy(srcMap, dstMap, node, peer, nodeTags, peerTags) {
  670. return true
  671. }
  672. }
  673. return false
  674. }
  675. func RemoveUserFromAclPolicy(userName string) {
  676. acls := ListAcls()
  677. for _, acl := range acls {
  678. delete := false
  679. update := false
  680. if acl.RuleType == models.UserPolicy {
  681. for i := len(acl.Src) - 1; i >= 0; i-- {
  682. if acl.Src[i].ID == models.UserAclID && acl.Src[i].Value == userName {
  683. if len(acl.Src) == 1 {
  684. // delete policy
  685. delete = true
  686. break
  687. } else {
  688. acl.Src = append(acl.Src[:i], acl.Src[i+1:]...)
  689. update = true
  690. }
  691. }
  692. }
  693. if delete {
  694. DeleteAcl(acl)
  695. continue
  696. }
  697. if update {
  698. UpsertAcl(acl)
  699. }
  700. }
  701. }
  702. }
  703. func RemoveNodeFromAclPolicy(node models.Node) {
  704. var nodeID string
  705. if node.IsStatic {
  706. nodeID = node.StaticNode.ClientID
  707. } else {
  708. nodeID = node.ID.String()
  709. }
  710. acls, _ := ListAclsByNetwork(models.NetworkID(node.Network))
  711. for _, acl := range acls {
  712. delete := false
  713. update := false
  714. if acl.RuleType == models.DevicePolicy {
  715. for i := len(acl.Src) - 1; i >= 0; i-- {
  716. if acl.Src[i].ID == models.NodeID && acl.Src[i].Value == nodeID {
  717. if len(acl.Src) == 1 {
  718. // delete policy
  719. delete = true
  720. break
  721. } else {
  722. acl.Src = append(acl.Src[:i], acl.Src[i+1:]...)
  723. update = true
  724. }
  725. }
  726. }
  727. if delete {
  728. DeleteAcl(acl)
  729. continue
  730. }
  731. for i := len(acl.Dst) - 1; i >= 0; i-- {
  732. if acl.Dst[i].ID == models.NodeID && acl.Dst[i].Value == nodeID {
  733. if len(acl.Dst) == 1 {
  734. // delete policy
  735. delete = true
  736. break
  737. } else {
  738. acl.Dst = append(acl.Dst[:i], acl.Dst[i+1:]...)
  739. update = true
  740. }
  741. }
  742. }
  743. if delete {
  744. DeleteAcl(acl)
  745. continue
  746. }
  747. if update {
  748. UpsertAcl(acl)
  749. }
  750. }
  751. if acl.RuleType == models.UserPolicy {
  752. for i := len(acl.Dst) - 1; i >= 0; i-- {
  753. if acl.Dst[i].ID == models.NodeID && acl.Dst[i].Value == nodeID {
  754. if len(acl.Dst) == 1 {
  755. // delete policy
  756. delete = true
  757. break
  758. } else {
  759. acl.Dst = append(acl.Dst[:i], acl.Dst[i+1:]...)
  760. update = true
  761. }
  762. }
  763. }
  764. if delete {
  765. DeleteAcl(acl)
  766. continue
  767. }
  768. if update {
  769. UpsertAcl(acl)
  770. }
  771. }
  772. }
  773. }
  774. func checkTagGroupPolicy(srcMap, dstMap map[string]struct{}, node, peer models.Node,
  775. nodeTags, peerTags map[models.TagID]struct{}) bool {
  776. // check for node ID
  777. if _, ok := srcMap[node.ID.String()]; ok {
  778. if _, ok = dstMap[peer.ID.String()]; ok {
  779. return true
  780. }
  781. }
  782. if _, ok := dstMap[node.ID.String()]; ok {
  783. if _, ok = srcMap[peer.ID.String()]; ok {
  784. return true
  785. }
  786. }
  787. for tagID := range nodeTags {
  788. if _, ok := dstMap[tagID.String()]; ok {
  789. if _, ok := srcMap["*"]; ok {
  790. return true
  791. }
  792. for tagID := range peerTags {
  793. if _, ok := srcMap[tagID.String()]; ok {
  794. return true
  795. }
  796. }
  797. }
  798. if _, ok := srcMap[tagID.String()]; ok {
  799. if _, ok := dstMap["*"]; ok {
  800. return true
  801. }
  802. for tagID := range peerTags {
  803. if _, ok := dstMap[tagID.String()]; ok {
  804. return true
  805. }
  806. }
  807. }
  808. }
  809. for tagID := range peerTags {
  810. if _, ok := dstMap[tagID.String()]; ok {
  811. if _, ok := srcMap["*"]; ok {
  812. return true
  813. }
  814. for tagID := range nodeTags {
  815. if _, ok := srcMap[tagID.String()]; ok {
  816. return true
  817. }
  818. }
  819. }
  820. if _, ok := srcMap[tagID.String()]; ok {
  821. if _, ok := dstMap["*"]; ok {
  822. return true
  823. }
  824. for tagID := range nodeTags {
  825. if _, ok := dstMap[tagID.String()]; ok {
  826. return true
  827. }
  828. }
  829. }
  830. }
  831. return false
  832. }
  833. func uniquePolicies(items []models.Acl) []models.Acl {
  834. if len(items) == 0 {
  835. return items
  836. }
  837. seen := make(map[string]bool)
  838. var result []models.Acl
  839. for _, item := range items {
  840. if !seen[item.ID] {
  841. seen[item.ID] = true
  842. result = append(result, item)
  843. }
  844. }
  845. return result
  846. }
  847. // IsNodeAllowedToCommunicate - check node is allowed to communicate with the peer // ADD ALLOWED DIRECTION - 0 => node -> peer, 1 => peer-> node,
  848. func IsNodeAllowedToCommunicateV1(node, peer models.Node, checkDefaultPolicy bool) (bool, []models.Acl) {
  849. var nodeId, peerId string
  850. if peer.IsFailOver && node.FailedOverBy != uuid.Nil && node.FailedOverBy == peer.ID {
  851. return true, []models.Acl{}
  852. }
  853. if node.IsFailOver && peer.FailedOverBy != uuid.Nil && peer.FailedOverBy == node.ID {
  854. return true, []models.Acl{}
  855. }
  856. if node.IsStatic {
  857. nodeId = node.StaticNode.ClientID
  858. node = node.StaticNode.ConvertToStaticNode()
  859. } else {
  860. nodeId = node.ID.String()
  861. }
  862. if peer.IsStatic {
  863. peerId = peer.StaticNode.ClientID
  864. peer = peer.StaticNode.ConvertToStaticNode()
  865. } else {
  866. peerId = peer.ID.String()
  867. }
  868. var nodeTags, peerTags map[models.TagID]struct{}
  869. if node.Mutex != nil {
  870. node.Mutex.Lock()
  871. nodeTags = maps.Clone(node.Tags)
  872. node.Mutex.Unlock()
  873. } else {
  874. nodeTags = node.Tags
  875. }
  876. if peer.Mutex != nil {
  877. peer.Mutex.Lock()
  878. peerTags = maps.Clone(peer.Tags)
  879. peer.Mutex.Unlock()
  880. } else {
  881. peerTags = peer.Tags
  882. }
  883. if nodeTags == nil {
  884. nodeTags = make(map[models.TagID]struct{})
  885. }
  886. if peerTags == nil {
  887. peerTags = make(map[models.TagID]struct{})
  888. }
  889. nodeTags[models.TagID(nodeId)] = struct{}{}
  890. peerTags[models.TagID(peerId)] = struct{}{}
  891. if checkDefaultPolicy {
  892. // check default policy if all allowed return true
  893. defaultPolicy, err := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  894. if err == nil {
  895. if defaultPolicy.Enabled {
  896. return true, []models.Acl{defaultPolicy}
  897. }
  898. }
  899. }
  900. allowedPolicies := []models.Acl{}
  901. defer func() {
  902. allowedPolicies = uniquePolicies(allowedPolicies)
  903. }()
  904. // list device policies
  905. policies := listDevicePolicies(models.NetworkID(peer.Network))
  906. srcMap := make(map[string]struct{})
  907. dstMap := make(map[string]struct{})
  908. defer func() {
  909. srcMap = nil
  910. dstMap = nil
  911. }()
  912. for _, policy := range policies {
  913. if !policy.Enabled {
  914. continue
  915. }
  916. allowed := false
  917. srcMap = convAclTagToValueMap(policy.Src)
  918. dstMap = convAclTagToValueMap(policy.Dst)
  919. _, srcAll := srcMap["*"]
  920. _, dstAll := dstMap["*"]
  921. if policy.AllowedDirection == models.TrafficDirectionBi {
  922. if _, ok := srcMap[nodeId]; ok || srcAll {
  923. if _, ok := dstMap[peerId]; ok || dstAll {
  924. allowedPolicies = append(allowedPolicies, policy)
  925. continue
  926. }
  927. }
  928. if _, ok := dstMap[nodeId]; ok || dstAll {
  929. if _, ok := srcMap[peerId]; ok || srcAll {
  930. allowedPolicies = append(allowedPolicies, policy)
  931. continue
  932. }
  933. }
  934. }
  935. if _, ok := dstMap[peerId]; ok || dstAll {
  936. if _, ok := srcMap[nodeId]; ok || srcAll {
  937. allowedPolicies = append(allowedPolicies, policy)
  938. continue
  939. }
  940. }
  941. if policy.AllowedDirection == models.TrafficDirectionBi {
  942. for tagID := range nodeTags {
  943. if _, ok := dstMap[tagID.String()]; ok || dstAll {
  944. if srcAll {
  945. allowed = true
  946. break
  947. }
  948. for tagID := range peerTags {
  949. if _, ok := srcMap[tagID.String()]; ok {
  950. allowed = true
  951. break
  952. }
  953. }
  954. }
  955. if allowed {
  956. allowedPolicies = append(allowedPolicies, policy)
  957. break
  958. }
  959. if _, ok := srcMap[tagID.String()]; ok || srcAll {
  960. if dstAll {
  961. allowed = true
  962. break
  963. }
  964. for tagID := range peerTags {
  965. if _, ok := dstMap[tagID.String()]; ok {
  966. allowed = true
  967. break
  968. }
  969. }
  970. }
  971. if allowed {
  972. break
  973. }
  974. }
  975. if allowed {
  976. allowedPolicies = append(allowedPolicies, policy)
  977. continue
  978. }
  979. }
  980. for tagID := range peerTags {
  981. if _, ok := dstMap[tagID.String()]; ok || dstAll {
  982. if srcAll {
  983. allowed = true
  984. break
  985. }
  986. for tagID := range nodeTags {
  987. if _, ok := srcMap[tagID.String()]; ok {
  988. allowed = true
  989. break
  990. }
  991. }
  992. }
  993. if allowed {
  994. break
  995. }
  996. }
  997. if allowed {
  998. allowedPolicies = append(allowedPolicies, policy)
  999. }
  1000. }
  1001. if len(allowedPolicies) > 0 {
  1002. return true, allowedPolicies
  1003. }
  1004. return false, allowedPolicies
  1005. }
  1006. // SortTagEntrys - Sorts slice of Tag entries by their id
  1007. func SortAclEntrys(acls []models.Acl) {
  1008. sort.Slice(acls, func(i, j int) bool {
  1009. return acls[i].Name < acls[j].Name
  1010. })
  1011. }
  1012. // UpdateDeviceTag - updates device tag on acl policies
  1013. func UpdateDeviceTag(OldID, newID models.TagID, netID models.NetworkID) {
  1014. acls := listDevicePolicies(netID)
  1015. update := false
  1016. for _, acl := range acls {
  1017. for i, srcTagI := range acl.Src {
  1018. if srcTagI.ID == models.NodeTagID {
  1019. if OldID.String() == srcTagI.Value {
  1020. acl.Src[i].Value = newID.String()
  1021. update = true
  1022. }
  1023. }
  1024. }
  1025. for i, dstTagI := range acl.Dst {
  1026. if dstTagI.ID == models.NodeTagID {
  1027. if OldID.String() == dstTagI.Value {
  1028. acl.Dst[i].Value = newID.String()
  1029. update = true
  1030. }
  1031. }
  1032. }
  1033. if update {
  1034. UpsertAcl(acl)
  1035. }
  1036. }
  1037. }
  1038. func CheckIfTagAsActivePolicy(tagID models.TagID, netID models.NetworkID) bool {
  1039. acls := listDevicePolicies(netID)
  1040. for _, acl := range acls {
  1041. for _, srcTagI := range acl.Src {
  1042. if srcTagI.ID == models.NodeTagID {
  1043. if tagID.String() == srcTagI.Value {
  1044. return true
  1045. }
  1046. }
  1047. }
  1048. for _, dstTagI := range acl.Dst {
  1049. if dstTagI.ID == models.NodeTagID {
  1050. if tagID.String() == dstTagI.Value {
  1051. return true
  1052. }
  1053. }
  1054. }
  1055. }
  1056. return false
  1057. }
  1058. // RemoveDeviceTagFromAclPolicies - remove device tag from acl policies
  1059. func RemoveDeviceTagFromAclPolicies(tagID models.TagID, netID models.NetworkID) error {
  1060. acls := listDevicePolicies(netID)
  1061. update := false
  1062. for _, acl := range acls {
  1063. for i := len(acl.Src) - 1; i >= 0; i-- {
  1064. if acl.Src[i].ID == models.NodeTagID {
  1065. if tagID.String() == acl.Src[i].Value {
  1066. acl.Src = append(acl.Src[:i], acl.Src[i+1:]...)
  1067. update = true
  1068. }
  1069. }
  1070. }
  1071. for i := len(acl.Dst) - 1; i >= 0; i-- {
  1072. if acl.Dst[i].ID == models.NodeTagID {
  1073. if tagID.String() == acl.Dst[i].Value {
  1074. acl.Dst = append(acl.Dst[:i], acl.Dst[i+1:]...)
  1075. update = true
  1076. }
  1077. }
  1078. }
  1079. if update {
  1080. UpsertAcl(acl)
  1081. }
  1082. }
  1083. return nil
  1084. }
  1085. func getEgressUserRulesForNode(targetnode *models.Node,
  1086. rules map[string]models.AclRule) map[string]models.AclRule {
  1087. userNodes := GetStaticUserNodesByNetwork(models.NetworkID(targetnode.Network))
  1088. userGrpMap := GetUserGrpMap()
  1089. allowedUsers := make(map[string][]models.Acl)
  1090. acls := listUserPolicies(models.NetworkID(targetnode.Network))
  1091. var targetNodeTags = make(map[models.TagID]struct{})
  1092. targetNodeTags["*"] = struct{}{}
  1093. for _, rangeI := range targetnode.EgressGatewayRanges {
  1094. targetNodeTags[models.TagID(rangeI)] = struct{}{}
  1095. }
  1096. for _, acl := range acls {
  1097. if !acl.Enabled {
  1098. continue
  1099. }
  1100. dstTags := convAclTagToValueMap(acl.Dst)
  1101. _, all := dstTags["*"]
  1102. addUsers := false
  1103. if !all {
  1104. for nodeTag := range targetNodeTags {
  1105. if _, ok := dstTags[nodeTag.String()]; ok {
  1106. addUsers = true
  1107. break
  1108. }
  1109. }
  1110. } else {
  1111. addUsers = true
  1112. }
  1113. if addUsers {
  1114. // get all src tags
  1115. for _, srcAcl := range acl.Src {
  1116. if srcAcl.ID == models.UserAclID {
  1117. allowedUsers[srcAcl.Value] = append(allowedUsers[srcAcl.Value], acl)
  1118. } else if srcAcl.ID == models.UserGroupAclID {
  1119. // fetch all users in the group
  1120. if usersMap, ok := userGrpMap[models.UserGroupID(srcAcl.Value)]; ok {
  1121. for userName := range usersMap {
  1122. allowedUsers[userName] = append(allowedUsers[userName], acl)
  1123. }
  1124. }
  1125. }
  1126. }
  1127. }
  1128. }
  1129. for _, userNode := range userNodes {
  1130. if !userNode.StaticNode.Enabled {
  1131. continue
  1132. }
  1133. acls, ok := allowedUsers[userNode.StaticNode.OwnerID]
  1134. if !ok {
  1135. continue
  1136. }
  1137. for _, acl := range acls {
  1138. if !acl.Enabled {
  1139. continue
  1140. }
  1141. r := models.AclRule{
  1142. ID: acl.ID,
  1143. AllowedProtocol: acl.Proto,
  1144. AllowedPorts: acl.Port,
  1145. Direction: acl.AllowedDirection,
  1146. Allowed: true,
  1147. }
  1148. // Get peers in the tags and add allowed rules
  1149. if userNode.StaticNode.Address != "" {
  1150. r.IPList = append(r.IPList, userNode.StaticNode.AddressIPNet4())
  1151. }
  1152. if userNode.StaticNode.Address6 != "" {
  1153. r.IP6List = append(r.IP6List, userNode.StaticNode.AddressIPNet6())
  1154. }
  1155. for _, dstI := range acl.Dst {
  1156. if dstI.ID == models.EgressRange {
  1157. ip, cidr, err := net.ParseCIDR(dstI.Value)
  1158. if err == nil {
  1159. if ip.To4() != nil {
  1160. r.Dst = append(r.Dst, *cidr)
  1161. } else {
  1162. r.Dst6 = append(r.Dst6, *cidr)
  1163. }
  1164. }
  1165. }
  1166. }
  1167. if aclRule, ok := rules[acl.ID]; ok {
  1168. aclRule.IPList = append(aclRule.IPList, r.IPList...)
  1169. aclRule.IP6List = append(aclRule.IP6List, r.IP6List...)
  1170. rules[acl.ID] = aclRule
  1171. } else {
  1172. rules[acl.ID] = r
  1173. }
  1174. }
  1175. }
  1176. return rules
  1177. }
  1178. func getUserAclRulesForNode(targetnode *models.Node,
  1179. rules map[string]models.AclRule) map[string]models.AclRule {
  1180. userNodes := GetStaticUserNodesByNetwork(models.NetworkID(targetnode.Network))
  1181. userGrpMap := GetUserGrpMap()
  1182. allowedUsers := make(map[string][]models.Acl)
  1183. acls := listUserPolicies(models.NetworkID(targetnode.Network))
  1184. var targetNodeTags = make(map[models.TagID]struct{})
  1185. if targetnode.Mutex != nil {
  1186. targetnode.Mutex.Lock()
  1187. targetNodeTags = maps.Clone(targetnode.Tags)
  1188. targetnode.Mutex.Unlock()
  1189. } else {
  1190. targetNodeTags = maps.Clone(targetnode.Tags)
  1191. }
  1192. if targetNodeTags == nil {
  1193. targetNodeTags = make(map[models.TagID]struct{})
  1194. }
  1195. targetNodeTags[models.TagID(targetnode.ID.String())] = struct{}{}
  1196. for _, acl := range acls {
  1197. if !acl.Enabled {
  1198. continue
  1199. }
  1200. dstTags := convAclTagToValueMap(acl.Dst)
  1201. _, all := dstTags["*"]
  1202. addUsers := false
  1203. if !all {
  1204. for nodeTag := range targetNodeTags {
  1205. if _, ok := dstTags[nodeTag.String()]; ok {
  1206. addUsers = true
  1207. break
  1208. }
  1209. }
  1210. } else {
  1211. addUsers = true
  1212. }
  1213. if addUsers {
  1214. // get all src tags
  1215. for _, srcAcl := range acl.Src {
  1216. if srcAcl.ID == models.UserAclID {
  1217. allowedUsers[srcAcl.Value] = append(allowedUsers[srcAcl.Value], acl)
  1218. } else if srcAcl.ID == models.UserGroupAclID {
  1219. // fetch all users in the group
  1220. if usersMap, ok := userGrpMap[models.UserGroupID(srcAcl.Value)]; ok {
  1221. for userName := range usersMap {
  1222. allowedUsers[userName] = append(allowedUsers[userName], acl)
  1223. }
  1224. }
  1225. }
  1226. }
  1227. }
  1228. }
  1229. for _, userNode := range userNodes {
  1230. if !userNode.StaticNode.Enabled {
  1231. continue
  1232. }
  1233. acls, ok := allowedUsers[userNode.StaticNode.OwnerID]
  1234. if !ok {
  1235. continue
  1236. }
  1237. for _, acl := range acls {
  1238. if !acl.Enabled {
  1239. continue
  1240. }
  1241. r := models.AclRule{
  1242. ID: acl.ID,
  1243. AllowedProtocol: acl.Proto,
  1244. AllowedPorts: acl.Port,
  1245. Direction: acl.AllowedDirection,
  1246. Allowed: true,
  1247. }
  1248. // Get peers in the tags and add allowed rules
  1249. if userNode.StaticNode.Address != "" {
  1250. r.IPList = append(r.IPList, userNode.StaticNode.AddressIPNet4())
  1251. }
  1252. if userNode.StaticNode.Address6 != "" {
  1253. r.IP6List = append(r.IP6List, userNode.StaticNode.AddressIPNet6())
  1254. }
  1255. if aclRule, ok := rules[acl.ID]; ok {
  1256. aclRule.IPList = append(aclRule.IPList, r.IPList...)
  1257. aclRule.IP6List = append(aclRule.IP6List, r.IP6List...)
  1258. aclRule.IPList = UniqueIPNetList(aclRule.IPList)
  1259. aclRule.IP6List = UniqueIPNetList(aclRule.IP6List)
  1260. rules[acl.ID] = aclRule
  1261. } else {
  1262. r.IPList = UniqueIPNetList(r.IPList)
  1263. r.IP6List = UniqueIPNetList(r.IP6List)
  1264. rules[acl.ID] = r
  1265. }
  1266. }
  1267. }
  1268. return rules
  1269. }
  1270. func checkIfAnyActiveEgressPolicy(targetNode models.Node) bool {
  1271. if !targetNode.IsEgressGateway {
  1272. return false
  1273. }
  1274. var targetNodeTags = make(map[models.TagID]struct{})
  1275. if targetNode.Mutex != nil {
  1276. targetNode.Mutex.Lock()
  1277. targetNodeTags = maps.Clone(targetNode.Tags)
  1278. targetNode.Mutex.Unlock()
  1279. } else {
  1280. targetNodeTags = maps.Clone(targetNode.Tags)
  1281. }
  1282. if targetNodeTags == nil {
  1283. targetNodeTags = make(map[models.TagID]struct{})
  1284. }
  1285. targetNodeTags[models.TagID(targetNode.ID.String())] = struct{}{}
  1286. targetNodeTags["*"] = struct{}{}
  1287. acls, _ := ListAclsByNetwork(models.NetworkID(targetNode.Network))
  1288. for _, acl := range acls {
  1289. if !acl.Enabled {
  1290. continue
  1291. }
  1292. srcTags := convAclTagToValueMap(acl.Src)
  1293. dstTags := convAclTagToValueMap(acl.Dst)
  1294. for nodeTag := range targetNodeTags {
  1295. if acl.RuleType == models.DevicePolicy {
  1296. if _, ok := srcTags[nodeTag.String()]; ok {
  1297. return true
  1298. }
  1299. if _, ok := srcTags[targetNode.ID.String()]; ok {
  1300. return true
  1301. }
  1302. }
  1303. if _, ok := dstTags[nodeTag.String()]; ok {
  1304. return true
  1305. }
  1306. if _, ok := dstTags[targetNode.ID.String()]; ok {
  1307. return true
  1308. }
  1309. }
  1310. }
  1311. return false
  1312. }
  1313. func checkIfAnyPolicyisUniDirectional(targetNode models.Node) bool {
  1314. var targetNodeTags = make(map[models.TagID]struct{})
  1315. if targetNode.Mutex != nil {
  1316. targetNode.Mutex.Lock()
  1317. targetNodeTags = maps.Clone(targetNode.Tags)
  1318. targetNode.Mutex.Unlock()
  1319. } else {
  1320. targetNodeTags = maps.Clone(targetNode.Tags)
  1321. }
  1322. if targetNodeTags == nil {
  1323. targetNodeTags = make(map[models.TagID]struct{})
  1324. }
  1325. targetNodeTags[models.TagID(targetNode.ID.String())] = struct{}{}
  1326. targetNodeTags["*"] = struct{}{}
  1327. acls, _ := ListAclsByNetwork(models.NetworkID(targetNode.Network))
  1328. for _, acl := range acls {
  1329. if !acl.Enabled {
  1330. continue
  1331. }
  1332. if acl.AllowedDirection == models.TrafficDirectionBi && acl.Proto == models.ALL && acl.ServiceType == models.Any {
  1333. continue
  1334. }
  1335. if acl.Proto != models.ALL || acl.ServiceType != models.Any {
  1336. return true
  1337. }
  1338. srcTags := convAclTagToValueMap(acl.Src)
  1339. dstTags := convAclTagToValueMap(acl.Dst)
  1340. for nodeTag := range targetNodeTags {
  1341. if acl.RuleType == models.DevicePolicy {
  1342. if _, ok := srcTags[nodeTag.String()]; ok {
  1343. return true
  1344. }
  1345. if _, ok := srcTags[targetNode.ID.String()]; ok {
  1346. return true
  1347. }
  1348. }
  1349. if _, ok := dstTags[nodeTag.String()]; ok {
  1350. return true
  1351. }
  1352. if _, ok := dstTags[targetNode.ID.String()]; ok {
  1353. return true
  1354. }
  1355. }
  1356. }
  1357. return false
  1358. }
  1359. func GetAclRulesForNode(targetnodeI *models.Node) (rules map[string]models.AclRule) {
  1360. targetnode := *targetnodeI
  1361. defer func() {
  1362. if !targetnode.IsIngressGateway {
  1363. rules = getUserAclRulesForNode(&targetnode, rules)
  1364. }
  1365. }()
  1366. rules = make(map[string]models.AclRule)
  1367. var taggedNodes map[models.TagID][]models.Node
  1368. if targetnode.IsIngressGateway {
  1369. taggedNodes = GetTagMapWithNodesByNetwork(models.NetworkID(targetnode.Network), false)
  1370. } else {
  1371. taggedNodes = GetTagMapWithNodesByNetwork(models.NetworkID(targetnode.Network), true)
  1372. }
  1373. acls := listDevicePolicies(models.NetworkID(targetnode.Network))
  1374. var targetNodeTags = make(map[models.TagID]struct{})
  1375. if targetnode.Mutex != nil {
  1376. targetnode.Mutex.Lock()
  1377. targetNodeTags = maps.Clone(targetnode.Tags)
  1378. targetnode.Mutex.Unlock()
  1379. } else {
  1380. targetNodeTags = maps.Clone(targetnode.Tags)
  1381. }
  1382. if targetNodeTags == nil {
  1383. targetNodeTags = make(map[models.TagID]struct{})
  1384. }
  1385. targetNodeTags[models.TagID(targetnode.ID.String())] = struct{}{}
  1386. targetNodeTags["*"] = struct{}{}
  1387. for _, acl := range acls {
  1388. if !acl.Enabled {
  1389. continue
  1390. }
  1391. srcTags := convAclTagToValueMap(acl.Src)
  1392. dstTags := convAclTagToValueMap(acl.Dst)
  1393. _, srcAll := srcTags["*"]
  1394. _, dstAll := dstTags["*"]
  1395. aclRule := models.AclRule{
  1396. ID: acl.ID,
  1397. AllowedProtocol: acl.Proto,
  1398. AllowedPorts: acl.Port,
  1399. Direction: acl.AllowedDirection,
  1400. Allowed: true,
  1401. }
  1402. for nodeTag := range targetNodeTags {
  1403. if acl.AllowedDirection == models.TrafficDirectionBi {
  1404. var existsInSrcTag bool
  1405. var existsInDstTag bool
  1406. if _, ok := srcTags[nodeTag.String()]; ok || srcAll {
  1407. existsInSrcTag = true
  1408. }
  1409. if _, ok := srcTags[targetnode.ID.String()]; ok || srcAll {
  1410. existsInSrcTag = true
  1411. }
  1412. if _, ok := dstTags[nodeTag.String()]; ok || dstAll {
  1413. existsInDstTag = true
  1414. }
  1415. if _, ok := dstTags[targetnode.ID.String()]; ok || dstAll {
  1416. existsInDstTag = true
  1417. }
  1418. if existsInSrcTag && !existsInDstTag {
  1419. // get all dst tags
  1420. for dst := range dstTags {
  1421. if dst == nodeTag.String() {
  1422. continue
  1423. }
  1424. // Get peers in the tags and add allowed rules
  1425. nodes := taggedNodes[models.TagID(dst)]
  1426. if dst != targetnode.ID.String() {
  1427. node, err := GetNodeByID(dst)
  1428. if err == nil {
  1429. nodes = append(nodes, node)
  1430. }
  1431. }
  1432. for _, node := range nodes {
  1433. if node.ID == targetnode.ID {
  1434. continue
  1435. }
  1436. if node.IsStatic && node.StaticNode.IngressGatewayID == targetnode.ID.String() {
  1437. continue
  1438. }
  1439. if node.Address.IP != nil {
  1440. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  1441. }
  1442. if node.Address6.IP != nil {
  1443. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  1444. }
  1445. if node.IsStatic && node.StaticNode.Address != "" {
  1446. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  1447. }
  1448. if node.IsStatic && node.StaticNode.Address6 != "" {
  1449. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  1450. }
  1451. }
  1452. }
  1453. }
  1454. if existsInDstTag && !existsInSrcTag {
  1455. // get all src tags
  1456. for src := range srcTags {
  1457. if src == nodeTag.String() {
  1458. continue
  1459. }
  1460. // Get peers in the tags and add allowed rules
  1461. nodes := taggedNodes[models.TagID(src)]
  1462. if src != targetnode.ID.String() {
  1463. node, err := GetNodeByID(src)
  1464. if err == nil {
  1465. nodes = append(nodes, node)
  1466. }
  1467. }
  1468. for _, node := range nodes {
  1469. if node.ID == targetnode.ID {
  1470. continue
  1471. }
  1472. if node.IsStatic && node.StaticNode.IngressGatewayID == targetnode.ID.String() {
  1473. continue
  1474. }
  1475. if node.Address.IP != nil {
  1476. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  1477. }
  1478. if node.Address6.IP != nil {
  1479. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  1480. }
  1481. if node.IsStatic && node.StaticNode.Address != "" {
  1482. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  1483. }
  1484. if node.IsStatic && node.StaticNode.Address6 != "" {
  1485. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  1486. }
  1487. }
  1488. }
  1489. }
  1490. if existsInDstTag && existsInSrcTag {
  1491. nodes := taggedNodes[nodeTag]
  1492. for srcID := range srcTags {
  1493. if srcID == targetnode.ID.String() {
  1494. continue
  1495. }
  1496. node, err := GetNodeByID(srcID)
  1497. if err == nil {
  1498. nodes = append(nodes, node)
  1499. }
  1500. }
  1501. for dstID := range dstTags {
  1502. if dstID == targetnode.ID.String() {
  1503. continue
  1504. }
  1505. node, err := GetNodeByID(dstID)
  1506. if err == nil {
  1507. nodes = append(nodes, node)
  1508. }
  1509. }
  1510. for _, node := range nodes {
  1511. if node.ID == targetnode.ID {
  1512. continue
  1513. }
  1514. if node.IsStatic && node.StaticNode.IngressGatewayID == targetnode.ID.String() {
  1515. continue
  1516. }
  1517. if node.Address.IP != nil {
  1518. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  1519. }
  1520. if node.Address6.IP != nil {
  1521. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  1522. }
  1523. if node.IsStatic && node.StaticNode.Address != "" {
  1524. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  1525. }
  1526. if node.IsStatic && node.StaticNode.Address6 != "" {
  1527. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  1528. }
  1529. }
  1530. }
  1531. } else {
  1532. _, all := dstTags["*"]
  1533. if _, ok := dstTags[nodeTag.String()]; ok || all {
  1534. // get all src tags
  1535. for src := range srcTags {
  1536. if src == nodeTag.String() {
  1537. continue
  1538. }
  1539. // Get peers in the tags and add allowed rules
  1540. nodes := taggedNodes[models.TagID(src)]
  1541. for _, node := range nodes {
  1542. if node.ID == targetnode.ID {
  1543. continue
  1544. }
  1545. if node.IsStatic && node.StaticNode.IngressGatewayID == targetnode.ID.String() {
  1546. continue
  1547. }
  1548. if node.Address.IP != nil {
  1549. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  1550. }
  1551. if node.Address6.IP != nil {
  1552. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  1553. }
  1554. if node.IsStatic && node.StaticNode.Address != "" {
  1555. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  1556. }
  1557. if node.IsStatic && node.StaticNode.Address6 != "" {
  1558. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  1559. }
  1560. }
  1561. }
  1562. }
  1563. }
  1564. }
  1565. if len(aclRule.IPList) > 0 || len(aclRule.IP6List) > 0 {
  1566. aclRule.IPList = UniqueIPNetList(aclRule.IPList)
  1567. aclRule.IP6List = UniqueIPNetList(aclRule.IP6List)
  1568. rules[acl.ID] = aclRule
  1569. }
  1570. }
  1571. return rules
  1572. }
  1573. func GetEgressRulesForNode(targetnode models.Node) (rules map[string]models.AclRule) {
  1574. rules = make(map[string]models.AclRule)
  1575. defer func() {
  1576. rules = getEgressUserRulesForNode(&targetnode, rules)
  1577. }()
  1578. taggedNodes := GetTagMapWithNodesByNetwork(models.NetworkID(targetnode.Network), true)
  1579. acls := listDevicePolicies(models.NetworkID(targetnode.Network))
  1580. var targetNodeTags = make(map[models.TagID]struct{})
  1581. targetNodeTags["*"] = struct{}{}
  1582. /*
  1583. if target node is egress gateway
  1584. if acl policy has egress route and it is present in target node egress ranges
  1585. fetch all the nodes in that policy and add rules
  1586. */
  1587. for _, rangeI := range targetnode.EgressGatewayRanges {
  1588. targetNodeTags[models.TagID(rangeI)] = struct{}{}
  1589. }
  1590. for _, acl := range acls {
  1591. if !acl.Enabled {
  1592. continue
  1593. }
  1594. srcTags := convAclTagToValueMap(acl.Src)
  1595. dstTags := convAclTagToValueMap(acl.Dst)
  1596. _, srcAll := srcTags["*"]
  1597. _, dstAll := dstTags["*"]
  1598. for nodeTag := range targetNodeTags {
  1599. aclRule := models.AclRule{
  1600. ID: acl.ID,
  1601. AllowedProtocol: acl.Proto,
  1602. AllowedPorts: acl.Port,
  1603. Direction: acl.AllowedDirection,
  1604. Allowed: true,
  1605. }
  1606. if nodeTag != "*" {
  1607. ip, cidr, err := net.ParseCIDR(nodeTag.String())
  1608. if err != nil {
  1609. continue
  1610. }
  1611. if ip.To4() != nil {
  1612. aclRule.Dst = append(aclRule.Dst, *cidr)
  1613. } else {
  1614. aclRule.Dst6 = append(aclRule.Dst6, *cidr)
  1615. }
  1616. } else {
  1617. aclRule.Dst = append(aclRule.Dst, net.IPNet{
  1618. IP: net.IPv4zero, // 0.0.0.0
  1619. Mask: net.CIDRMask(0, 32), // /0 means match all IPv4
  1620. })
  1621. aclRule.Dst6 = append(aclRule.Dst6, net.IPNet{
  1622. IP: net.IPv6zero, // ::
  1623. Mask: net.CIDRMask(0, 128), // /0 means match all IPv6
  1624. })
  1625. }
  1626. if acl.AllowedDirection == models.TrafficDirectionBi {
  1627. var existsInSrcTag bool
  1628. var existsInDstTag bool
  1629. if _, ok := srcTags[nodeTag.String()]; ok || srcAll {
  1630. existsInSrcTag = true
  1631. }
  1632. if _, ok := dstTags[nodeTag.String()]; ok || dstAll {
  1633. existsInDstTag = true
  1634. }
  1635. if existsInSrcTag && !existsInDstTag {
  1636. // get all dst tags
  1637. for dst := range dstTags {
  1638. if dst == nodeTag.String() {
  1639. continue
  1640. }
  1641. // Get peers in the tags and add allowed rules
  1642. nodes := taggedNodes[models.TagID(dst)]
  1643. if dst != targetnode.ID.String() {
  1644. node, err := GetNodeByID(dst)
  1645. if err == nil {
  1646. nodes = append(nodes, node)
  1647. }
  1648. }
  1649. for _, node := range nodes {
  1650. if node.ID == targetnode.ID {
  1651. continue
  1652. }
  1653. if node.Address.IP != nil {
  1654. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  1655. }
  1656. if node.Address6.IP != nil {
  1657. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  1658. }
  1659. if node.IsStatic && node.StaticNode.Address != "" {
  1660. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  1661. }
  1662. if node.IsStatic && node.StaticNode.Address6 != "" {
  1663. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  1664. }
  1665. }
  1666. }
  1667. }
  1668. if existsInDstTag && !existsInSrcTag {
  1669. // get all src tags
  1670. for src := range srcTags {
  1671. if src == nodeTag.String() {
  1672. continue
  1673. }
  1674. // Get peers in the tags and add allowed rules
  1675. nodes := taggedNodes[models.TagID(src)]
  1676. if src != targetnode.ID.String() {
  1677. node, err := GetNodeByID(src)
  1678. if err == nil {
  1679. nodes = append(nodes, node)
  1680. }
  1681. }
  1682. for _, node := range nodes {
  1683. if node.ID == targetnode.ID {
  1684. continue
  1685. }
  1686. if node.Address.IP != nil {
  1687. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  1688. }
  1689. if node.Address6.IP != nil {
  1690. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  1691. }
  1692. if node.IsStatic && node.StaticNode.Address != "" {
  1693. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  1694. }
  1695. if node.IsStatic && node.StaticNode.Address6 != "" {
  1696. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  1697. }
  1698. }
  1699. }
  1700. }
  1701. if existsInDstTag && existsInSrcTag {
  1702. nodes := taggedNodes[nodeTag]
  1703. for srcID := range srcTags {
  1704. if srcID == targetnode.ID.String() {
  1705. continue
  1706. }
  1707. node, err := GetNodeByID(srcID)
  1708. if err == nil {
  1709. nodes = append(nodes, node)
  1710. }
  1711. }
  1712. for dstID := range dstTags {
  1713. if dstID == targetnode.ID.String() {
  1714. continue
  1715. }
  1716. node, err := GetNodeByID(dstID)
  1717. if err == nil {
  1718. nodes = append(nodes, node)
  1719. }
  1720. }
  1721. for _, node := range nodes {
  1722. if node.ID == targetnode.ID {
  1723. continue
  1724. }
  1725. if node.Address.IP != nil {
  1726. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  1727. }
  1728. if node.Address6.IP != nil {
  1729. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  1730. }
  1731. if node.IsStatic && node.StaticNode.Address != "" {
  1732. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  1733. }
  1734. if node.IsStatic && node.StaticNode.Address6 != "" {
  1735. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  1736. }
  1737. }
  1738. }
  1739. } else {
  1740. _, all := dstTags["*"]
  1741. if _, ok := dstTags[nodeTag.String()]; ok || all {
  1742. // get all src tags
  1743. for src := range srcTags {
  1744. if src == nodeTag.String() {
  1745. continue
  1746. }
  1747. // Get peers in the tags and add allowed rules
  1748. nodes := taggedNodes[models.TagID(src)]
  1749. for _, node := range nodes {
  1750. if node.ID == targetnode.ID {
  1751. continue
  1752. }
  1753. if node.Address.IP != nil {
  1754. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  1755. }
  1756. if node.Address6.IP != nil {
  1757. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  1758. }
  1759. if node.IsStatic && node.StaticNode.Address != "" {
  1760. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  1761. }
  1762. if node.IsStatic && node.StaticNode.Address6 != "" {
  1763. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  1764. }
  1765. }
  1766. }
  1767. }
  1768. }
  1769. if len(aclRule.IPList) > 0 || len(aclRule.IP6List) > 0 {
  1770. aclRule.IPList = UniqueIPNetList(aclRule.IPList)
  1771. aclRule.IP6List = UniqueIPNetList(aclRule.IP6List)
  1772. rules[acl.ID] = aclRule
  1773. }
  1774. }
  1775. }
  1776. return
  1777. }
  1778. // Compare two IPs and return true if ip1 < ip2
  1779. func lessIP(ip1, ip2 net.IP) bool {
  1780. ip1 = ip1.To16() // Ensure IPv4 is converted to IPv6-mapped format
  1781. ip2 = ip2.To16()
  1782. return string(ip1) < string(ip2)
  1783. }
  1784. // Sort by IP first, then by prefix length
  1785. func sortIPNets(ipNets []net.IPNet) {
  1786. sort.Slice(ipNets, func(i, j int) bool {
  1787. ip1, ip2 := ipNets[i].IP, ipNets[j].IP
  1788. mask1, _ := ipNets[i].Mask.Size()
  1789. mask2, _ := ipNets[j].Mask.Size()
  1790. // Compare IPs first
  1791. if ip1.Equal(ip2) {
  1792. return mask1 < mask2 // If same IP, sort by subnet mask size
  1793. }
  1794. return lessIP(ip1, ip2)
  1795. })
  1796. }
  1797. func UniqueIPNetList(ipnets []net.IPNet) []net.IPNet {
  1798. uniqueMap := make(map[string]net.IPNet)
  1799. for _, ipnet := range ipnets {
  1800. key := ipnet.String() // Uses CIDR notation as a unique key
  1801. if _, exists := uniqueMap[key]; !exists {
  1802. uniqueMap[key] = ipnet
  1803. }
  1804. }
  1805. // Convert map back to slice
  1806. uniqueList := make([]net.IPNet, 0, len(uniqueMap))
  1807. for _, ipnet := range uniqueMap {
  1808. uniqueList = append(uniqueList, ipnet)
  1809. }
  1810. sortIPNets(uniqueList)
  1811. return uniqueList
  1812. }