acls.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  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.DeviceAclID,
  50. Value: "*",
  51. }},
  52. Dst: []models.AclPolicyTag{
  53. {
  54. ID: models.DeviceAclID,
  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.DeviceAclID,
  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-remote-access-gws")) {
  93. defaultUserAcl := models.Acl{
  94. ID: fmt.Sprintf("%s.%s", netID, "all-remote-access-gws"),
  95. Default: true,
  96. Name: "All Remote Access 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.DeviceAclID,
  105. Value: fmt.Sprintf("%s.%s", netID, models.RemoteAccessTagName),
  106. },
  107. },
  108. Dst: []models.AclPolicyTag{
  109. {
  110. ID: models.DeviceAclID,
  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. // DeleteDefaultNetworkPolicies - deletes all default network acl policies
  124. func DeleteDefaultNetworkPolicies(netId models.NetworkID) {
  125. acls, _ := ListAclsByNetwork(netId)
  126. for _, acl := range acls {
  127. if acl.NetworkID == netId && acl.Default {
  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. // IsAclPolicyValid - validates if acl policy is valid
  210. func IsAclPolicyValid(acl models.Acl) bool {
  211. //check if src and dst are valid
  212. if acl.AllowedDirection != models.TrafficDirectionBi &&
  213. acl.AllowedDirection != models.TrafficDirectionUni {
  214. return false
  215. }
  216. switch acl.RuleType {
  217. case models.UserPolicy:
  218. // src list should only contain users
  219. for _, srcI := range acl.Src {
  220. if srcI.ID == "" || srcI.Value == "" {
  221. return false
  222. }
  223. if srcI.Value == "*" {
  224. continue
  225. }
  226. if srcI.ID != models.UserAclID && srcI.ID != models.UserGroupAclID {
  227. return false
  228. }
  229. // check if user group is valid
  230. if srcI.ID == models.UserAclID {
  231. _, err := GetUser(srcI.Value)
  232. if err != nil {
  233. return false
  234. }
  235. } else if srcI.ID == models.UserGroupAclID {
  236. err := IsGroupValid(models.UserGroupID(srcI.Value))
  237. if err != nil {
  238. return false
  239. }
  240. // check if group belongs to this network
  241. netGrps := GetUserGroupsInNetwork(acl.NetworkID)
  242. if _, ok := netGrps[models.UserGroupID(srcI.Value)]; !ok {
  243. return false
  244. }
  245. }
  246. }
  247. for _, dstI := range acl.Dst {
  248. if dstI.ID == "" || dstI.Value == "" {
  249. return false
  250. }
  251. if dstI.ID != models.DeviceAclID {
  252. return false
  253. }
  254. if dstI.Value == "*" {
  255. continue
  256. }
  257. // check if tag is valid
  258. _, err := GetTag(models.TagID(dstI.Value))
  259. if err != nil {
  260. return false
  261. }
  262. }
  263. case models.DevicePolicy:
  264. for _, srcI := range acl.Src {
  265. if srcI.ID == "" || srcI.Value == "" {
  266. return false
  267. }
  268. if srcI.ID != models.DeviceAclID {
  269. return false
  270. }
  271. if srcI.Value == "*" {
  272. continue
  273. }
  274. // check if tag is valid
  275. _, err := GetTag(models.TagID(srcI.Value))
  276. if err != nil {
  277. return false
  278. }
  279. }
  280. for _, dstI := range acl.Dst {
  281. if dstI.ID == "" || dstI.Value == "" {
  282. return false
  283. }
  284. if dstI.ID != models.DeviceAclID {
  285. return false
  286. }
  287. if dstI.Value == "*" {
  288. continue
  289. }
  290. // check if tag is valid
  291. _, err := GetTag(models.TagID(dstI.Value))
  292. if err != nil {
  293. return false
  294. }
  295. }
  296. }
  297. return true
  298. }
  299. // UpdateAcl - updates allowed fields on acls and commits to DB
  300. func UpdateAcl(newAcl, acl models.Acl) error {
  301. if !acl.Default {
  302. acl.Name = newAcl.Name
  303. acl.Src = newAcl.Src
  304. acl.Dst = newAcl.Dst
  305. acl.AllowedDirection = newAcl.AllowedDirection
  306. acl.Port = newAcl.Port
  307. acl.Proto = newAcl.Proto
  308. acl.ServiceType = newAcl.ServiceType
  309. }
  310. if newAcl.ServiceType == models.Any {
  311. acl.Port = []string{}
  312. acl.Proto = models.ALL
  313. }
  314. acl.Enabled = newAcl.Enabled
  315. d, err := json.Marshal(acl)
  316. if err != nil {
  317. return err
  318. }
  319. err = database.Insert(acl.ID, string(d), database.ACLS_TABLE_NAME)
  320. if err == nil && servercfg.CacheEnabled() {
  321. storeAclInCache(acl)
  322. }
  323. return err
  324. }
  325. // UpsertAcl - upserts acl
  326. func UpsertAcl(acl models.Acl) error {
  327. d, err := json.Marshal(acl)
  328. if err != nil {
  329. return err
  330. }
  331. err = database.Insert(acl.ID, string(d), database.ACLS_TABLE_NAME)
  332. if err == nil && servercfg.CacheEnabled() {
  333. storeAclInCache(acl)
  334. }
  335. return err
  336. }
  337. // DeleteAcl - deletes acl policy
  338. func DeleteAcl(a models.Acl) error {
  339. err := database.DeleteRecord(database.ACLS_TABLE_NAME, a.ID)
  340. if err == nil && servercfg.CacheEnabled() {
  341. removeAclFromCache(a)
  342. }
  343. return err
  344. }
  345. // GetDefaultPolicy - fetches default policy in the network by ruleType
  346. func GetDefaultPolicy(netID models.NetworkID, ruleType models.AclPolicyType) (models.Acl, error) {
  347. aclID := "all-users"
  348. if ruleType == models.DevicePolicy {
  349. aclID = "all-nodes"
  350. }
  351. acl, err := GetAcl(fmt.Sprintf("%s.%s", netID, aclID))
  352. if err != nil {
  353. return models.Acl{}, errors.New("default rule not found")
  354. }
  355. if acl.Enabled {
  356. return acl, nil
  357. }
  358. // check if there are any custom all policies
  359. srcMap := make(map[string]struct{})
  360. dstMap := make(map[string]struct{})
  361. defer func() {
  362. srcMap = nil
  363. dstMap = nil
  364. }()
  365. policies, _ := ListAclsByNetwork(netID)
  366. for _, policy := range policies {
  367. if !policy.Enabled {
  368. continue
  369. }
  370. if policy.RuleType == ruleType {
  371. dstMap = convAclTagToValueMap(policy.Dst)
  372. srcMap = convAclTagToValueMap(policy.Src)
  373. if _, ok := srcMap["*"]; ok {
  374. if _, ok := dstMap["*"]; ok {
  375. return policy, nil
  376. }
  377. }
  378. }
  379. }
  380. return acl, nil
  381. }
  382. func ListAcls() (acls []models.Acl) {
  383. if servercfg.CacheEnabled() && len(aclCacheMap) > 0 {
  384. return listAclFromCache()
  385. }
  386. data, err := database.FetchRecords(database.ACLS_TABLE_NAME)
  387. if err != nil && !database.IsEmptyRecord(err) {
  388. return []models.Acl{}
  389. }
  390. for _, dataI := range data {
  391. acl := models.Acl{}
  392. err := json.Unmarshal([]byte(dataI), &acl)
  393. if err != nil {
  394. continue
  395. }
  396. acls = append(acls, acl)
  397. if servercfg.CacheEnabled() {
  398. storeAclInCache(acl)
  399. }
  400. }
  401. return
  402. }
  403. // ListUserPolicies - lists all acl policies enforced on an user
  404. func ListUserPolicies(u models.User) []models.Acl {
  405. allAcls := ListAcls()
  406. userAcls := []models.Acl{}
  407. for _, acl := range allAcls {
  408. if acl.RuleType == models.UserPolicy {
  409. srcMap := convAclTagToValueMap(acl.Src)
  410. if _, ok := srcMap[u.UserName]; ok {
  411. userAcls = append(userAcls, acl)
  412. } else {
  413. // check for user groups
  414. for gID := range u.UserGroups {
  415. if _, ok := srcMap[gID.String()]; ok {
  416. userAcls = append(userAcls, acl)
  417. break
  418. }
  419. }
  420. }
  421. }
  422. }
  423. return userAcls
  424. }
  425. // listPoliciesOfUser - lists all user acl policies applied to user in an network
  426. func listPoliciesOfUser(user models.User, netID models.NetworkID) []models.Acl {
  427. allAcls := ListAcls()
  428. userAcls := []models.Acl{}
  429. for _, acl := range allAcls {
  430. if acl.NetworkID == netID && acl.RuleType == models.UserPolicy {
  431. srcMap := convAclTagToValueMap(acl.Src)
  432. if _, ok := srcMap[user.UserName]; ok {
  433. userAcls = append(userAcls, acl)
  434. continue
  435. }
  436. for netRole := range user.NetworkRoles {
  437. if _, ok := srcMap[netRole.String()]; ok {
  438. userAcls = append(userAcls, acl)
  439. continue
  440. }
  441. }
  442. for userG := range user.UserGroups {
  443. if _, ok := srcMap[userG.String()]; ok {
  444. userAcls = append(userAcls, acl)
  445. continue
  446. }
  447. }
  448. }
  449. }
  450. return userAcls
  451. }
  452. // listDevicePolicies - lists all device policies in a network
  453. func listDevicePolicies(netID models.NetworkID) []models.Acl {
  454. allAcls := ListAcls()
  455. deviceAcls := []models.Acl{}
  456. for _, acl := range allAcls {
  457. if acl.NetworkID == netID && acl.RuleType == models.DevicePolicy {
  458. deviceAcls = append(deviceAcls, acl)
  459. }
  460. }
  461. return deviceAcls
  462. }
  463. // listUserPolicies - lists all user policies in a network
  464. func listUserPolicies(netID models.NetworkID) []models.Acl {
  465. allAcls := ListAcls()
  466. deviceAcls := []models.Acl{}
  467. for _, acl := range allAcls {
  468. if acl.NetworkID == netID && acl.RuleType == models.UserPolicy {
  469. deviceAcls = append(deviceAcls, acl)
  470. }
  471. }
  472. return deviceAcls
  473. }
  474. // ListAcls - lists all acl policies
  475. func ListAclsByNetwork(netID models.NetworkID) ([]models.Acl, error) {
  476. allAcls := ListAcls()
  477. netAcls := []models.Acl{}
  478. for _, acl := range allAcls {
  479. if acl.NetworkID == netID {
  480. netAcls = append(netAcls, acl)
  481. }
  482. }
  483. return netAcls, nil
  484. }
  485. func convAclTagToValueMap(acltags []models.AclPolicyTag) map[string]struct{} {
  486. aclValueMap := make(map[string]struct{})
  487. for _, aclTagI := range acltags {
  488. aclValueMap[aclTagI.Value] = struct{}{}
  489. }
  490. return aclValueMap
  491. }
  492. // IsUserAllowedToCommunicate - check if user is allowed to communicate with peer
  493. func IsUserAllowedToCommunicate(userName string, peer models.Node) (bool, []models.Acl) {
  494. if peer.IsStatic {
  495. peer = peer.StaticNode.ConvertToStaticNode()
  496. }
  497. acl, _ := GetDefaultPolicy(models.NetworkID(peer.Network), models.UserPolicy)
  498. if acl.Enabled {
  499. return true, []models.Acl{acl}
  500. }
  501. user, err := GetUser(userName)
  502. if err != nil {
  503. return false, []models.Acl{}
  504. }
  505. allowedPolicies := []models.Acl{}
  506. policies := listPoliciesOfUser(*user, models.NetworkID(peer.Network))
  507. for _, policy := range policies {
  508. if !policy.Enabled {
  509. continue
  510. }
  511. dstMap := convAclTagToValueMap(policy.Dst)
  512. if _, ok := dstMap["*"]; ok {
  513. allowedPolicies = append(allowedPolicies, policy)
  514. continue
  515. }
  516. for tagID := range peer.Tags {
  517. if _, ok := dstMap[tagID.String()]; ok {
  518. allowedPolicies = append(allowedPolicies, policy)
  519. break
  520. }
  521. }
  522. }
  523. if len(allowedPolicies) > 0 {
  524. return true, allowedPolicies
  525. }
  526. return false, []models.Acl{}
  527. }
  528. // IsPeerAllowed - checks if peer needs to be added to the interface
  529. func IsPeerAllowed(node, peer models.Node, checkDefaultPolicy bool) bool {
  530. if node.IsStatic {
  531. node = node.StaticNode.ConvertToStaticNode()
  532. }
  533. if peer.IsStatic {
  534. peer = peer.StaticNode.ConvertToStaticNode()
  535. }
  536. var nodeTags, peerTags map[models.TagID]struct{}
  537. if node.Mutex != nil {
  538. node.Mutex.Lock()
  539. nodeTags = maps.Clone(node.Tags)
  540. node.Mutex.Unlock()
  541. } else {
  542. nodeTags = node.Tags
  543. }
  544. if peer.Mutex != nil {
  545. peer.Mutex.Lock()
  546. peerTags = maps.Clone(peer.Tags)
  547. peer.Mutex.Unlock()
  548. } else {
  549. peerTags = peer.Tags
  550. }
  551. if checkDefaultPolicy {
  552. // check default policy if all allowed return true
  553. defaultPolicy, err := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  554. if err == nil {
  555. if defaultPolicy.Enabled {
  556. return true
  557. }
  558. }
  559. }
  560. // list device policies
  561. policies := listDevicePolicies(models.NetworkID(peer.Network))
  562. srcMap := make(map[string]struct{})
  563. dstMap := make(map[string]struct{})
  564. defer func() {
  565. srcMap = nil
  566. dstMap = nil
  567. }()
  568. for _, policy := range policies {
  569. if !policy.Enabled {
  570. continue
  571. }
  572. srcMap = convAclTagToValueMap(policy.Src)
  573. dstMap = convAclTagToValueMap(policy.Dst)
  574. for tagID := range nodeTags {
  575. if _, ok := dstMap[tagID.String()]; ok {
  576. if _, ok := srcMap["*"]; ok {
  577. return true
  578. }
  579. for tagID := range peerTags {
  580. if _, ok := srcMap[tagID.String()]; ok {
  581. return true
  582. }
  583. }
  584. }
  585. if _, ok := srcMap[tagID.String()]; ok {
  586. if _, ok := dstMap["*"]; ok {
  587. return true
  588. }
  589. for tagID := range peerTags {
  590. if _, ok := dstMap[tagID.String()]; ok {
  591. return true
  592. }
  593. }
  594. }
  595. }
  596. for tagID := range peerTags {
  597. if _, ok := dstMap[tagID.String()]; ok {
  598. if _, ok := srcMap["*"]; ok {
  599. return true
  600. }
  601. for tagID := range nodeTags {
  602. if _, ok := srcMap[tagID.String()]; ok {
  603. return true
  604. }
  605. }
  606. }
  607. if _, ok := srcMap[tagID.String()]; ok {
  608. if _, ok := dstMap["*"]; ok {
  609. return true
  610. }
  611. for tagID := range nodeTags {
  612. if _, ok := dstMap[tagID.String()]; ok {
  613. return true
  614. }
  615. }
  616. }
  617. }
  618. }
  619. return false
  620. }
  621. // IsNodeAllowedToCommunicate - check node is allowed to communicate with the peer
  622. func IsNodeAllowedToCommunicate(node, peer models.Node, checkDefaultPolicy bool) (bool, []models.Acl) {
  623. if node.IsStatic {
  624. node = node.StaticNode.ConvertToStaticNode()
  625. }
  626. if peer.IsStatic {
  627. peer = peer.StaticNode.ConvertToStaticNode()
  628. }
  629. var nodeTags, peerTags map[models.TagID]struct{}
  630. if node.Mutex != nil {
  631. node.Mutex.Lock()
  632. nodeTags = maps.Clone(node.Tags)
  633. node.Mutex.Unlock()
  634. } else {
  635. nodeTags = node.Tags
  636. }
  637. if peer.Mutex != nil {
  638. peer.Mutex.Lock()
  639. peerTags = maps.Clone(peer.Tags)
  640. peer.Mutex.Unlock()
  641. } else {
  642. peerTags = peer.Tags
  643. }
  644. if checkDefaultPolicy {
  645. // check default policy if all allowed return true
  646. defaultPolicy, err := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  647. if err == nil {
  648. if defaultPolicy.Enabled {
  649. return true, []models.Acl{defaultPolicy}
  650. }
  651. }
  652. }
  653. allowedPolicies := []models.Acl{}
  654. // list device policies
  655. policies := listDevicePolicies(models.NetworkID(peer.Network))
  656. srcMap := make(map[string]struct{})
  657. dstMap := make(map[string]struct{})
  658. defer func() {
  659. srcMap = nil
  660. dstMap = nil
  661. }()
  662. for _, policy := range policies {
  663. if !policy.Enabled {
  664. continue
  665. }
  666. srcMap = convAclTagToValueMap(policy.Src)
  667. dstMap = convAclTagToValueMap(policy.Dst)
  668. for tagID := range nodeTags {
  669. allowed := false
  670. if _, ok := dstMap[tagID.String()]; policy.AllowedDirection == models.TrafficDirectionBi && ok {
  671. if _, ok := srcMap["*"]; ok {
  672. allowed = true
  673. allowedPolicies = append(allowedPolicies, policy)
  674. break
  675. }
  676. for tagID := range peerTags {
  677. if _, ok := srcMap[tagID.String()]; ok {
  678. allowed = true
  679. break
  680. }
  681. }
  682. }
  683. if allowed {
  684. allowedPolicies = append(allowedPolicies, policy)
  685. break
  686. }
  687. if _, ok := srcMap[tagID.String()]; ok {
  688. if _, ok := dstMap["*"]; ok {
  689. allowed = true
  690. allowedPolicies = append(allowedPolicies, policy)
  691. break
  692. }
  693. for tagID := range peerTags {
  694. if _, ok := dstMap[tagID.String()]; ok {
  695. allowed = true
  696. break
  697. }
  698. }
  699. }
  700. if allowed {
  701. allowedPolicies = append(allowedPolicies, policy)
  702. break
  703. }
  704. }
  705. for tagID := range peerTags {
  706. allowed := false
  707. if _, ok := dstMap[tagID.String()]; ok {
  708. if _, ok := srcMap["*"]; ok {
  709. allowed = true
  710. allowedPolicies = append(allowedPolicies, policy)
  711. break
  712. }
  713. for tagID := range nodeTags {
  714. if _, ok := srcMap[tagID.String()]; ok {
  715. allowed = true
  716. break
  717. }
  718. }
  719. }
  720. if allowed {
  721. allowedPolicies = append(allowedPolicies, policy)
  722. break
  723. }
  724. if _, ok := srcMap[tagID.String()]; policy.AllowedDirection == models.TrafficDirectionBi && ok {
  725. if _, ok := dstMap["*"]; ok {
  726. allowed = true
  727. allowedPolicies = append(allowedPolicies, policy)
  728. break
  729. }
  730. for tagID := range nodeTags {
  731. if _, ok := dstMap[tagID.String()]; ok {
  732. allowed = true
  733. break
  734. }
  735. }
  736. }
  737. if allowed {
  738. allowedPolicies = append(allowedPolicies, policy)
  739. break
  740. }
  741. }
  742. }
  743. if len(allowedPolicies) > 0 {
  744. return true, allowedPolicies
  745. }
  746. return false, allowedPolicies
  747. }
  748. // SortTagEntrys - Sorts slice of Tag entries by their id
  749. func SortAclEntrys(acls []models.Acl) {
  750. sort.Slice(acls, func(i, j int) bool {
  751. return acls[i].Name < acls[j].Name
  752. })
  753. }
  754. // UpdateDeviceTag - updates device tag on acl policies
  755. func UpdateDeviceTag(OldID, newID models.TagID, netID models.NetworkID) {
  756. acls := listDevicePolicies(netID)
  757. update := false
  758. for _, acl := range acls {
  759. for i, srcTagI := range acl.Src {
  760. if srcTagI.ID == models.DeviceAclID {
  761. if OldID.String() == srcTagI.Value {
  762. acl.Src[i].Value = newID.String()
  763. update = true
  764. }
  765. }
  766. }
  767. for i, dstTagI := range acl.Dst {
  768. if dstTagI.ID == models.DeviceAclID {
  769. if OldID.String() == dstTagI.Value {
  770. acl.Dst[i].Value = newID.String()
  771. update = true
  772. }
  773. }
  774. }
  775. if update {
  776. UpsertAcl(acl)
  777. }
  778. }
  779. }
  780. func CheckIfTagAsActivePolicy(tagID models.TagID, netID models.NetworkID) bool {
  781. acls := listDevicePolicies(netID)
  782. for _, acl := range acls {
  783. for _, srcTagI := range acl.Src {
  784. if srcTagI.ID == models.DeviceAclID {
  785. if tagID.String() == srcTagI.Value {
  786. return true
  787. }
  788. }
  789. }
  790. for _, dstTagI := range acl.Dst {
  791. if dstTagI.ID == models.DeviceAclID {
  792. if tagID.String() == dstTagI.Value {
  793. return true
  794. }
  795. }
  796. }
  797. }
  798. return false
  799. }
  800. // RemoveDeviceTagFromAclPolicies - remove device tag from acl policies
  801. func RemoveDeviceTagFromAclPolicies(tagID models.TagID, netID models.NetworkID) error {
  802. acls := listDevicePolicies(netID)
  803. update := false
  804. for _, acl := range acls {
  805. for i, srcTagI := range acl.Src {
  806. if srcTagI.ID == models.DeviceAclID {
  807. if tagID.String() == srcTagI.Value {
  808. acl.Src = append(acl.Src[:i], acl.Src[i+1:]...)
  809. update = true
  810. }
  811. }
  812. }
  813. for i, dstTagI := range acl.Dst {
  814. if dstTagI.ID == models.DeviceAclID {
  815. if tagID.String() == dstTagI.Value {
  816. acl.Dst = append(acl.Dst[:i], acl.Dst[i+1:]...)
  817. update = true
  818. }
  819. }
  820. }
  821. if update {
  822. UpsertAcl(acl)
  823. }
  824. }
  825. return nil
  826. }
  827. func getUserAclRulesForNode(targetnode *models.Node,
  828. rules map[string]models.AclRule) map[string]models.AclRule {
  829. userNodes := GetStaticUserNodesByNetwork(models.NetworkID(targetnode.Network))
  830. userGrpMap := GetUserGrpMap()
  831. allowedUsers := make(map[string][]models.Acl)
  832. acls := listUserPolicies(models.NetworkID(targetnode.Network))
  833. var targetNodeTags = make(map[models.TagID]struct{})
  834. if targetnode.Mutex != nil {
  835. targetnode.Mutex.Lock()
  836. targetNodeTags = maps.Clone(targetnode.Tags)
  837. targetnode.Mutex.Unlock()
  838. } else {
  839. targetNodeTags = maps.Clone(targetnode.Tags)
  840. }
  841. for nodeTag := range targetNodeTags {
  842. for _, acl := range acls {
  843. if !acl.Enabled {
  844. continue
  845. }
  846. dstTags := convAclTagToValueMap(acl.Dst)
  847. if _, ok := dstTags[nodeTag.String()]; ok {
  848. // get all src tags
  849. for _, srcAcl := range acl.Src {
  850. if srcAcl.ID == models.UserAclID {
  851. allowedUsers[srcAcl.Value] = append(allowedUsers[srcAcl.Value], acl)
  852. } else if srcAcl.ID == models.UserGroupAclID {
  853. // fetch all users in the group
  854. if usersMap, ok := userGrpMap[models.UserGroupID(srcAcl.Value)]; ok {
  855. for userName := range usersMap {
  856. allowedUsers[userName] = append(allowedUsers[userName], acl)
  857. }
  858. }
  859. }
  860. }
  861. }
  862. }
  863. }
  864. for _, userNode := range userNodes {
  865. if !userNode.StaticNode.Enabled {
  866. continue
  867. }
  868. acls, ok := allowedUsers[userNode.StaticNode.OwnerID]
  869. if !ok {
  870. continue
  871. }
  872. for _, acl := range acls {
  873. if !acl.Enabled {
  874. continue
  875. }
  876. r := models.AclRule{
  877. ID: acl.ID,
  878. AllowedProtocol: acl.Proto,
  879. AllowedPorts: acl.Port,
  880. Direction: acl.AllowedDirection,
  881. Allowed: true,
  882. }
  883. // Get peers in the tags and add allowed rules
  884. if userNode.StaticNode.Address != "" {
  885. r.IPList = append(r.IPList, userNode.StaticNode.AddressIPNet4())
  886. }
  887. if userNode.StaticNode.Address6 != "" {
  888. r.IP6List = append(r.IP6List, userNode.StaticNode.AddressIPNet6())
  889. }
  890. if aclRule, ok := rules[acl.ID]; ok {
  891. aclRule.IPList = append(aclRule.IPList, r.IPList...)
  892. aclRule.IP6List = append(aclRule.IP6List, r.IP6List...)
  893. aclRule.IPList = UniqueIPNetList(aclRule.IPList)
  894. aclRule.IP6List = UniqueIPNetList(aclRule.IP6List)
  895. rules[acl.ID] = aclRule
  896. } else {
  897. r.IPList = UniqueIPNetList(r.IPList)
  898. r.IP6List = UniqueIPNetList(r.IP6List)
  899. rules[acl.ID] = r
  900. }
  901. }
  902. }
  903. return rules
  904. }
  905. func GetAclRulesForNode(targetnode *models.Node) (rules map[string]models.AclRule) {
  906. defer func() {
  907. if !targetnode.IsIngressGateway {
  908. rules = getUserAclRulesForNode(targetnode, rules)
  909. }
  910. }()
  911. rules = make(map[string]models.AclRule)
  912. var taggedNodes map[models.TagID][]models.Node
  913. if targetnode.IsIngressGateway {
  914. taggedNodes = GetTagMapWithNodesByNetwork(models.NetworkID(targetnode.Network), false)
  915. } else {
  916. taggedNodes = GetTagMapWithNodesByNetwork(models.NetworkID(targetnode.Network), true)
  917. }
  918. acls := listDevicePolicies(models.NetworkID(targetnode.Network))
  919. var targetNodeTags = make(map[models.TagID]struct{})
  920. if targetnode.Mutex != nil {
  921. targetnode.Mutex.Lock()
  922. targetNodeTags = maps.Clone(targetnode.Tags)
  923. targetnode.Mutex.Unlock()
  924. } else {
  925. targetNodeTags = maps.Clone(targetnode.Tags)
  926. }
  927. targetNodeTags["*"] = struct{}{}
  928. for nodeTag := range targetNodeTags {
  929. for _, acl := range acls {
  930. if !acl.Enabled {
  931. continue
  932. }
  933. srcTags := convAclTagToValueMap(acl.Src)
  934. dstTags := convAclTagToValueMap(acl.Dst)
  935. aclRule := models.AclRule{
  936. ID: acl.ID,
  937. AllowedProtocol: acl.Proto,
  938. AllowedPorts: acl.Port,
  939. Direction: acl.AllowedDirection,
  940. Allowed: true,
  941. }
  942. if acl.AllowedDirection == models.TrafficDirectionBi {
  943. var existsInSrcTag bool
  944. var existsInDstTag bool
  945. if _, ok := srcTags[nodeTag.String()]; ok {
  946. existsInSrcTag = true
  947. }
  948. if _, ok := dstTags[nodeTag.String()]; ok {
  949. existsInDstTag = true
  950. }
  951. if existsInSrcTag && !existsInDstTag {
  952. // get all dst tags
  953. for dst := range dstTags {
  954. if dst == nodeTag.String() {
  955. continue
  956. }
  957. // Get peers in the tags and add allowed rules
  958. nodes := taggedNodes[models.TagID(dst)]
  959. for _, node := range nodes {
  960. if node.ID == targetnode.ID {
  961. continue
  962. }
  963. if node.Address.IP != nil {
  964. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  965. }
  966. if node.Address6.IP != nil {
  967. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  968. }
  969. if node.IsStatic && node.StaticNode.Address != "" {
  970. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  971. }
  972. if node.IsStatic && node.StaticNode.Address6 != "" {
  973. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  974. }
  975. }
  976. }
  977. }
  978. if existsInDstTag && !existsInSrcTag {
  979. // get all src tags
  980. for src := range srcTags {
  981. if src == nodeTag.String() {
  982. continue
  983. }
  984. // Get peers in the tags and add allowed rules
  985. nodes := taggedNodes[models.TagID(src)]
  986. for _, node := range nodes {
  987. if node.ID == targetnode.ID {
  988. continue
  989. }
  990. if node.Address.IP != nil {
  991. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  992. }
  993. if node.Address6.IP != nil {
  994. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  995. }
  996. if node.IsStatic && node.StaticNode.Address != "" {
  997. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  998. }
  999. if node.IsStatic && node.StaticNode.Address6 != "" {
  1000. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  1001. }
  1002. }
  1003. }
  1004. }
  1005. if existsInDstTag && existsInSrcTag {
  1006. nodes := taggedNodes[nodeTag]
  1007. for _, node := range nodes {
  1008. if node.ID == targetnode.ID {
  1009. continue
  1010. }
  1011. if node.Address.IP != nil {
  1012. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  1013. }
  1014. if node.Address6.IP != nil {
  1015. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  1016. }
  1017. if node.IsStatic && node.StaticNode.Address != "" {
  1018. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  1019. }
  1020. if node.IsStatic && node.StaticNode.Address6 != "" {
  1021. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  1022. }
  1023. }
  1024. }
  1025. } else {
  1026. _, all := dstTags["*"]
  1027. if _, ok := dstTags[nodeTag.String()]; ok || all {
  1028. // get all src tags
  1029. for src := range srcTags {
  1030. if src == nodeTag.String() {
  1031. continue
  1032. }
  1033. // Get peers in the tags and add allowed rules
  1034. nodes := taggedNodes[models.TagID(src)]
  1035. for _, node := range nodes {
  1036. if node.ID == targetnode.ID {
  1037. continue
  1038. }
  1039. if node.Address.IP != nil {
  1040. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  1041. }
  1042. if node.Address6.IP != nil {
  1043. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  1044. }
  1045. if node.IsStatic && node.StaticNode.Address != "" {
  1046. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  1047. }
  1048. if node.IsStatic && node.StaticNode.Address6 != "" {
  1049. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  1050. }
  1051. }
  1052. }
  1053. }
  1054. }
  1055. if len(aclRule.IPList) > 0 || len(aclRule.IP6List) > 0 {
  1056. aclRule.IPList = UniqueIPNetList(aclRule.IPList)
  1057. aclRule.IP6List = UniqueIPNetList(aclRule.IP6List)
  1058. rules[acl.ID] = aclRule
  1059. }
  1060. }
  1061. }
  1062. return rules
  1063. }
  1064. // Compare two IPs and return true if ip1 < ip2
  1065. func lessIP(ip1, ip2 net.IP) bool {
  1066. ip1 = ip1.To16() // Ensure IPv4 is converted to IPv6-mapped format
  1067. ip2 = ip2.To16()
  1068. return string(ip1) < string(ip2)
  1069. }
  1070. // Sort by IP first, then by prefix length
  1071. func sortIPNets(ipNets []net.IPNet) {
  1072. sort.Slice(ipNets, func(i, j int) bool {
  1073. ip1, ip2 := ipNets[i].IP, ipNets[j].IP
  1074. mask1, _ := ipNets[i].Mask.Size()
  1075. mask2, _ := ipNets[j].Mask.Size()
  1076. // Compare IPs first
  1077. if ip1.Equal(ip2) {
  1078. return mask1 < mask2 // If same IP, sort by subnet mask size
  1079. }
  1080. return lessIP(ip1, ip2)
  1081. })
  1082. }
  1083. func UniqueIPNetList(ipnets []net.IPNet) []net.IPNet {
  1084. uniqueMap := make(map[string]net.IPNet)
  1085. for _, ipnet := range ipnets {
  1086. key := ipnet.String() // Uses CIDR notation as a unique key
  1087. if _, exists := uniqueMap[key]; !exists {
  1088. uniqueMap[key] = ipnet
  1089. }
  1090. }
  1091. // Convert map back to slice
  1092. uniqueList := make([]net.IPNet, 0, len(uniqueMap))
  1093. for _, ipnet := range uniqueMap {
  1094. uniqueList = append(uniqueList, ipnet)
  1095. }
  1096. sortIPNets(uniqueList)
  1097. return uniqueList
  1098. }