acls.go 22 KB

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