acls.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  1. package logic
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net"
  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. // CreateDefaultAclNetworkPolicies - create default acl network policies
  19. func CreateDefaultAclNetworkPolicies(netID models.NetworkID) {
  20. if netID.String() == "" {
  21. return
  22. }
  23. if !IsAclExists(fmt.Sprintf("%s.%s", netID, "all-nodes")) {
  24. defaultDeviceAcl := models.Acl{
  25. ID: fmt.Sprintf("%s.%s", netID, "all-nodes"),
  26. Name: "All Nodes",
  27. MetaData: "This Policy allows all nodes in the network to communicate with each other",
  28. Default: true,
  29. NetworkID: netID,
  30. RuleType: models.DevicePolicy,
  31. Src: []models.AclPolicyTag{
  32. {
  33. ID: models.DeviceAclID,
  34. Value: "*",
  35. }},
  36. Dst: []models.AclPolicyTag{
  37. {
  38. ID: models.DeviceAclID,
  39. Value: "*",
  40. }},
  41. AllowedDirection: models.TrafficDirectionBi,
  42. Enabled: true,
  43. CreatedBy: "auto",
  44. CreatedAt: time.Now().UTC(),
  45. }
  46. InsertAcl(defaultDeviceAcl)
  47. }
  48. if !IsAclExists(fmt.Sprintf("%s.%s", netID, "all-users")) {
  49. defaultUserAcl := models.Acl{
  50. ID: fmt.Sprintf("%s.%s", netID, "all-users"),
  51. Default: true,
  52. Name: "All Users",
  53. MetaData: "This policy gives access to everything in the network for an user",
  54. NetworkID: netID,
  55. RuleType: models.UserPolicy,
  56. Src: []models.AclPolicyTag{
  57. {
  58. ID: models.UserAclID,
  59. Value: "*",
  60. },
  61. },
  62. Dst: []models.AclPolicyTag{{
  63. ID: models.DeviceAclID,
  64. Value: "*",
  65. }},
  66. AllowedDirection: models.TrafficDirectionUni,
  67. Enabled: true,
  68. CreatedBy: "auto",
  69. CreatedAt: time.Now().UTC(),
  70. }
  71. InsertAcl(defaultUserAcl)
  72. }
  73. if !IsAclExists(fmt.Sprintf("%s.%s", netID, "all-remote-access-gws")) {
  74. defaultUserAcl := models.Acl{
  75. ID: fmt.Sprintf("%s.%s", netID, "all-remote-access-gws"),
  76. Default: true,
  77. Name: "All Remote Access Gateways",
  78. NetworkID: netID,
  79. RuleType: models.DevicePolicy,
  80. Src: []models.AclPolicyTag{
  81. {
  82. ID: models.DeviceAclID,
  83. Value: fmt.Sprintf("%s.%s", netID, models.RemoteAccessTagName),
  84. },
  85. },
  86. Dst: []models.AclPolicyTag{
  87. {
  88. ID: models.DeviceAclID,
  89. Value: "*",
  90. },
  91. },
  92. AllowedDirection: models.TrafficDirectionBi,
  93. Enabled: true,
  94. CreatedBy: "auto",
  95. CreatedAt: time.Now().UTC(),
  96. }
  97. InsertAcl(defaultUserAcl)
  98. }
  99. CreateDefaultUserPolicies(netID)
  100. }
  101. // DeleteDefaultNetworkPolicies - deletes all default network acl policies
  102. func DeleteDefaultNetworkPolicies(netId models.NetworkID) {
  103. acls, _ := ListAcls(netId)
  104. for _, acl := range acls {
  105. if acl.NetworkID == netId && acl.Default {
  106. DeleteAcl(acl)
  107. }
  108. }
  109. }
  110. // ValidateCreateAclReq - validates create req for acl
  111. func ValidateCreateAclReq(req models.Acl) error {
  112. // check if acl network exists
  113. _, err := GetNetwork(req.NetworkID.String())
  114. if err != nil {
  115. return errors.New("failed to get network details for " + req.NetworkID.String())
  116. }
  117. // err = CheckIDSyntax(req.Name)
  118. // if err != nil {
  119. // return err
  120. // }
  121. return nil
  122. }
  123. func listAclFromCache() (acls []models.Acl) {
  124. aclCacheMutex.RLock()
  125. defer aclCacheMutex.RUnlock()
  126. for _, acl := range aclCacheMap {
  127. acls = append(acls, acl)
  128. }
  129. return
  130. }
  131. func storeAclInCache(a models.Acl) {
  132. aclCacheMutex.Lock()
  133. defer aclCacheMutex.Unlock()
  134. aclCacheMap[a.ID] = a
  135. }
  136. func removeAclFromCache(a models.Acl) {
  137. aclCacheMutex.Lock()
  138. defer aclCacheMutex.Unlock()
  139. delete(aclCacheMap, a.ID)
  140. }
  141. func getAclFromCache(aID string) (a models.Acl, ok bool) {
  142. aclCacheMutex.RLock()
  143. defer aclCacheMutex.RUnlock()
  144. a, ok = aclCacheMap[aID]
  145. return
  146. }
  147. // InsertAcl - creates acl policy
  148. func InsertAcl(a models.Acl) error {
  149. d, err := json.Marshal(a)
  150. if err != nil {
  151. return err
  152. }
  153. err = database.Insert(a.ID, string(d), database.ACLS_TABLE_NAME)
  154. if err == nil && servercfg.CacheEnabled() {
  155. storeAclInCache(a)
  156. }
  157. return err
  158. }
  159. // GetAcl - gets acl info by id
  160. func GetAcl(aID string) (models.Acl, error) {
  161. a := models.Acl{}
  162. if servercfg.CacheEnabled() {
  163. if len(aclCacheMap) == 0 {
  164. _ = listAcls()
  165. }
  166. var ok bool
  167. a, ok = getAclFromCache(aID)
  168. if ok {
  169. return a, nil
  170. }
  171. }
  172. d, err := database.FetchRecord(database.ACLS_TABLE_NAME, aID)
  173. if err != nil {
  174. return a, err
  175. }
  176. err = json.Unmarshal([]byte(d), &a)
  177. if err != nil {
  178. return a, err
  179. }
  180. if servercfg.CacheEnabled() {
  181. storeAclInCache(a)
  182. }
  183. return a, nil
  184. }
  185. // IsAclExists - checks if acl exists
  186. func IsAclExists(aclID string) bool {
  187. _, err := GetAcl(aclID)
  188. return err == nil
  189. }
  190. // IsAclPolicyValid - validates if acl policy is valid
  191. func IsAclPolicyValid(acl models.Acl) bool {
  192. //check if src and dst are valid
  193. if acl.AllowedDirection != models.TrafficDirectionBi &&
  194. acl.AllowedDirection != models.TrafficDirectionUni {
  195. return false
  196. }
  197. switch acl.RuleType {
  198. case models.UserPolicy:
  199. // src list should only contain users
  200. for _, srcI := range acl.Src {
  201. if srcI.ID == "" || srcI.Value == "" {
  202. return false
  203. }
  204. if srcI.Value == "*" {
  205. continue
  206. }
  207. if srcI.ID != models.UserAclID && srcI.ID != models.UserGroupAclID {
  208. return false
  209. }
  210. // check if user group is valid
  211. if srcI.ID == models.UserAclID {
  212. _, err := GetUser(srcI.Value)
  213. if err != nil {
  214. return false
  215. }
  216. } else if srcI.ID == models.UserGroupAclID {
  217. err := IsGroupValid(models.UserGroupID(srcI.Value))
  218. if err != nil {
  219. return false
  220. }
  221. // check if group belongs to this network
  222. netGrps := GetUserGroupsInNetwork(acl.NetworkID)
  223. if _, ok := netGrps[models.UserGroupID(srcI.Value)]; !ok {
  224. return false
  225. }
  226. }
  227. }
  228. for _, dstI := range acl.Dst {
  229. if dstI.ID == "" || dstI.Value == "" {
  230. return false
  231. }
  232. if dstI.ID != models.DeviceAclID {
  233. return false
  234. }
  235. if dstI.Value == "*" {
  236. continue
  237. }
  238. // check if tag is valid
  239. _, err := GetTag(models.TagID(dstI.Value))
  240. if err != nil {
  241. return false
  242. }
  243. }
  244. case models.DevicePolicy:
  245. for _, srcI := range acl.Src {
  246. if srcI.ID == "" || srcI.Value == "" {
  247. return false
  248. }
  249. if srcI.ID != models.DeviceAclID {
  250. return false
  251. }
  252. if srcI.Value == "*" {
  253. continue
  254. }
  255. // check if tag is valid
  256. _, err := GetTag(models.TagID(srcI.Value))
  257. if err != nil {
  258. return false
  259. }
  260. }
  261. for _, dstI := range acl.Dst {
  262. if dstI.ID == "" || dstI.Value == "" {
  263. return false
  264. }
  265. if dstI.ID != models.DeviceAclID {
  266. return false
  267. }
  268. if dstI.Value == "*" {
  269. continue
  270. }
  271. // check if tag is valid
  272. _, err := GetTag(models.TagID(dstI.Value))
  273. if err != nil {
  274. return false
  275. }
  276. }
  277. }
  278. return true
  279. }
  280. // UpdateAcl - updates allowed fields on acls and commits to DB
  281. func UpdateAcl(newAcl, acl models.Acl) error {
  282. if !acl.Default {
  283. acl.Name = newAcl.Name
  284. acl.Src = newAcl.Src
  285. acl.Dst = newAcl.Dst
  286. acl.AllowedDirection = newAcl.AllowedDirection
  287. acl.Port = newAcl.Port
  288. acl.Proto = newAcl.Proto
  289. }
  290. acl.Enabled = newAcl.Enabled
  291. d, err := json.Marshal(acl)
  292. if err != nil {
  293. return err
  294. }
  295. err = database.Insert(acl.ID, string(d), database.ACLS_TABLE_NAME)
  296. if err == nil && servercfg.CacheEnabled() {
  297. storeAclInCache(acl)
  298. }
  299. return err
  300. }
  301. // UpsertAcl - upserts acl
  302. func UpsertAcl(acl models.Acl) error {
  303. d, err := json.Marshal(acl)
  304. if err != nil {
  305. return err
  306. }
  307. err = database.Insert(acl.ID, string(d), database.ACLS_TABLE_NAME)
  308. if err == nil && servercfg.CacheEnabled() {
  309. storeAclInCache(acl)
  310. }
  311. return err
  312. }
  313. // DeleteAcl - deletes acl policy
  314. func DeleteAcl(a models.Acl) error {
  315. err := database.DeleteRecord(database.ACLS_TABLE_NAME, a.ID)
  316. if err == nil && servercfg.CacheEnabled() {
  317. removeAclFromCache(a)
  318. }
  319. return err
  320. }
  321. // GetDefaultPolicy - fetches default policy in the network by ruleType
  322. func GetDefaultPolicy(netID models.NetworkID, ruleType models.AclPolicyType) (models.Acl, error) {
  323. aclID := "all-users"
  324. if ruleType == models.DevicePolicy {
  325. aclID = "all-nodes"
  326. }
  327. acl, err := GetAcl(fmt.Sprintf("%s.%s", netID, aclID))
  328. if err != nil {
  329. return models.Acl{}, errors.New("default rule not found")
  330. }
  331. if acl.Enabled {
  332. return acl, nil
  333. }
  334. // check if there are any custom all policies
  335. policies, _ := ListAcls(netID)
  336. for _, policy := range policies {
  337. if !policy.Enabled {
  338. continue
  339. }
  340. if policy.RuleType == ruleType {
  341. dstMap := convAclTagToValueMap(policy.Dst)
  342. srcMap := convAclTagToValueMap(policy.Src)
  343. if _, ok := srcMap["*"]; ok {
  344. if _, ok := dstMap["*"]; ok {
  345. return policy, nil
  346. }
  347. }
  348. }
  349. }
  350. return acl, nil
  351. }
  352. func listAcls() (acls []models.Acl) {
  353. if servercfg.CacheEnabled() && len(aclCacheMap) > 0 {
  354. return listAclFromCache()
  355. }
  356. data, err := database.FetchRecords(database.ACLS_TABLE_NAME)
  357. if err != nil && !database.IsEmptyRecord(err) {
  358. return []models.Acl{}
  359. }
  360. fmt.Println("===> ACL Db DATA: ", data)
  361. for _, dataI := range data {
  362. acl := models.Acl{}
  363. err := json.Unmarshal([]byte(dataI), &acl)
  364. if err != nil {
  365. fmt.Println("======> UNMARSHAL ERROR ACLS ", err)
  366. continue
  367. }
  368. acls = append(acls, acl)
  369. if servercfg.CacheEnabled() {
  370. storeAclInCache(acl)
  371. }
  372. }
  373. return
  374. }
  375. // ListUserPolicies - lists all acl policies enforced on an user
  376. func ListUserPolicies(u models.User) []models.Acl {
  377. allAcls := listAcls()
  378. userAcls := []models.Acl{}
  379. for _, acl := range allAcls {
  380. if acl.RuleType == models.UserPolicy {
  381. srcMap := convAclTagToValueMap(acl.Src)
  382. if _, ok := srcMap[u.UserName]; ok {
  383. userAcls = append(userAcls, acl)
  384. } else {
  385. // check for user groups
  386. for gID := range u.UserGroups {
  387. if _, ok := srcMap[gID.String()]; ok {
  388. userAcls = append(userAcls, acl)
  389. break
  390. }
  391. }
  392. }
  393. }
  394. }
  395. return userAcls
  396. }
  397. // listPoliciesOfUser - lists all user acl policies applied to user in an network
  398. func listPoliciesOfUser(user models.User, netID models.NetworkID) []models.Acl {
  399. allAcls := listAcls()
  400. userAcls := []models.Acl{}
  401. for _, acl := range allAcls {
  402. if acl.NetworkID == netID && acl.RuleType == models.UserPolicy {
  403. srcMap := convAclTagToValueMap(acl.Src)
  404. if _, ok := srcMap[user.UserName]; ok {
  405. userAcls = append(userAcls, acl)
  406. continue
  407. }
  408. for netRole := range user.NetworkRoles {
  409. if _, ok := srcMap[netRole.String()]; ok {
  410. userAcls = append(userAcls, acl)
  411. continue
  412. }
  413. }
  414. for userG := range user.UserGroups {
  415. if _, ok := srcMap[userG.String()]; ok {
  416. userAcls = append(userAcls, acl)
  417. continue
  418. }
  419. }
  420. }
  421. }
  422. return userAcls
  423. }
  424. // listDevicePolicies - lists all device policies in a network
  425. func listDevicePolicies(netID models.NetworkID) []models.Acl {
  426. allAcls := listAcls()
  427. deviceAcls := []models.Acl{}
  428. for _, acl := range allAcls {
  429. if acl.NetworkID == netID && acl.RuleType == models.DevicePolicy {
  430. deviceAcls = append(deviceAcls, acl)
  431. }
  432. }
  433. return deviceAcls
  434. }
  435. // ListAcls - lists all acl policies
  436. func ListAcls(netID models.NetworkID) ([]models.Acl, error) {
  437. allAcls := listAcls()
  438. netAcls := []models.Acl{}
  439. for _, acl := range allAcls {
  440. if acl.NetworkID == netID {
  441. netAcls = append(netAcls, acl)
  442. }
  443. }
  444. return netAcls, nil
  445. }
  446. func convAclTagToValueMap(acltags []models.AclPolicyTag) map[string]struct{} {
  447. aclValueMap := make(map[string]struct{})
  448. for _, aclTagI := range acltags {
  449. aclValueMap[aclTagI.Value] = struct{}{}
  450. }
  451. return aclValueMap
  452. }
  453. // IsUserAllowedToCommunicate - check if user is allowed to communicate with peer
  454. func IsUserAllowedToCommunicate(userName string, peer models.Node) bool {
  455. if peer.IsStatic {
  456. peer = peer.StaticNode.ConvertToStaticNode()
  457. }
  458. acl, _ := GetDefaultPolicy(models.NetworkID(peer.Network), models.UserPolicy)
  459. if acl.Enabled {
  460. return true
  461. }
  462. user, err := GetUser(userName)
  463. if err != nil {
  464. return false
  465. }
  466. policies := listPoliciesOfUser(*user, models.NetworkID(peer.Network))
  467. for _, policy := range policies {
  468. if !policy.Enabled {
  469. continue
  470. }
  471. dstMap := convAclTagToValueMap(policy.Dst)
  472. if _, ok := dstMap["*"]; ok {
  473. return true
  474. }
  475. for tagID := range peer.Tags {
  476. if _, ok := dstMap[tagID.String()]; ok {
  477. return true
  478. }
  479. }
  480. }
  481. return false
  482. }
  483. // IsNodeAllowedToCommunicate - check node is allowed to communicate with the peer
  484. func IsNodeAllowedToCommunicate(node, peer models.Node) bool {
  485. if node.IsStatic {
  486. node = node.StaticNode.ConvertToStaticNode()
  487. }
  488. if peer.IsStatic {
  489. peer = peer.StaticNode.ConvertToStaticNode()
  490. }
  491. // check default policy if all allowed return true
  492. defaultPolicy, err := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  493. if err == nil {
  494. if defaultPolicy.Enabled {
  495. return true
  496. }
  497. }
  498. // list device policies
  499. policies := listDevicePolicies(models.NetworkID(peer.Network))
  500. for _, policy := range policies {
  501. if !policy.Enabled {
  502. continue
  503. }
  504. srcMap := convAclTagToValueMap(policy.Src)
  505. dstMap := convAclTagToValueMap(policy.Dst)
  506. // fmt.Printf("\n======> SRCMAP: %+v\n", srcMap)
  507. // fmt.Printf("\n======> DSTMAP: %+v\n", dstMap)
  508. // fmt.Printf("\n======> node Tags: %+v\n", node.Tags)
  509. // fmt.Printf("\n======> peer Tags: %+v\n", peer.Tags)
  510. for tagID := range node.Tags {
  511. if _, ok := dstMap[tagID.String()]; ok {
  512. if _, ok := srcMap["*"]; ok {
  513. return true
  514. }
  515. for tagID := range peer.Tags {
  516. if _, ok := srcMap[tagID.String()]; ok {
  517. return true
  518. }
  519. }
  520. }
  521. if _, ok := srcMap[tagID.String()]; ok {
  522. if _, ok := dstMap["*"]; ok {
  523. return true
  524. }
  525. for tagID := range peer.Tags {
  526. if _, ok := dstMap[tagID.String()]; ok {
  527. return true
  528. }
  529. }
  530. }
  531. }
  532. for tagID := range peer.Tags {
  533. if _, ok := dstMap[tagID.String()]; ok {
  534. if _, ok := srcMap["*"]; ok {
  535. return true
  536. }
  537. for tagID := range node.Tags {
  538. if _, ok := srcMap[tagID.String()]; ok {
  539. return true
  540. }
  541. }
  542. }
  543. if _, ok := srcMap[tagID.String()]; ok {
  544. if _, ok := dstMap["*"]; ok {
  545. return true
  546. }
  547. for tagID := range node.Tags {
  548. if _, ok := dstMap[tagID.String()]; ok {
  549. return true
  550. }
  551. }
  552. }
  553. }
  554. }
  555. return false
  556. }
  557. // SortTagEntrys - Sorts slice of Tag entries by their id
  558. func SortAclEntrys(acls []models.Acl) {
  559. sort.Slice(acls, func(i, j int) bool {
  560. return acls[i].Name < acls[j].Name
  561. })
  562. }
  563. // UpdateDeviceTag - updates device tag on acl policies
  564. func UpdateDeviceTag(OldID, newID models.TagID, netID models.NetworkID) {
  565. acls := listDevicePolicies(netID)
  566. update := false
  567. for _, acl := range acls {
  568. for i, srcTagI := range acl.Src {
  569. if srcTagI.ID == models.DeviceAclID {
  570. if OldID.String() == srcTagI.Value {
  571. acl.Src[i].Value = newID.String()
  572. update = true
  573. }
  574. }
  575. }
  576. for i, dstTagI := range acl.Dst {
  577. if dstTagI.ID == models.DeviceAclID {
  578. if OldID.String() == dstTagI.Value {
  579. acl.Dst[i].Value = newID.String()
  580. update = true
  581. }
  582. }
  583. }
  584. if update {
  585. UpsertAcl(acl)
  586. }
  587. }
  588. }
  589. func CheckIfTagAsActivePolicy(tagID models.TagID, netID models.NetworkID) bool {
  590. acls := listDevicePolicies(netID)
  591. for _, acl := range acls {
  592. for _, srcTagI := range acl.Src {
  593. if srcTagI.ID == models.DeviceAclID {
  594. if tagID.String() == srcTagI.Value {
  595. return true
  596. }
  597. }
  598. }
  599. for _, dstTagI := range acl.Dst {
  600. if dstTagI.ID == models.DeviceAclID {
  601. return true
  602. }
  603. }
  604. }
  605. return false
  606. }
  607. // RemoveDeviceTagFromAclPolicies - remove device tag from acl policies
  608. func RemoveDeviceTagFromAclPolicies(tagID models.TagID, netID models.NetworkID) error {
  609. acls := listDevicePolicies(netID)
  610. update := false
  611. for _, acl := range acls {
  612. for i, srcTagI := range acl.Src {
  613. if srcTagI.ID == models.DeviceAclID {
  614. if tagID.String() == srcTagI.Value {
  615. acl.Src = append(acl.Src[:i], acl.Src[i+1:]...)
  616. update = true
  617. }
  618. }
  619. }
  620. for i, dstTagI := range acl.Dst {
  621. if dstTagI.ID == models.DeviceAclID {
  622. if tagID.String() == dstTagI.Value {
  623. acl.Dst = append(acl.Dst[:i], acl.Dst[i+1:]...)
  624. update = true
  625. }
  626. }
  627. }
  628. if update {
  629. UpsertAcl(acl)
  630. }
  631. }
  632. return nil
  633. }
  634. func GetAclRulesForNode(node *models.Node) (rules map[string]models.AclRule) {
  635. defaultPolicy, err := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  636. rules = make(map[string]models.AclRule)
  637. if err == nil && defaultPolicy.Enabled {
  638. return map[string]models.AclRule{
  639. defaultPolicy.ID: {
  640. IPList: []net.IPNet{node.NetworkRange},
  641. IP6List: []net.IPNet{node.NetworkRange6},
  642. AllowedProtocols: []models.Protocol{models.ALL},
  643. Direction: models.TrafficDirectionBi,
  644. Allowed: true,
  645. },
  646. }
  647. }
  648. taggedNodes := GetTagMapWithNodesByNetwork(models.NetworkID(node.Network))
  649. acls := listDevicePolicies(models.NetworkID(node.Network))
  650. //allowedNodeUniqueMap := make(map[string]struct{})
  651. for nodeTag := range node.Tags {
  652. for _, acl := range acls {
  653. if acl.Default || !acl.Enabled {
  654. continue
  655. }
  656. srcTags := convAclTagToValueMap(acl.Src)
  657. dstTags := convAclTagToValueMap(acl.Dst)
  658. aclRule := models.AclRule{
  659. ID: acl.ID,
  660. AllowedProtocols: acl.Proto,
  661. AllowedPorts: acl.Port,
  662. Direction: acl.AllowedDirection,
  663. Allowed: true,
  664. }
  665. if acl.AllowedDirection == models.TrafficDirectionBi {
  666. var existsInSrcTag bool
  667. var existsInDstTag bool
  668. // if contains all resources, return entire cidr
  669. if _, ok := srcTags["*"]; ok {
  670. return map[string]models.AclRule{
  671. acl.ID: {
  672. IPList: []net.IPNet{node.NetworkRange},
  673. IP6List: []net.IPNet{node.NetworkRange6},
  674. AllowedProtocols: []models.Protocol{models.ALL},
  675. AllowedPorts: acl.Port,
  676. Direction: acl.AllowedDirection,
  677. Allowed: true,
  678. },
  679. }
  680. }
  681. if _, ok := dstTags["*"]; ok {
  682. return map[string]models.AclRule{
  683. acl.ID: {
  684. IPList: []net.IPNet{node.NetworkRange},
  685. IP6List: []net.IPNet{node.NetworkRange6},
  686. AllowedProtocols: []models.Protocol{models.ALL},
  687. AllowedPorts: acl.Port,
  688. Direction: acl.AllowedDirection,
  689. Allowed: true,
  690. },
  691. }
  692. }
  693. if _, ok := srcTags[nodeTag.String()]; ok {
  694. existsInSrcTag = true
  695. }
  696. if _, ok := dstTags[nodeTag.String()]; ok {
  697. existsInDstTag = true
  698. }
  699. if existsInSrcTag {
  700. // get all dst tags
  701. for dst := range dstTags {
  702. if dst == nodeTag.String() {
  703. continue
  704. }
  705. // Get peers in the tags and add allowed rules
  706. nodes := taggedNodes[models.TagID(dst)]
  707. for _, node := range nodes {
  708. if node.Address.IP != nil {
  709. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  710. }
  711. if node.Address6.IP != nil {
  712. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  713. }
  714. }
  715. }
  716. }
  717. if existsInDstTag {
  718. // get all src tags
  719. for src := range srcTags {
  720. if src == nodeTag.String() {
  721. continue
  722. }
  723. // Get peers in the tags and add allowed rules
  724. nodes := taggedNodes[models.TagID(src)]
  725. for _, node := range nodes {
  726. if node.Address.IP != nil {
  727. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  728. }
  729. if node.Address6.IP != nil {
  730. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  731. }
  732. }
  733. }
  734. }
  735. if existsInDstTag && existsInSrcTag {
  736. nodes := taggedNodes[nodeTag]
  737. for _, node := range nodes {
  738. if node.Address.IP != nil {
  739. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  740. }
  741. if node.Address6.IP != nil {
  742. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  743. }
  744. }
  745. }
  746. } else {
  747. if _, ok := dstTags[nodeTag.String()]; ok {
  748. // get all src tags
  749. for src := range srcTags {
  750. if src == nodeTag.String() {
  751. continue
  752. }
  753. // Get peers in the tags and add allowed rules
  754. nodes := taggedNodes[models.TagID(src)]
  755. for _, node := range nodes {
  756. if node.Address.IP != nil {
  757. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  758. }
  759. if node.Address6.IP != nil {
  760. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  761. }
  762. }
  763. }
  764. }
  765. }
  766. if len(aclRule.IPList) > 0 || len(aclRule.IP6List) > 0 {
  767. rules[acl.ID] = aclRule
  768. }
  769. }
  770. }
  771. return rules
  772. }