acls.go 46 KB

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