acls.go 27 KB

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