acls.go 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  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. peerTags := maps.Clone(peer.Tags)
  536. nodeTags := maps.Clone(node.Tags)
  537. if checkDefaultPolicy {
  538. // check default policy if all allowed return true
  539. defaultPolicy, err := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  540. if err == nil {
  541. if defaultPolicy.Enabled {
  542. return true
  543. }
  544. }
  545. }
  546. // list device policies
  547. policies := listDevicePolicies(models.NetworkID(peer.Network))
  548. srcMap := make(map[string]struct{})
  549. dstMap := make(map[string]struct{})
  550. defer func() {
  551. srcMap = nil
  552. dstMap = nil
  553. }()
  554. for _, policy := range policies {
  555. if !policy.Enabled {
  556. continue
  557. }
  558. srcMap = convAclTagToValueMap(policy.Src)
  559. dstMap = convAclTagToValueMap(policy.Dst)
  560. for tagID := range nodeTags {
  561. if _, ok := dstMap[tagID.String()]; ok {
  562. if _, ok := srcMap["*"]; ok {
  563. return true
  564. }
  565. for tagID := range peerTags {
  566. if _, ok := srcMap[tagID.String()]; ok {
  567. return true
  568. }
  569. }
  570. }
  571. if _, ok := srcMap[tagID.String()]; ok {
  572. if _, ok := dstMap["*"]; ok {
  573. return true
  574. }
  575. for tagID := range peerTags {
  576. if _, ok := dstMap[tagID.String()]; ok {
  577. return true
  578. }
  579. }
  580. }
  581. }
  582. for tagID := range peerTags {
  583. if _, ok := dstMap[tagID.String()]; ok {
  584. if _, ok := srcMap["*"]; ok {
  585. return true
  586. }
  587. for tagID := range nodeTags {
  588. if _, ok := srcMap[tagID.String()]; ok {
  589. return true
  590. }
  591. }
  592. }
  593. if _, ok := srcMap[tagID.String()]; ok {
  594. if _, ok := dstMap["*"]; ok {
  595. return true
  596. }
  597. for tagID := range nodeTags {
  598. if _, ok := dstMap[tagID.String()]; ok {
  599. return true
  600. }
  601. }
  602. }
  603. }
  604. }
  605. return false
  606. }
  607. // IsNodeAllowedToCommunicate - check node is allowed to communicate with the peer
  608. func IsNodeAllowedToCommunicate(node, peer models.Node, checkDefaultPolicy bool) (bool, []models.Acl) {
  609. if node.IsStatic {
  610. node = node.StaticNode.ConvertToStaticNode()
  611. }
  612. if peer.IsStatic {
  613. peer = peer.StaticNode.ConvertToStaticNode()
  614. }
  615. peerTags := maps.Clone(peer.Tags)
  616. nodeTags := maps.Clone(node.Tags)
  617. if checkDefaultPolicy {
  618. // check default policy if all allowed return true
  619. defaultPolicy, err := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  620. if err == nil {
  621. if defaultPolicy.Enabled {
  622. return true, []models.Acl{defaultPolicy}
  623. }
  624. }
  625. }
  626. allowedPolicies := []models.Acl{}
  627. // list device policies
  628. policies := listDevicePolicies(models.NetworkID(peer.Network))
  629. srcMap := make(map[string]struct{})
  630. dstMap := make(map[string]struct{})
  631. defer func() {
  632. srcMap = nil
  633. dstMap = nil
  634. }()
  635. for _, policy := range policies {
  636. if !policy.Enabled {
  637. continue
  638. }
  639. srcMap = convAclTagToValueMap(policy.Src)
  640. dstMap = convAclTagToValueMap(policy.Dst)
  641. for tagID := range nodeTags {
  642. allowed := false
  643. if _, ok := dstMap[tagID.String()]; policy.AllowedDirection == models.TrafficDirectionBi && ok {
  644. if _, ok := srcMap["*"]; ok {
  645. allowed = true
  646. allowedPolicies = append(allowedPolicies, policy)
  647. break
  648. }
  649. for tagID := range peerTags {
  650. if _, ok := srcMap[tagID.String()]; ok {
  651. allowed = true
  652. break
  653. }
  654. }
  655. }
  656. if allowed {
  657. allowedPolicies = append(allowedPolicies, policy)
  658. break
  659. }
  660. if _, ok := srcMap[tagID.String()]; ok {
  661. if _, ok := dstMap["*"]; ok {
  662. allowed = true
  663. allowedPolicies = append(allowedPolicies, policy)
  664. break
  665. }
  666. for tagID := range peerTags {
  667. if _, ok := dstMap[tagID.String()]; ok {
  668. allowed = true
  669. break
  670. }
  671. }
  672. }
  673. if allowed {
  674. allowedPolicies = append(allowedPolicies, policy)
  675. break
  676. }
  677. }
  678. for tagID := range peerTags {
  679. allowed := false
  680. if _, ok := dstMap[tagID.String()]; ok {
  681. if _, ok := srcMap["*"]; ok {
  682. allowed = true
  683. allowedPolicies = append(allowedPolicies, policy)
  684. break
  685. }
  686. for tagID := range nodeTags {
  687. if _, ok := srcMap[tagID.String()]; ok {
  688. allowed = true
  689. break
  690. }
  691. }
  692. }
  693. if allowed {
  694. allowedPolicies = append(allowedPolicies, policy)
  695. break
  696. }
  697. if _, ok := srcMap[tagID.String()]; policy.AllowedDirection == models.TrafficDirectionBi && ok {
  698. if _, ok := dstMap["*"]; ok {
  699. allowed = true
  700. allowedPolicies = append(allowedPolicies, policy)
  701. break
  702. }
  703. for tagID := range nodeTags {
  704. if _, ok := dstMap[tagID.String()]; ok {
  705. allowed = true
  706. break
  707. }
  708. }
  709. }
  710. if allowed {
  711. allowedPolicies = append(allowedPolicies, policy)
  712. break
  713. }
  714. }
  715. }
  716. if len(allowedPolicies) > 0 {
  717. return true, allowedPolicies
  718. }
  719. return false, allowedPolicies
  720. }
  721. // SortTagEntrys - Sorts slice of Tag entries by their id
  722. func SortAclEntrys(acls []models.Acl) {
  723. sort.Slice(acls, func(i, j int) bool {
  724. return acls[i].Name < acls[j].Name
  725. })
  726. }
  727. // UpdateDeviceTag - updates device tag on acl policies
  728. func UpdateDeviceTag(OldID, newID models.TagID, netID models.NetworkID) {
  729. acls := listDevicePolicies(netID)
  730. update := false
  731. for _, acl := range acls {
  732. for i, srcTagI := range acl.Src {
  733. if srcTagI.ID == models.DeviceAclID {
  734. if OldID.String() == srcTagI.Value {
  735. acl.Src[i].Value = newID.String()
  736. update = true
  737. }
  738. }
  739. }
  740. for i, dstTagI := range acl.Dst {
  741. if dstTagI.ID == models.DeviceAclID {
  742. if OldID.String() == dstTagI.Value {
  743. acl.Dst[i].Value = newID.String()
  744. update = true
  745. }
  746. }
  747. }
  748. if update {
  749. UpsertAcl(acl)
  750. }
  751. }
  752. }
  753. func CheckIfTagAsActivePolicy(tagID models.TagID, netID models.NetworkID) bool {
  754. acls := listDevicePolicies(netID)
  755. for _, acl := range acls {
  756. for _, srcTagI := range acl.Src {
  757. if srcTagI.ID == models.DeviceAclID {
  758. if tagID.String() == srcTagI.Value {
  759. return true
  760. }
  761. }
  762. }
  763. for _, dstTagI := range acl.Dst {
  764. if dstTagI.ID == models.DeviceAclID {
  765. if tagID.String() == dstTagI.Value {
  766. return true
  767. }
  768. }
  769. }
  770. }
  771. return false
  772. }
  773. // RemoveDeviceTagFromAclPolicies - remove device tag from acl policies
  774. func RemoveDeviceTagFromAclPolicies(tagID models.TagID, netID models.NetworkID) error {
  775. acls := listDevicePolicies(netID)
  776. update := false
  777. for _, acl := range acls {
  778. for i, srcTagI := range acl.Src {
  779. if srcTagI.ID == models.DeviceAclID {
  780. if tagID.String() == srcTagI.Value {
  781. acl.Src = append(acl.Src[:i], acl.Src[i+1:]...)
  782. update = true
  783. }
  784. }
  785. }
  786. for i, dstTagI := range acl.Dst {
  787. if dstTagI.ID == models.DeviceAclID {
  788. if tagID.String() == dstTagI.Value {
  789. acl.Dst = append(acl.Dst[:i], acl.Dst[i+1:]...)
  790. update = true
  791. }
  792. }
  793. }
  794. if update {
  795. UpsertAcl(acl)
  796. }
  797. }
  798. return nil
  799. }
  800. func getUserAclRulesForNode(targetnode *models.Node,
  801. rules map[string]models.AclRule) map[string]models.AclRule {
  802. userNodes := GetStaticUserNodesByNetwork(models.NetworkID(targetnode.Network))
  803. userGrpMap := GetUserGrpMap()
  804. allowedUsers := make(map[string][]models.Acl)
  805. acls := listUserPolicies(models.NetworkID(targetnode.Network))
  806. for nodeTag := range targetnode.Tags {
  807. for _, acl := range acls {
  808. if !acl.Enabled {
  809. continue
  810. }
  811. dstTags := convAclTagToValueMap(acl.Dst)
  812. if _, ok := dstTags[nodeTag.String()]; ok {
  813. // get all src tags
  814. for _, srcAcl := range acl.Src {
  815. if srcAcl.ID == models.UserAclID {
  816. allowedUsers[srcAcl.Value] = append(allowedUsers[srcAcl.Value], acl)
  817. } else if srcAcl.ID == models.UserGroupAclID {
  818. // fetch all users in the group
  819. if usersMap, ok := userGrpMap[models.UserGroupID(srcAcl.Value)]; ok {
  820. for userName := range usersMap {
  821. allowedUsers[userName] = append(allowedUsers[userName], acl)
  822. }
  823. }
  824. }
  825. }
  826. }
  827. }
  828. }
  829. for _, userNode := range userNodes {
  830. if !userNode.StaticNode.Enabled {
  831. continue
  832. }
  833. acls, ok := allowedUsers[userNode.StaticNode.OwnerID]
  834. if !ok {
  835. continue
  836. }
  837. for _, acl := range acls {
  838. if !acl.Enabled {
  839. continue
  840. }
  841. r := models.AclRule{
  842. ID: acl.ID,
  843. AllowedProtocol: acl.Proto,
  844. AllowedPorts: acl.Port,
  845. Direction: acl.AllowedDirection,
  846. Allowed: true,
  847. }
  848. // Get peers in the tags and add allowed rules
  849. if userNode.StaticNode.Address != "" {
  850. r.IPList = append(r.IPList, userNode.StaticNode.AddressIPNet4())
  851. }
  852. if userNode.StaticNode.Address6 != "" {
  853. r.IP6List = append(r.IP6List, userNode.StaticNode.AddressIPNet6())
  854. }
  855. if aclRule, ok := rules[acl.ID]; ok {
  856. aclRule.IPList = append(aclRule.IPList, r.IPList...)
  857. aclRule.IP6List = append(aclRule.IP6List, r.IP6List...)
  858. rules[acl.ID] = aclRule
  859. } else {
  860. rules[acl.ID] = r
  861. }
  862. }
  863. }
  864. return rules
  865. }
  866. func GetAclRulesForNode(targetnode *models.Node) (rules map[string]models.AclRule) {
  867. defer func() {
  868. if !targetnode.IsIngressGateway {
  869. rules = getUserAclRulesForNode(targetnode, rules)
  870. }
  871. }()
  872. rules = make(map[string]models.AclRule)
  873. var taggedNodes map[models.TagID][]models.Node
  874. if targetnode.IsIngressGateway {
  875. taggedNodes = GetTagMapWithNodesByNetwork(models.NetworkID(targetnode.Network), false)
  876. } else {
  877. taggedNodes = GetTagMapWithNodesByNetwork(models.NetworkID(targetnode.Network), true)
  878. }
  879. acls := listDevicePolicies(models.NetworkID(targetnode.Network))
  880. targetnode.Tags["*"] = struct{}{}
  881. for nodeTag := range targetnode.Tags {
  882. for _, acl := range acls {
  883. if !acl.Enabled {
  884. continue
  885. }
  886. srcTags := convAclTagToValueMap(acl.Src)
  887. dstTags := convAclTagToValueMap(acl.Dst)
  888. aclRule := models.AclRule{
  889. ID: acl.ID,
  890. AllowedProtocol: acl.Proto,
  891. AllowedPorts: acl.Port,
  892. Direction: acl.AllowedDirection,
  893. Allowed: true,
  894. }
  895. if acl.AllowedDirection == models.TrafficDirectionBi {
  896. var existsInSrcTag bool
  897. var existsInDstTag bool
  898. if _, ok := srcTags[nodeTag.String()]; ok {
  899. existsInSrcTag = true
  900. }
  901. if _, ok := dstTags[nodeTag.String()]; ok {
  902. existsInDstTag = true
  903. }
  904. if existsInSrcTag && !existsInDstTag {
  905. // get all dst tags
  906. for dst := range dstTags {
  907. if dst == nodeTag.String() {
  908. continue
  909. }
  910. // Get peers in the tags and add allowed rules
  911. nodes := taggedNodes[models.TagID(dst)]
  912. for _, node := range nodes {
  913. if node.ID == targetnode.ID {
  914. continue
  915. }
  916. if node.Address.IP != nil {
  917. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  918. }
  919. if node.Address6.IP != nil {
  920. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  921. }
  922. if node.IsStatic && node.StaticNode.Address != "" {
  923. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  924. }
  925. if node.IsStatic && node.StaticNode.Address6 != "" {
  926. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  927. }
  928. }
  929. }
  930. }
  931. if existsInDstTag && !existsInSrcTag {
  932. // get all src tags
  933. for src := range srcTags {
  934. if src == nodeTag.String() {
  935. continue
  936. }
  937. // Get peers in the tags and add allowed rules
  938. nodes := taggedNodes[models.TagID(src)]
  939. for _, node := range nodes {
  940. if node.ID == targetnode.ID {
  941. continue
  942. }
  943. if node.Address.IP != nil {
  944. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  945. }
  946. if node.Address6.IP != nil {
  947. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  948. }
  949. if node.IsStatic && node.StaticNode.Address != "" {
  950. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  951. }
  952. if node.IsStatic && node.StaticNode.Address6 != "" {
  953. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  954. }
  955. }
  956. }
  957. }
  958. if existsInDstTag && existsInSrcTag {
  959. nodes := taggedNodes[nodeTag]
  960. for _, node := range nodes {
  961. if node.ID == targetnode.ID {
  962. continue
  963. }
  964. if node.Address.IP != nil {
  965. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  966. }
  967. if node.Address6.IP != nil {
  968. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  969. }
  970. if node.IsStatic && node.StaticNode.Address != "" {
  971. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  972. }
  973. if node.IsStatic && node.StaticNode.Address6 != "" {
  974. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  975. }
  976. }
  977. }
  978. } else {
  979. _, all := dstTags["*"]
  980. if _, ok := dstTags[nodeTag.String()]; ok || all {
  981. // get all src tags
  982. for src := range srcTags {
  983. if src == nodeTag.String() {
  984. continue
  985. }
  986. // Get peers in the tags and add allowed rules
  987. nodes := taggedNodes[models.TagID(src)]
  988. for _, node := range nodes {
  989. if node.ID == targetnode.ID {
  990. continue
  991. }
  992. if node.Address.IP != nil {
  993. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  994. }
  995. if node.Address6.IP != nil {
  996. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  997. }
  998. if node.IsStatic && node.StaticNode.Address != "" {
  999. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  1000. }
  1001. if node.IsStatic && node.StaticNode.Address6 != "" {
  1002. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  1003. }
  1004. }
  1005. }
  1006. }
  1007. }
  1008. if len(aclRule.IPList) > 0 || len(aclRule.IP6List) > 0 {
  1009. rules[acl.ID] = aclRule
  1010. }
  1011. }
  1012. }
  1013. return rules
  1014. }