acls.go 24 KB

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