acls.go 27 KB

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