acls.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  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. if newAcl.ServiceType == models.Any {
  306. acl.Port = []string{}
  307. acl.Proto = models.ALL
  308. }
  309. acl.Enabled = newAcl.Enabled
  310. d, err := json.Marshal(acl)
  311. if err != nil {
  312. return err
  313. }
  314. err = database.Insert(acl.ID, string(d), database.ACLS_TABLE_NAME)
  315. if err == nil && servercfg.CacheEnabled() {
  316. storeAclInCache(acl)
  317. }
  318. return err
  319. }
  320. // UpsertAcl - upserts acl
  321. func UpsertAcl(acl models.Acl) error {
  322. d, err := json.Marshal(acl)
  323. if err != nil {
  324. return err
  325. }
  326. err = database.Insert(acl.ID, string(d), database.ACLS_TABLE_NAME)
  327. if err == nil && servercfg.CacheEnabled() {
  328. storeAclInCache(acl)
  329. }
  330. return err
  331. }
  332. // DeleteAcl - deletes acl policy
  333. func DeleteAcl(a models.Acl) error {
  334. err := database.DeleteRecord(database.ACLS_TABLE_NAME, a.ID)
  335. if err == nil && servercfg.CacheEnabled() {
  336. removeAclFromCache(a)
  337. }
  338. return err
  339. }
  340. // GetDefaultPolicy - fetches default policy in the network by ruleType
  341. func GetDefaultPolicy(netID models.NetworkID, ruleType models.AclPolicyType) (models.Acl, error) {
  342. aclID := "all-users"
  343. if ruleType == models.DevicePolicy {
  344. aclID = "all-nodes"
  345. }
  346. acl, err := GetAcl(fmt.Sprintf("%s.%s", netID, aclID))
  347. if err != nil {
  348. return models.Acl{}, errors.New("default rule not found")
  349. }
  350. if acl.Enabled {
  351. return acl, nil
  352. }
  353. // check if there are any custom all policies
  354. srcMap := make(map[string]struct{})
  355. dstMap := make(map[string]struct{})
  356. defer func() {
  357. srcMap = nil
  358. dstMap = nil
  359. }()
  360. policies, _ := ListAclsByNetwork(netID)
  361. for _, policy := range policies {
  362. if !policy.Enabled {
  363. continue
  364. }
  365. if policy.RuleType == ruleType {
  366. dstMap = convAclTagToValueMap(policy.Dst)
  367. srcMap = convAclTagToValueMap(policy.Src)
  368. if _, ok := srcMap["*"]; ok {
  369. if _, ok := dstMap["*"]; ok {
  370. return policy, nil
  371. }
  372. }
  373. }
  374. }
  375. return acl, nil
  376. }
  377. func ListAcls() (acls []models.Acl) {
  378. if servercfg.CacheEnabled() && len(aclCacheMap) > 0 {
  379. return listAclFromCache()
  380. }
  381. data, err := database.FetchRecords(database.ACLS_TABLE_NAME)
  382. if err != nil && !database.IsEmptyRecord(err) {
  383. return []models.Acl{}
  384. }
  385. for _, dataI := range data {
  386. acl := models.Acl{}
  387. err := json.Unmarshal([]byte(dataI), &acl)
  388. if err != nil {
  389. continue
  390. }
  391. acls = append(acls, acl)
  392. if servercfg.CacheEnabled() {
  393. storeAclInCache(acl)
  394. }
  395. }
  396. return
  397. }
  398. // ListUserPolicies - lists all acl policies enforced on an user
  399. func ListUserPolicies(u models.User) []models.Acl {
  400. allAcls := ListAcls()
  401. userAcls := []models.Acl{}
  402. for _, acl := range allAcls {
  403. if acl.RuleType == models.UserPolicy {
  404. srcMap := convAclTagToValueMap(acl.Src)
  405. if _, ok := srcMap[u.UserName]; ok {
  406. userAcls = append(userAcls, acl)
  407. } else {
  408. // check for user groups
  409. for gID := range u.UserGroups {
  410. if _, ok := srcMap[gID.String()]; ok {
  411. userAcls = append(userAcls, acl)
  412. break
  413. }
  414. }
  415. }
  416. }
  417. }
  418. return userAcls
  419. }
  420. // listPoliciesOfUser - lists all user acl policies applied to user in an network
  421. func listPoliciesOfUser(user models.User, netID models.NetworkID) []models.Acl {
  422. allAcls := ListAcls()
  423. userAcls := []models.Acl{}
  424. for _, acl := range allAcls {
  425. if acl.NetworkID == netID && acl.RuleType == models.UserPolicy {
  426. srcMap := convAclTagToValueMap(acl.Src)
  427. if _, ok := srcMap[user.UserName]; ok {
  428. userAcls = append(userAcls, acl)
  429. continue
  430. }
  431. for netRole := range user.NetworkRoles {
  432. if _, ok := srcMap[netRole.String()]; ok {
  433. userAcls = append(userAcls, acl)
  434. continue
  435. }
  436. }
  437. for userG := range user.UserGroups {
  438. if _, ok := srcMap[userG.String()]; ok {
  439. userAcls = append(userAcls, acl)
  440. continue
  441. }
  442. }
  443. }
  444. }
  445. return userAcls
  446. }
  447. // listDevicePolicies - lists all device policies in a network
  448. func listDevicePolicies(netID models.NetworkID) []models.Acl {
  449. allAcls := ListAcls()
  450. deviceAcls := []models.Acl{}
  451. for _, acl := range allAcls {
  452. if acl.NetworkID == netID && acl.RuleType == models.DevicePolicy {
  453. deviceAcls = append(deviceAcls, acl)
  454. }
  455. }
  456. return deviceAcls
  457. }
  458. // listUserPolicies - lists all user policies in a network
  459. func listUserPolicies(netID models.NetworkID) []models.Acl {
  460. allAcls := ListAcls()
  461. deviceAcls := []models.Acl{}
  462. for _, acl := range allAcls {
  463. if acl.NetworkID == netID && acl.RuleType == models.UserPolicy {
  464. deviceAcls = append(deviceAcls, acl)
  465. }
  466. }
  467. return deviceAcls
  468. }
  469. // ListAcls - lists all acl policies
  470. func ListAclsByNetwork(netID models.NetworkID) ([]models.Acl, error) {
  471. allAcls := ListAcls()
  472. netAcls := []models.Acl{}
  473. for _, acl := range allAcls {
  474. if acl.NetworkID == netID {
  475. netAcls = append(netAcls, acl)
  476. }
  477. }
  478. return netAcls, nil
  479. }
  480. func convAclTagToValueMap(acltags []models.AclPolicyTag) map[string]struct{} {
  481. aclValueMap := make(map[string]struct{})
  482. for _, aclTagI := range acltags {
  483. aclValueMap[aclTagI.Value] = struct{}{}
  484. }
  485. return aclValueMap
  486. }
  487. // IsUserAllowedToCommunicate - check if user is allowed to communicate with peer
  488. func IsUserAllowedToCommunicate(userName string, peer models.Node) (bool, []models.Acl) {
  489. if peer.IsStatic {
  490. peer = peer.StaticNode.ConvertToStaticNode()
  491. }
  492. acl, _ := GetDefaultPolicy(models.NetworkID(peer.Network), models.UserPolicy)
  493. if acl.Enabled {
  494. return true, []models.Acl{acl}
  495. }
  496. user, err := GetUser(userName)
  497. if err != nil {
  498. return false, []models.Acl{}
  499. }
  500. allowedPolicies := []models.Acl{}
  501. policies := listPoliciesOfUser(*user, models.NetworkID(peer.Network))
  502. for _, policy := range policies {
  503. if !policy.Enabled {
  504. continue
  505. }
  506. dstMap := convAclTagToValueMap(policy.Dst)
  507. if _, ok := dstMap["*"]; ok {
  508. allowedPolicies = append(allowedPolicies, policy)
  509. continue
  510. }
  511. for tagID := range peer.Tags {
  512. if _, ok := dstMap[tagID.String()]; ok {
  513. allowedPolicies = append(allowedPolicies, policy)
  514. break
  515. }
  516. }
  517. }
  518. if len(allowedPolicies) > 0 {
  519. return true, allowedPolicies
  520. }
  521. return false, []models.Acl{}
  522. }
  523. // IsNodeAllowedToCommunicate - check node is allowed to communicate with the peer
  524. func IsNodeAllowedToCommunicate(node, peer models.Node, checkDefaultPolicy bool) (bool, []models.Acl) {
  525. if node.IsStatic {
  526. node = node.StaticNode.ConvertToStaticNode()
  527. }
  528. if peer.IsStatic {
  529. peer = peer.StaticNode.ConvertToStaticNode()
  530. }
  531. if checkDefaultPolicy {
  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. }
  540. allowedPolicies := []models.Acl{}
  541. // list device policies
  542. policies := listDevicePolicies(models.NetworkID(peer.Network))
  543. srcMap := make(map[string]struct{})
  544. dstMap := make(map[string]struct{})
  545. defer func() {
  546. srcMap = nil
  547. dstMap = nil
  548. }()
  549. for _, policy := range policies {
  550. if !policy.Enabled {
  551. continue
  552. }
  553. srcMap = convAclTagToValueMap(policy.Src)
  554. dstMap = convAclTagToValueMap(policy.Dst)
  555. for tagID := range node.Tags {
  556. allowed := false
  557. if _, ok := dstMap[tagID.String()]; policy.AllowedDirection == models.TrafficDirectionBi && ok {
  558. if _, ok := srcMap["*"]; ok {
  559. allowed = true
  560. allowedPolicies = append(allowedPolicies, policy)
  561. break
  562. }
  563. for tagID := range peer.Tags {
  564. if _, ok := srcMap[tagID.String()]; ok {
  565. allowed = true
  566. break
  567. }
  568. }
  569. }
  570. if allowed {
  571. allowedPolicies = append(allowedPolicies, policy)
  572. break
  573. }
  574. if _, ok := srcMap[tagID.String()]; ok {
  575. if _, ok := dstMap["*"]; ok {
  576. allowed = true
  577. allowedPolicies = append(allowedPolicies, policy)
  578. break
  579. }
  580. for tagID := range peer.Tags {
  581. if _, ok := dstMap[tagID.String()]; ok {
  582. allowed = true
  583. break
  584. }
  585. }
  586. }
  587. if allowed {
  588. allowedPolicies = append(allowedPolicies, policy)
  589. break
  590. }
  591. }
  592. for tagID := range peer.Tags {
  593. allowed := false
  594. if _, ok := dstMap[tagID.String()]; ok {
  595. if _, ok := srcMap["*"]; ok {
  596. allowed = true
  597. allowedPolicies = append(allowedPolicies, policy)
  598. break
  599. }
  600. for tagID := range node.Tags {
  601. if _, ok := srcMap[tagID.String()]; ok {
  602. allowed = true
  603. break
  604. }
  605. }
  606. }
  607. if allowed {
  608. allowedPolicies = append(allowedPolicies, policy)
  609. break
  610. }
  611. if _, ok := srcMap[tagID.String()]; policy.AllowedDirection == models.TrafficDirectionBi && ok {
  612. if _, ok := dstMap["*"]; ok {
  613. allowed = true
  614. allowedPolicies = append(allowedPolicies, policy)
  615. break
  616. }
  617. for tagID := range node.Tags {
  618. if _, ok := dstMap[tagID.String()]; ok {
  619. allowed = true
  620. break
  621. }
  622. }
  623. }
  624. if allowed {
  625. allowedPolicies = append(allowedPolicies, policy)
  626. break
  627. }
  628. }
  629. }
  630. if len(allowedPolicies) > 0 {
  631. return true, allowedPolicies
  632. }
  633. return false, allowedPolicies
  634. }
  635. // SortTagEntrys - Sorts slice of Tag entries by their id
  636. func SortAclEntrys(acls []models.Acl) {
  637. sort.Slice(acls, func(i, j int) bool {
  638. return acls[i].Name < acls[j].Name
  639. })
  640. }
  641. // UpdateDeviceTag - updates device tag on acl policies
  642. func UpdateDeviceTag(OldID, newID models.TagID, netID models.NetworkID) {
  643. acls := listDevicePolicies(netID)
  644. update := false
  645. for _, acl := range acls {
  646. for i, srcTagI := range acl.Src {
  647. if srcTagI.ID == models.DeviceAclID {
  648. if OldID.String() == srcTagI.Value {
  649. acl.Src[i].Value = newID.String()
  650. update = true
  651. }
  652. }
  653. }
  654. for i, dstTagI := range acl.Dst {
  655. if dstTagI.ID == models.DeviceAclID {
  656. if OldID.String() == dstTagI.Value {
  657. acl.Dst[i].Value = newID.String()
  658. update = true
  659. }
  660. }
  661. }
  662. if update {
  663. UpsertAcl(acl)
  664. }
  665. }
  666. }
  667. func CheckIfTagAsActivePolicy(tagID models.TagID, netID models.NetworkID) bool {
  668. acls := listDevicePolicies(netID)
  669. for _, acl := range acls {
  670. for _, srcTagI := range acl.Src {
  671. if srcTagI.ID == models.DeviceAclID {
  672. if tagID.String() == srcTagI.Value {
  673. return true
  674. }
  675. }
  676. }
  677. for _, dstTagI := range acl.Dst {
  678. if dstTagI.ID == models.DeviceAclID {
  679. if tagID.String() == dstTagI.Value {
  680. return true
  681. }
  682. }
  683. }
  684. }
  685. return false
  686. }
  687. // RemoveDeviceTagFromAclPolicies - remove device tag from acl policies
  688. func RemoveDeviceTagFromAclPolicies(tagID models.TagID, netID models.NetworkID) error {
  689. acls := listDevicePolicies(netID)
  690. update := false
  691. for _, acl := range acls {
  692. for i, srcTagI := range acl.Src {
  693. if srcTagI.ID == models.DeviceAclID {
  694. if tagID.String() == srcTagI.Value {
  695. acl.Src = append(acl.Src[:i], acl.Src[i+1:]...)
  696. update = true
  697. }
  698. }
  699. }
  700. for i, dstTagI := range acl.Dst {
  701. if dstTagI.ID == models.DeviceAclID {
  702. if tagID.String() == dstTagI.Value {
  703. acl.Dst = append(acl.Dst[:i], acl.Dst[i+1:]...)
  704. update = true
  705. }
  706. }
  707. }
  708. if update {
  709. UpsertAcl(acl)
  710. }
  711. }
  712. return nil
  713. }
  714. func getUserAclRulesForNode(targetnode *models.Node,
  715. rules map[string]models.AclRule) map[string]models.AclRule {
  716. userNodes := GetStaticUserNodesByNetwork(models.NetworkID(targetnode.Network))
  717. userGrpMap := GetUserGrpMap()
  718. allowedUsers := make(map[string][]models.Acl)
  719. acls := listUserPolicies(models.NetworkID(targetnode.Network))
  720. for nodeTag := range targetnode.Tags {
  721. for _, acl := range acls {
  722. if !acl.Enabled {
  723. continue
  724. }
  725. dstTags := convAclTagToValueMap(acl.Dst)
  726. if _, ok := dstTags[nodeTag.String()]; ok {
  727. // get all src tags
  728. for _, srcAcl := range acl.Src {
  729. if srcAcl.ID == models.UserAclID {
  730. allowedUsers[srcAcl.Value] = append(allowedUsers[srcAcl.Value], acl)
  731. } else if srcAcl.ID == models.UserGroupAclID {
  732. // fetch all users in the group
  733. if usersMap, ok := userGrpMap[models.UserGroupID(srcAcl.Value)]; ok {
  734. for userName := range usersMap {
  735. allowedUsers[userName] = append(allowedUsers[userName], acl)
  736. }
  737. }
  738. }
  739. }
  740. }
  741. }
  742. }
  743. for _, userNode := range userNodes {
  744. if !userNode.StaticNode.Enabled {
  745. continue
  746. }
  747. acls, ok := allowedUsers[userNode.StaticNode.OwnerID]
  748. if !ok {
  749. continue
  750. }
  751. for _, acl := range acls {
  752. if !acl.Enabled {
  753. continue
  754. }
  755. r := models.AclRule{
  756. ID: acl.ID,
  757. AllowedProtocol: acl.Proto,
  758. AllowedPorts: acl.Port,
  759. Direction: acl.AllowedDirection,
  760. Allowed: true,
  761. }
  762. // Get peers in the tags and add allowed rules
  763. if userNode.StaticNode.Address != "" {
  764. r.IPList = append(r.IPList, userNode.StaticNode.AddressIPNet4())
  765. }
  766. if userNode.StaticNode.Address6 != "" {
  767. r.IP6List = append(r.IP6List, userNode.StaticNode.AddressIPNet6())
  768. }
  769. if aclRule, ok := rules[acl.ID]; ok {
  770. aclRule.IPList = append(aclRule.IPList, r.IPList...)
  771. aclRule.IP6List = append(aclRule.IP6List, r.IP6List...)
  772. rules[acl.ID] = aclRule
  773. } else {
  774. rules[acl.ID] = r
  775. }
  776. }
  777. }
  778. return rules
  779. }
  780. func GetAclRulesForNode(targetnode *models.Node) (rules map[string]models.AclRule) {
  781. defer func() {
  782. if !targetnode.IsIngressGateway {
  783. rules = getUserAclRulesForNode(targetnode, rules)
  784. }
  785. }()
  786. rules = make(map[string]models.AclRule)
  787. var taggedNodes map[models.TagID][]models.Node
  788. if targetnode.IsIngressGateway {
  789. taggedNodes = GetTagMapWithNodesByNetwork(models.NetworkID(targetnode.Network), false)
  790. } else {
  791. taggedNodes = GetTagMapWithNodesByNetwork(models.NetworkID(targetnode.Network), true)
  792. }
  793. acls := listDevicePolicies(models.NetworkID(targetnode.Network))
  794. targetnode.Tags["*"] = struct{}{}
  795. for nodeTag := range targetnode.Tags {
  796. for _, acl := range acls {
  797. if !acl.Enabled {
  798. continue
  799. }
  800. srcTags := convAclTagToValueMap(acl.Src)
  801. dstTags := convAclTagToValueMap(acl.Dst)
  802. aclRule := models.AclRule{
  803. ID: acl.ID,
  804. AllowedProtocol: acl.Proto,
  805. AllowedPorts: acl.Port,
  806. Direction: acl.AllowedDirection,
  807. Allowed: true,
  808. }
  809. if acl.AllowedDirection == models.TrafficDirectionBi {
  810. var existsInSrcTag bool
  811. var existsInDstTag bool
  812. if _, ok := srcTags[nodeTag.String()]; ok {
  813. existsInSrcTag = true
  814. }
  815. if _, ok := dstTags[nodeTag.String()]; ok {
  816. existsInDstTag = true
  817. }
  818. if existsInSrcTag && !existsInDstTag {
  819. // get all dst tags
  820. for dst := range dstTags {
  821. if dst == nodeTag.String() {
  822. continue
  823. }
  824. // Get peers in the tags and add allowed rules
  825. nodes := taggedNodes[models.TagID(dst)]
  826. for _, node := range nodes {
  827. if node.ID == targetnode.ID {
  828. continue
  829. }
  830. if node.Address.IP != nil {
  831. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  832. }
  833. if node.Address6.IP != nil {
  834. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  835. }
  836. if node.IsStatic && node.StaticNode.Address != "" {
  837. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  838. }
  839. if node.IsStatic && node.StaticNode.Address6 != "" {
  840. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  841. }
  842. }
  843. }
  844. }
  845. if existsInDstTag && !existsInSrcTag {
  846. // get all src tags
  847. for src := range srcTags {
  848. if src == nodeTag.String() {
  849. continue
  850. }
  851. // Get peers in the tags and add allowed rules
  852. nodes := taggedNodes[models.TagID(src)]
  853. for _, node := range nodes {
  854. if node.ID == targetnode.ID {
  855. continue
  856. }
  857. if node.Address.IP != nil {
  858. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  859. }
  860. if node.Address6.IP != nil {
  861. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  862. }
  863. if node.IsStatic && node.StaticNode.Address != "" {
  864. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  865. }
  866. if node.IsStatic && node.StaticNode.Address6 != "" {
  867. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  868. }
  869. }
  870. }
  871. }
  872. if existsInDstTag && existsInSrcTag {
  873. nodes := taggedNodes[nodeTag]
  874. for _, node := range nodes {
  875. if node.ID == targetnode.ID {
  876. continue
  877. }
  878. if node.Address.IP != nil {
  879. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  880. }
  881. if node.Address6.IP != nil {
  882. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  883. }
  884. if node.IsStatic && node.StaticNode.Address != "" {
  885. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  886. }
  887. if node.IsStatic && node.StaticNode.Address6 != "" {
  888. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  889. }
  890. }
  891. }
  892. } else {
  893. _, all := dstTags["*"]
  894. if _, ok := dstTags[nodeTag.String()]; ok || all {
  895. // get all src tags
  896. for src := range srcTags {
  897. if src == nodeTag.String() {
  898. continue
  899. }
  900. // Get peers in the tags and add allowed rules
  901. nodes := taggedNodes[models.TagID(src)]
  902. for _, node := range nodes {
  903. if node.ID == targetnode.ID {
  904. continue
  905. }
  906. if node.Address.IP != nil {
  907. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  908. }
  909. if node.Address6.IP != nil {
  910. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  911. }
  912. if node.IsStatic && node.StaticNode.Address != "" {
  913. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  914. }
  915. if node.IsStatic && node.StaticNode.Address6 != "" {
  916. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  917. }
  918. }
  919. }
  920. }
  921. }
  922. if len(aclRule.IPList) > 0 || len(aclRule.IP6List) > 0 {
  923. rules[acl.ID] = aclRule
  924. }
  925. }
  926. }
  927. return rules
  928. }