acls.go 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  1. package logic
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "maps"
  7. "sort"
  8. "sync"
  9. "time"
  10. "github.com/gravitl/netmaker/database"
  11. "github.com/gravitl/netmaker/models"
  12. "github.com/gravitl/netmaker/servercfg"
  13. )
  14. var (
  15. aclCacheMutex = &sync.RWMutex{}
  16. aclCacheMap = make(map[string]models.Acl)
  17. )
  18. func MigrateAclPolicies() {
  19. acls := ListAcls()
  20. for _, acl := range acls {
  21. if acl.Proto.String() == "" {
  22. acl.Proto = models.ALL
  23. acl.ServiceType = models.Any
  24. acl.Port = []string{}
  25. UpsertAcl(acl)
  26. }
  27. }
  28. }
  29. // CreateDefaultAclNetworkPolicies - create default acl network policies
  30. func CreateDefaultAclNetworkPolicies(netID models.NetworkID) {
  31. if netID.String() == "" {
  32. return
  33. }
  34. _, _ = ListAclsByNetwork(netID)
  35. if !IsAclExists(fmt.Sprintf("%s.%s", netID, "all-nodes")) {
  36. defaultDeviceAcl := models.Acl{
  37. ID: fmt.Sprintf("%s.%s", netID, "all-nodes"),
  38. Name: "All Nodes",
  39. MetaData: "This Policy allows all nodes in the network to communicate with each other",
  40. Default: true,
  41. NetworkID: netID,
  42. Proto: models.ALL,
  43. ServiceType: models.Any,
  44. Port: []string{},
  45. RuleType: models.DevicePolicy,
  46. Src: []models.AclPolicyTag{
  47. {
  48. ID: models.DeviceAclID,
  49. Value: "*",
  50. }},
  51. Dst: []models.AclPolicyTag{
  52. {
  53. ID: models.DeviceAclID,
  54. Value: "*",
  55. }},
  56. AllowedDirection: models.TrafficDirectionBi,
  57. Enabled: true,
  58. CreatedBy: "auto",
  59. CreatedAt: time.Now().UTC(),
  60. }
  61. InsertAcl(defaultDeviceAcl)
  62. }
  63. if !IsAclExists(fmt.Sprintf("%s.%s", netID, "all-users")) {
  64. defaultUserAcl := models.Acl{
  65. ID: fmt.Sprintf("%s.%s", netID, "all-users"),
  66. Default: true,
  67. Name: "All Users",
  68. MetaData: "This policy gives access to everything in the network for an user",
  69. NetworkID: netID,
  70. Proto: models.ALL,
  71. ServiceType: models.Any,
  72. Port: []string{},
  73. RuleType: models.UserPolicy,
  74. Src: []models.AclPolicyTag{
  75. {
  76. ID: models.UserAclID,
  77. Value: "*",
  78. },
  79. },
  80. Dst: []models.AclPolicyTag{{
  81. ID: models.DeviceAclID,
  82. Value: "*",
  83. }},
  84. AllowedDirection: models.TrafficDirectionUni,
  85. Enabled: true,
  86. CreatedBy: "auto",
  87. CreatedAt: time.Now().UTC(),
  88. }
  89. InsertAcl(defaultUserAcl)
  90. }
  91. if !IsAclExists(fmt.Sprintf("%s.%s", netID, "all-remote-access-gws")) {
  92. defaultUserAcl := models.Acl{
  93. ID: fmt.Sprintf("%s.%s", netID, "all-remote-access-gws"),
  94. Default: true,
  95. Name: "All Remote Access Gateways",
  96. NetworkID: netID,
  97. Proto: models.ALL,
  98. ServiceType: models.Any,
  99. Port: []string{},
  100. RuleType: models.DevicePolicy,
  101. Src: []models.AclPolicyTag{
  102. {
  103. ID: models.DeviceAclID,
  104. Value: fmt.Sprintf("%s.%s", netID, models.RemoteAccessTagName),
  105. },
  106. },
  107. Dst: []models.AclPolicyTag{
  108. {
  109. ID: models.DeviceAclID,
  110. Value: "*",
  111. },
  112. },
  113. AllowedDirection: models.TrafficDirectionBi,
  114. Enabled: true,
  115. CreatedBy: "auto",
  116. CreatedAt: time.Now().UTC(),
  117. }
  118. InsertAcl(defaultUserAcl)
  119. }
  120. CreateDefaultUserPolicies(netID)
  121. }
  122. // DeleteDefaultNetworkPolicies - deletes all default network acl policies
  123. func DeleteDefaultNetworkPolicies(netId models.NetworkID) {
  124. acls, _ := ListAclsByNetwork(netId)
  125. for _, acl := range acls {
  126. if acl.NetworkID == netId && acl.Default {
  127. DeleteAcl(acl)
  128. }
  129. }
  130. }
  131. // ValidateCreateAclReq - validates create req for acl
  132. func ValidateCreateAclReq(req models.Acl) error {
  133. // check if acl network exists
  134. _, err := GetNetwork(req.NetworkID.String())
  135. if err != nil {
  136. return errors.New("failed to get network details for " + req.NetworkID.String())
  137. }
  138. // err = CheckIDSyntax(req.Name)
  139. // if err != nil {
  140. // return err
  141. // }
  142. return nil
  143. }
  144. func listAclFromCache() (acls []models.Acl) {
  145. aclCacheMutex.RLock()
  146. defer aclCacheMutex.RUnlock()
  147. for _, acl := range aclCacheMap {
  148. acls = append(acls, acl)
  149. }
  150. return
  151. }
  152. func storeAclInCache(a models.Acl) {
  153. aclCacheMutex.Lock()
  154. defer aclCacheMutex.Unlock()
  155. aclCacheMap[a.ID] = a
  156. }
  157. func removeAclFromCache(a models.Acl) {
  158. aclCacheMutex.Lock()
  159. defer aclCacheMutex.Unlock()
  160. delete(aclCacheMap, a.ID)
  161. }
  162. func getAclFromCache(aID string) (a models.Acl, ok bool) {
  163. aclCacheMutex.RLock()
  164. defer aclCacheMutex.RUnlock()
  165. a, ok = aclCacheMap[aID]
  166. return
  167. }
  168. // InsertAcl - creates acl policy
  169. func InsertAcl(a models.Acl) error {
  170. d, err := json.Marshal(a)
  171. if err != nil {
  172. return err
  173. }
  174. err = database.Insert(a.ID, string(d), database.ACLS_TABLE_NAME)
  175. if err == nil && servercfg.CacheEnabled() {
  176. storeAclInCache(a)
  177. }
  178. return err
  179. }
  180. // GetAcl - gets acl info by id
  181. func GetAcl(aID string) (models.Acl, error) {
  182. a := models.Acl{}
  183. if servercfg.CacheEnabled() {
  184. var ok bool
  185. a, ok = getAclFromCache(aID)
  186. if ok {
  187. return a, nil
  188. }
  189. }
  190. d, err := database.FetchRecord(database.ACLS_TABLE_NAME, aID)
  191. if err != nil {
  192. return a, err
  193. }
  194. err = json.Unmarshal([]byte(d), &a)
  195. if err != nil {
  196. return a, err
  197. }
  198. if servercfg.CacheEnabled() {
  199. storeAclInCache(a)
  200. }
  201. return a, nil
  202. }
  203. // IsAclExists - checks if acl exists
  204. func IsAclExists(aclID string) bool {
  205. _, err := GetAcl(aclID)
  206. return err == nil
  207. }
  208. // IsAclPolicyValid - validates if acl policy is valid
  209. func IsAclPolicyValid(acl models.Acl) bool {
  210. //check if src and dst are valid
  211. if acl.AllowedDirection != models.TrafficDirectionBi &&
  212. acl.AllowedDirection != models.TrafficDirectionUni {
  213. return false
  214. }
  215. switch acl.RuleType {
  216. case models.UserPolicy:
  217. // src list should only contain users
  218. for _, srcI := range acl.Src {
  219. if srcI.ID == "" || srcI.Value == "" {
  220. return false
  221. }
  222. if srcI.Value == "*" {
  223. continue
  224. }
  225. if srcI.ID != models.UserAclID && srcI.ID != models.UserGroupAclID {
  226. return false
  227. }
  228. // check if user group is valid
  229. if srcI.ID == models.UserAclID {
  230. _, err := GetUser(srcI.Value)
  231. if err != nil {
  232. return false
  233. }
  234. } else if srcI.ID == models.UserGroupAclID {
  235. err := IsGroupValid(models.UserGroupID(srcI.Value))
  236. if err != nil {
  237. return false
  238. }
  239. // check if group belongs to this network
  240. netGrps := GetUserGroupsInNetwork(acl.NetworkID)
  241. if _, ok := netGrps[models.UserGroupID(srcI.Value)]; !ok {
  242. return false
  243. }
  244. }
  245. }
  246. for _, dstI := range acl.Dst {
  247. if dstI.ID == "" || dstI.Value == "" {
  248. return false
  249. }
  250. if dstI.ID != models.DeviceAclID {
  251. return false
  252. }
  253. if dstI.Value == "*" {
  254. continue
  255. }
  256. // check if tag is valid
  257. _, err := GetTag(models.TagID(dstI.Value))
  258. if err != nil {
  259. return false
  260. }
  261. }
  262. case models.DevicePolicy:
  263. for _, srcI := range acl.Src {
  264. if srcI.ID == "" || srcI.Value == "" {
  265. return false
  266. }
  267. if srcI.ID != models.DeviceAclID {
  268. return false
  269. }
  270. if srcI.Value == "*" {
  271. continue
  272. }
  273. // check if tag is valid
  274. _, err := GetTag(models.TagID(srcI.Value))
  275. if err != nil {
  276. return false
  277. }
  278. }
  279. for _, dstI := range acl.Dst {
  280. if dstI.ID == "" || dstI.Value == "" {
  281. return false
  282. }
  283. if dstI.ID != models.DeviceAclID {
  284. return false
  285. }
  286. if dstI.Value == "*" {
  287. continue
  288. }
  289. // check if tag is valid
  290. _, err := GetTag(models.TagID(dstI.Value))
  291. if err != nil {
  292. return false
  293. }
  294. }
  295. }
  296. return true
  297. }
  298. // UpdateAcl - updates allowed fields on acls and commits to DB
  299. func UpdateAcl(newAcl, acl models.Acl) error {
  300. if !acl.Default {
  301. acl.Name = newAcl.Name
  302. acl.Src = newAcl.Src
  303. acl.Dst = newAcl.Dst
  304. acl.AllowedDirection = newAcl.AllowedDirection
  305. acl.Port = newAcl.Port
  306. acl.Proto = newAcl.Proto
  307. acl.ServiceType = newAcl.ServiceType
  308. }
  309. if newAcl.ServiceType == models.Any {
  310. acl.Port = []string{}
  311. acl.Proto = models.ALL
  312. }
  313. acl.Enabled = newAcl.Enabled
  314. d, err := json.Marshal(acl)
  315. if err != nil {
  316. return err
  317. }
  318. err = database.Insert(acl.ID, string(d), database.ACLS_TABLE_NAME)
  319. if err == nil && servercfg.CacheEnabled() {
  320. storeAclInCache(acl)
  321. }
  322. return err
  323. }
  324. // UpsertAcl - upserts acl
  325. func UpsertAcl(acl models.Acl) error {
  326. d, err := json.Marshal(acl)
  327. if err != nil {
  328. return err
  329. }
  330. err = database.Insert(acl.ID, string(d), database.ACLS_TABLE_NAME)
  331. if err == nil && servercfg.CacheEnabled() {
  332. storeAclInCache(acl)
  333. }
  334. return err
  335. }
  336. // DeleteAcl - deletes acl policy
  337. func DeleteAcl(a models.Acl) error {
  338. err := database.DeleteRecord(database.ACLS_TABLE_NAME, a.ID)
  339. if err == nil && servercfg.CacheEnabled() {
  340. removeAclFromCache(a)
  341. }
  342. return err
  343. }
  344. // GetDefaultPolicy - fetches default policy in the network by ruleType
  345. func GetDefaultPolicy(netID models.NetworkID, ruleType models.AclPolicyType) (models.Acl, error) {
  346. aclID := "all-users"
  347. if ruleType == models.DevicePolicy {
  348. aclID = "all-nodes"
  349. }
  350. acl, err := GetAcl(fmt.Sprintf("%s.%s", netID, aclID))
  351. if err != nil {
  352. return models.Acl{}, errors.New("default rule not found")
  353. }
  354. if acl.Enabled {
  355. return acl, nil
  356. }
  357. // check if there are any custom all policies
  358. srcMap := make(map[string]struct{})
  359. dstMap := make(map[string]struct{})
  360. defer func() {
  361. srcMap = nil
  362. dstMap = nil
  363. }()
  364. policies, _ := ListAclsByNetwork(netID)
  365. for _, policy := range policies {
  366. if !policy.Enabled {
  367. continue
  368. }
  369. if policy.RuleType == ruleType {
  370. dstMap = convAclTagToValueMap(policy.Dst)
  371. srcMap = convAclTagToValueMap(policy.Src)
  372. if _, ok := srcMap["*"]; ok {
  373. if _, ok := dstMap["*"]; ok {
  374. return policy, nil
  375. }
  376. }
  377. }
  378. }
  379. return acl, nil
  380. }
  381. func ListAcls() (acls []models.Acl) {
  382. if servercfg.CacheEnabled() && len(aclCacheMap) > 0 {
  383. return listAclFromCache()
  384. }
  385. data, err := database.FetchRecords(database.ACLS_TABLE_NAME)
  386. if err != nil && !database.IsEmptyRecord(err) {
  387. return []models.Acl{}
  388. }
  389. for _, dataI := range data {
  390. acl := models.Acl{}
  391. err := json.Unmarshal([]byte(dataI), &acl)
  392. if err != nil {
  393. continue
  394. }
  395. acls = append(acls, acl)
  396. if servercfg.CacheEnabled() {
  397. storeAclInCache(acl)
  398. }
  399. }
  400. return
  401. }
  402. // ListUserPolicies - lists all acl policies enforced on an user
  403. func ListUserPolicies(u models.User) []models.Acl {
  404. allAcls := ListAcls()
  405. userAcls := []models.Acl{}
  406. for _, acl := range allAcls {
  407. if acl.RuleType == models.UserPolicy {
  408. srcMap := convAclTagToValueMap(acl.Src)
  409. if _, ok := srcMap[u.UserName]; ok {
  410. userAcls = append(userAcls, acl)
  411. } else {
  412. // check for user groups
  413. for gID := range u.UserGroups {
  414. if _, ok := srcMap[gID.String()]; ok {
  415. userAcls = append(userAcls, acl)
  416. break
  417. }
  418. }
  419. }
  420. }
  421. }
  422. return userAcls
  423. }
  424. // listPoliciesOfUser - lists all user acl policies applied to user in an network
  425. func listPoliciesOfUser(user models.User, netID models.NetworkID) []models.Acl {
  426. allAcls := ListAcls()
  427. userAcls := []models.Acl{}
  428. for _, acl := range allAcls {
  429. if acl.NetworkID == netID && acl.RuleType == models.UserPolicy {
  430. srcMap := convAclTagToValueMap(acl.Src)
  431. if _, ok := srcMap[user.UserName]; ok {
  432. userAcls = append(userAcls, acl)
  433. continue
  434. }
  435. for netRole := range user.NetworkRoles {
  436. if _, ok := srcMap[netRole.String()]; ok {
  437. userAcls = append(userAcls, acl)
  438. continue
  439. }
  440. }
  441. for userG := range user.UserGroups {
  442. if _, ok := srcMap[userG.String()]; ok {
  443. userAcls = append(userAcls, acl)
  444. continue
  445. }
  446. }
  447. }
  448. }
  449. return userAcls
  450. }
  451. // listDevicePolicies - lists all device policies in a network
  452. func listDevicePolicies(netID models.NetworkID) []models.Acl {
  453. allAcls := ListAcls()
  454. deviceAcls := []models.Acl{}
  455. for _, acl := range allAcls {
  456. if acl.NetworkID == netID && acl.RuleType == models.DevicePolicy {
  457. deviceAcls = append(deviceAcls, acl)
  458. }
  459. }
  460. return deviceAcls
  461. }
  462. // listUserPolicies - lists all user policies in a network
  463. func listUserPolicies(netID models.NetworkID) []models.Acl {
  464. allAcls := ListAcls()
  465. deviceAcls := []models.Acl{}
  466. for _, acl := range allAcls {
  467. if acl.NetworkID == netID && acl.RuleType == models.UserPolicy {
  468. deviceAcls = append(deviceAcls, acl)
  469. }
  470. }
  471. return deviceAcls
  472. }
  473. // ListAcls - lists all acl policies
  474. func ListAclsByNetwork(netID models.NetworkID) ([]models.Acl, error) {
  475. allAcls := ListAcls()
  476. netAcls := []models.Acl{}
  477. for _, acl := range allAcls {
  478. if acl.NetworkID == netID {
  479. netAcls = append(netAcls, acl)
  480. }
  481. }
  482. return netAcls, nil
  483. }
  484. func convAclTagToValueMap(acltags []models.AclPolicyTag) map[string]struct{} {
  485. aclValueMap := make(map[string]struct{})
  486. for _, aclTagI := range acltags {
  487. aclValueMap[aclTagI.Value] = struct{}{}
  488. }
  489. return aclValueMap
  490. }
  491. // IsUserAllowedToCommunicate - check if user is allowed to communicate with peer
  492. func IsUserAllowedToCommunicate(userName string, peer models.Node) (bool, []models.Acl) {
  493. if peer.IsStatic {
  494. peer = peer.StaticNode.ConvertToStaticNode()
  495. }
  496. acl, _ := GetDefaultPolicy(models.NetworkID(peer.Network), models.UserPolicy)
  497. if acl.Enabled {
  498. return true, []models.Acl{acl}
  499. }
  500. user, err := GetUser(userName)
  501. if err != nil {
  502. return false, []models.Acl{}
  503. }
  504. allowedPolicies := []models.Acl{}
  505. policies := listPoliciesOfUser(*user, models.NetworkID(peer.Network))
  506. for _, policy := range policies {
  507. if !policy.Enabled {
  508. continue
  509. }
  510. dstMap := convAclTagToValueMap(policy.Dst)
  511. if _, ok := dstMap["*"]; ok {
  512. allowedPolicies = append(allowedPolicies, policy)
  513. continue
  514. }
  515. for tagID := range peer.Tags {
  516. if _, ok := dstMap[tagID.String()]; ok {
  517. allowedPolicies = append(allowedPolicies, policy)
  518. break
  519. }
  520. }
  521. }
  522. if len(allowedPolicies) > 0 {
  523. return true, allowedPolicies
  524. }
  525. return false, []models.Acl{}
  526. }
  527. // IsPeerAllowed - checks if peer needs to be added to the interface
  528. func IsPeerAllowed(node, peer models.Node, checkDefaultPolicy bool) bool {
  529. if node.IsStatic {
  530. node = node.StaticNode.ConvertToStaticNode()
  531. }
  532. if peer.IsStatic {
  533. peer = peer.StaticNode.ConvertToStaticNode()
  534. }
  535. var nodeTags, peerTags map[models.TagID]struct{}
  536. if node.Mutex != nil {
  537. node.Mutex.Lock()
  538. nodeTags = maps.Clone(node.Tags)
  539. node.Mutex.Unlock()
  540. } else {
  541. nodeTags = node.Tags
  542. }
  543. if peer.Mutex != nil {
  544. peer.Mutex.Lock()
  545. peerTags = maps.Clone(peer.Tags)
  546. peer.Mutex.Unlock()
  547. } else {
  548. peerTags = peer.Tags
  549. }
  550. if checkDefaultPolicy {
  551. // check default policy if all allowed return true
  552. defaultPolicy, err := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  553. if err == nil {
  554. if defaultPolicy.Enabled {
  555. return true
  556. }
  557. }
  558. }
  559. // list device policies
  560. policies := listDevicePolicies(models.NetworkID(peer.Network))
  561. srcMap := make(map[string]struct{})
  562. dstMap := make(map[string]struct{})
  563. defer func() {
  564. srcMap = nil
  565. dstMap = nil
  566. }()
  567. for _, policy := range policies {
  568. if !policy.Enabled {
  569. continue
  570. }
  571. srcMap = convAclTagToValueMap(policy.Src)
  572. dstMap = convAclTagToValueMap(policy.Dst)
  573. for tagID := range nodeTags {
  574. if _, ok := dstMap[tagID.String()]; ok {
  575. if _, ok := srcMap["*"]; ok {
  576. return true
  577. }
  578. for tagID := range peerTags {
  579. if _, ok := srcMap[tagID.String()]; ok {
  580. return true
  581. }
  582. }
  583. }
  584. if _, ok := srcMap[tagID.String()]; ok {
  585. if _, ok := dstMap["*"]; ok {
  586. return true
  587. }
  588. for tagID := range peerTags {
  589. if _, ok := dstMap[tagID.String()]; ok {
  590. return true
  591. }
  592. }
  593. }
  594. }
  595. for tagID := range peerTags {
  596. if _, ok := dstMap[tagID.String()]; ok {
  597. if _, ok := srcMap["*"]; ok {
  598. return true
  599. }
  600. for tagID := range nodeTags {
  601. if _, ok := srcMap[tagID.String()]; ok {
  602. return true
  603. }
  604. }
  605. }
  606. if _, ok := srcMap[tagID.String()]; ok {
  607. if _, ok := dstMap["*"]; ok {
  608. return true
  609. }
  610. for tagID := range nodeTags {
  611. if _, ok := dstMap[tagID.String()]; ok {
  612. return true
  613. }
  614. }
  615. }
  616. }
  617. }
  618. return false
  619. }
  620. // IsNodeAllowedToCommunicate - check node is allowed to communicate with the peer
  621. func IsNodeAllowedToCommunicate(node, peer models.Node, checkDefaultPolicy bool) (bool, []models.Acl) {
  622. if node.IsStatic {
  623. node = node.StaticNode.ConvertToStaticNode()
  624. }
  625. if peer.IsStatic {
  626. peer = peer.StaticNode.ConvertToStaticNode()
  627. }
  628. var nodeTags, peerTags map[models.TagID]struct{}
  629. if node.Mutex != nil {
  630. node.Mutex.Lock()
  631. nodeTags = maps.Clone(node.Tags)
  632. node.Mutex.Unlock()
  633. } else {
  634. nodeTags = node.Tags
  635. }
  636. if peer.Mutex != nil {
  637. peer.Mutex.Lock()
  638. peerTags = maps.Clone(peer.Tags)
  639. peer.Mutex.Unlock()
  640. } else {
  641. peerTags = peer.Tags
  642. }
  643. if checkDefaultPolicy {
  644. // check default policy if all allowed return true
  645. defaultPolicy, err := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  646. if err == nil {
  647. if defaultPolicy.Enabled {
  648. return true, []models.Acl{defaultPolicy}
  649. }
  650. }
  651. }
  652. allowedPolicies := []models.Acl{}
  653. // list device policies
  654. policies := listDevicePolicies(models.NetworkID(peer.Network))
  655. srcMap := make(map[string]struct{})
  656. dstMap := make(map[string]struct{})
  657. defer func() {
  658. srcMap = nil
  659. dstMap = nil
  660. }()
  661. for _, policy := range policies {
  662. if !policy.Enabled {
  663. continue
  664. }
  665. srcMap = convAclTagToValueMap(policy.Src)
  666. dstMap = convAclTagToValueMap(policy.Dst)
  667. for tagID := range nodeTags {
  668. allowed := false
  669. if _, ok := dstMap[tagID.String()]; policy.AllowedDirection == models.TrafficDirectionBi && ok {
  670. if _, ok := srcMap["*"]; ok {
  671. allowed = true
  672. allowedPolicies = append(allowedPolicies, policy)
  673. break
  674. }
  675. for tagID := range peerTags {
  676. if _, ok := srcMap[tagID.String()]; ok {
  677. allowed = true
  678. break
  679. }
  680. }
  681. }
  682. if allowed {
  683. allowedPolicies = append(allowedPolicies, policy)
  684. break
  685. }
  686. if _, ok := srcMap[tagID.String()]; ok {
  687. if _, ok := dstMap["*"]; ok {
  688. allowed = true
  689. allowedPolicies = append(allowedPolicies, policy)
  690. break
  691. }
  692. for tagID := range peerTags {
  693. if _, ok := dstMap[tagID.String()]; ok {
  694. allowed = true
  695. break
  696. }
  697. }
  698. }
  699. if allowed {
  700. allowedPolicies = append(allowedPolicies, policy)
  701. break
  702. }
  703. }
  704. for tagID := range peerTags {
  705. allowed := false
  706. if _, ok := dstMap[tagID.String()]; ok {
  707. if _, ok := srcMap["*"]; ok {
  708. allowed = true
  709. allowedPolicies = append(allowedPolicies, policy)
  710. break
  711. }
  712. for tagID := range nodeTags {
  713. if _, ok := srcMap[tagID.String()]; ok {
  714. allowed = true
  715. break
  716. }
  717. }
  718. }
  719. if allowed {
  720. allowedPolicies = append(allowedPolicies, policy)
  721. break
  722. }
  723. if _, ok := srcMap[tagID.String()]; policy.AllowedDirection == models.TrafficDirectionBi && ok {
  724. if _, ok := dstMap["*"]; ok {
  725. allowed = true
  726. allowedPolicies = append(allowedPolicies, policy)
  727. break
  728. }
  729. for tagID := range nodeTags {
  730. if _, ok := dstMap[tagID.String()]; ok {
  731. allowed = true
  732. break
  733. }
  734. }
  735. }
  736. if allowed {
  737. allowedPolicies = append(allowedPolicies, policy)
  738. break
  739. }
  740. }
  741. }
  742. if len(allowedPolicies) > 0 {
  743. return true, allowedPolicies
  744. }
  745. return false, allowedPolicies
  746. }
  747. // SortTagEntrys - Sorts slice of Tag entries by their id
  748. func SortAclEntrys(acls []models.Acl) {
  749. sort.Slice(acls, func(i, j int) bool {
  750. return acls[i].Name < acls[j].Name
  751. })
  752. }
  753. // UpdateDeviceTag - updates device tag on acl policies
  754. func UpdateDeviceTag(OldID, newID models.TagID, netID models.NetworkID) {
  755. acls := listDevicePolicies(netID)
  756. update := false
  757. for _, acl := range acls {
  758. for i, srcTagI := range acl.Src {
  759. if srcTagI.ID == models.DeviceAclID {
  760. if OldID.String() == srcTagI.Value {
  761. acl.Src[i].Value = newID.String()
  762. update = true
  763. }
  764. }
  765. }
  766. for i, dstTagI := range acl.Dst {
  767. if dstTagI.ID == models.DeviceAclID {
  768. if OldID.String() == dstTagI.Value {
  769. acl.Dst[i].Value = newID.String()
  770. update = true
  771. }
  772. }
  773. }
  774. if update {
  775. UpsertAcl(acl)
  776. }
  777. }
  778. }
  779. func CheckIfTagAsActivePolicy(tagID models.TagID, netID models.NetworkID) bool {
  780. acls := listDevicePolicies(netID)
  781. for _, acl := range acls {
  782. for _, srcTagI := range acl.Src {
  783. if srcTagI.ID == models.DeviceAclID {
  784. if tagID.String() == srcTagI.Value {
  785. return true
  786. }
  787. }
  788. }
  789. for _, dstTagI := range acl.Dst {
  790. if dstTagI.ID == models.DeviceAclID {
  791. if tagID.String() == dstTagI.Value {
  792. return true
  793. }
  794. }
  795. }
  796. }
  797. return false
  798. }
  799. // RemoveDeviceTagFromAclPolicies - remove device tag from acl policies
  800. func RemoveDeviceTagFromAclPolicies(tagID models.TagID, netID models.NetworkID) error {
  801. acls := listDevicePolicies(netID)
  802. update := false
  803. for _, acl := range acls {
  804. for i, srcTagI := range acl.Src {
  805. if srcTagI.ID == models.DeviceAclID {
  806. if tagID.String() == srcTagI.Value {
  807. acl.Src = append(acl.Src[:i], acl.Src[i+1:]...)
  808. update = true
  809. }
  810. }
  811. }
  812. for i, dstTagI := range acl.Dst {
  813. if dstTagI.ID == models.DeviceAclID {
  814. if tagID.String() == dstTagI.Value {
  815. acl.Dst = append(acl.Dst[:i], acl.Dst[i+1:]...)
  816. update = true
  817. }
  818. }
  819. }
  820. if update {
  821. UpsertAcl(acl)
  822. }
  823. }
  824. return nil
  825. }
  826. func getUserAclRulesForNode(targetnode *models.Node,
  827. rules map[string]models.AclRule) map[string]models.AclRule {
  828. userNodes := GetStaticUserNodesByNetwork(models.NetworkID(targetnode.Network))
  829. userGrpMap := GetUserGrpMap()
  830. allowedUsers := make(map[string][]models.Acl)
  831. acls := listUserPolicies(models.NetworkID(targetnode.Network))
  832. var targetNodeTags = make(map[models.TagID]struct{})
  833. if targetnode.Mutex != nil {
  834. targetnode.Mutex.Lock()
  835. targetNodeTags = maps.Clone(targetnode.Tags)
  836. targetnode.Mutex.Unlock()
  837. } else {
  838. targetNodeTags = maps.Clone(targetnode.Tags)
  839. }
  840. for nodeTag := range targetNodeTags {
  841. for _, acl := range acls {
  842. if !acl.Enabled {
  843. continue
  844. }
  845. dstTags := convAclTagToValueMap(acl.Dst)
  846. if _, ok := dstTags[nodeTag.String()]; ok {
  847. // get all src tags
  848. for _, srcAcl := range acl.Src {
  849. if srcAcl.ID == models.UserAclID {
  850. allowedUsers[srcAcl.Value] = append(allowedUsers[srcAcl.Value], acl)
  851. } else if srcAcl.ID == models.UserGroupAclID {
  852. // fetch all users in the group
  853. if usersMap, ok := userGrpMap[models.UserGroupID(srcAcl.Value)]; ok {
  854. for userName := range usersMap {
  855. allowedUsers[userName] = append(allowedUsers[userName], acl)
  856. }
  857. }
  858. }
  859. }
  860. }
  861. }
  862. }
  863. for _, userNode := range userNodes {
  864. if !userNode.StaticNode.Enabled {
  865. continue
  866. }
  867. acls, ok := allowedUsers[userNode.StaticNode.OwnerID]
  868. if !ok {
  869. continue
  870. }
  871. for _, acl := range acls {
  872. if !acl.Enabled {
  873. continue
  874. }
  875. r := models.AclRule{
  876. ID: acl.ID,
  877. AllowedProtocol: acl.Proto,
  878. AllowedPorts: acl.Port,
  879. Direction: acl.AllowedDirection,
  880. Allowed: true,
  881. }
  882. // Get peers in the tags and add allowed rules
  883. if userNode.StaticNode.Address != "" {
  884. r.IPList = append(r.IPList, userNode.StaticNode.AddressIPNet4())
  885. }
  886. if userNode.StaticNode.Address6 != "" {
  887. r.IP6List = append(r.IP6List, userNode.StaticNode.AddressIPNet6())
  888. }
  889. if aclRule, ok := rules[acl.ID]; ok {
  890. aclRule.IPList = append(aclRule.IPList, r.IPList...)
  891. aclRule.IP6List = append(aclRule.IP6List, r.IP6List...)
  892. rules[acl.ID] = aclRule
  893. } else {
  894. rules[acl.ID] = r
  895. }
  896. }
  897. }
  898. return rules
  899. }
  900. func GetAclRulesForNode(targetnode *models.Node) (rules map[string]models.AclRule) {
  901. defer func() {
  902. if !targetnode.IsIngressGateway {
  903. rules = getUserAclRulesForNode(targetnode, rules)
  904. }
  905. }()
  906. rules = make(map[string]models.AclRule)
  907. var taggedNodes map[models.TagID][]models.Node
  908. if targetnode.IsIngressGateway {
  909. taggedNodes = GetTagMapWithNodesByNetwork(models.NetworkID(targetnode.Network), false)
  910. } else {
  911. taggedNodes = GetTagMapWithNodesByNetwork(models.NetworkID(targetnode.Network), true)
  912. }
  913. acls := listDevicePolicies(models.NetworkID(targetnode.Network))
  914. var targetNodeTags = make(map[models.TagID]struct{})
  915. if targetnode.Mutex != nil {
  916. targetnode.Mutex.Lock()
  917. targetNodeTags = maps.Clone(targetnode.Tags)
  918. targetnode.Mutex.Unlock()
  919. } else {
  920. targetNodeTags = maps.Clone(targetnode.Tags)
  921. }
  922. targetNodeTags["*"] = struct{}{}
  923. for nodeTag := range targetNodeTags {
  924. for _, acl := range acls {
  925. if !acl.Enabled {
  926. continue
  927. }
  928. srcTags := convAclTagToValueMap(acl.Src)
  929. dstTags := convAclTagToValueMap(acl.Dst)
  930. aclRule := models.AclRule{
  931. ID: acl.ID,
  932. AllowedProtocol: acl.Proto,
  933. AllowedPorts: acl.Port,
  934. Direction: acl.AllowedDirection,
  935. Allowed: true,
  936. }
  937. if acl.AllowedDirection == models.TrafficDirectionBi {
  938. var existsInSrcTag bool
  939. var existsInDstTag bool
  940. if _, ok := srcTags[nodeTag.String()]; ok {
  941. existsInSrcTag = true
  942. }
  943. if _, ok := dstTags[nodeTag.String()]; ok {
  944. existsInDstTag = true
  945. }
  946. if existsInSrcTag && !existsInDstTag {
  947. // get all dst tags
  948. for dst := range dstTags {
  949. if dst == nodeTag.String() {
  950. continue
  951. }
  952. // Get peers in the tags and add allowed rules
  953. nodes := taggedNodes[models.TagID(dst)]
  954. for _, node := range nodes {
  955. if node.ID == targetnode.ID {
  956. continue
  957. }
  958. if node.Address.IP != nil {
  959. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  960. }
  961. if node.Address6.IP != nil {
  962. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  963. }
  964. if node.IsStatic && node.StaticNode.Address != "" {
  965. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  966. }
  967. if node.IsStatic && node.StaticNode.Address6 != "" {
  968. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  969. }
  970. }
  971. }
  972. }
  973. if existsInDstTag && !existsInSrcTag {
  974. // get all src tags
  975. for src := range srcTags {
  976. if src == nodeTag.String() {
  977. continue
  978. }
  979. // Get peers in the tags and add allowed rules
  980. nodes := taggedNodes[models.TagID(src)]
  981. for _, node := range nodes {
  982. if node.ID == targetnode.ID {
  983. continue
  984. }
  985. if node.Address.IP != nil {
  986. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  987. }
  988. if node.Address6.IP != nil {
  989. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  990. }
  991. if node.IsStatic && node.StaticNode.Address != "" {
  992. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  993. }
  994. if node.IsStatic && node.StaticNode.Address6 != "" {
  995. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  996. }
  997. }
  998. }
  999. }
  1000. if existsInDstTag && existsInSrcTag {
  1001. nodes := taggedNodes[nodeTag]
  1002. for _, node := range nodes {
  1003. if node.ID == targetnode.ID {
  1004. continue
  1005. }
  1006. if node.Address.IP != nil {
  1007. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  1008. }
  1009. if node.Address6.IP != nil {
  1010. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  1011. }
  1012. if node.IsStatic && node.StaticNode.Address != "" {
  1013. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  1014. }
  1015. if node.IsStatic && node.StaticNode.Address6 != "" {
  1016. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  1017. }
  1018. }
  1019. }
  1020. } else {
  1021. _, all := dstTags["*"]
  1022. if _, ok := dstTags[nodeTag.String()]; ok || all {
  1023. // get all src tags
  1024. for src := range srcTags {
  1025. if src == nodeTag.String() {
  1026. continue
  1027. }
  1028. // Get peers in the tags and add allowed rules
  1029. nodes := taggedNodes[models.TagID(src)]
  1030. for _, node := range nodes {
  1031. if node.ID == targetnode.ID {
  1032. continue
  1033. }
  1034. if node.Address.IP != nil {
  1035. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  1036. }
  1037. if node.Address6.IP != nil {
  1038. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  1039. }
  1040. if node.IsStatic && node.StaticNode.Address != "" {
  1041. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  1042. }
  1043. if node.IsStatic && node.StaticNode.Address6 != "" {
  1044. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  1045. }
  1046. }
  1047. }
  1048. }
  1049. }
  1050. if len(aclRule.IPList) > 0 || len(aclRule.IP6List) > 0 {
  1051. rules[acl.ID] = aclRule
  1052. }
  1053. }
  1054. }
  1055. return rules
  1056. }