acls.go 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  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. // IsPeerAllowed - checks if peer needs to be added to the interface
  524. func IsPeerAllowed(node, peer models.Node, checkDefaultPolicy bool) bool {
  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
  537. }
  538. }
  539. }
  540. // list device policies
  541. policies := listDevicePolicies(models.NetworkID(peer.Network))
  542. srcMap := make(map[string]struct{})
  543. dstMap := make(map[string]struct{})
  544. defer func() {
  545. srcMap = nil
  546. dstMap = nil
  547. }()
  548. for _, policy := range policies {
  549. if !policy.Enabled {
  550. continue
  551. }
  552. srcMap = convAclTagToValueMap(policy.Src)
  553. dstMap = convAclTagToValueMap(policy.Dst)
  554. for tagID := range node.Tags {
  555. if _, ok := dstMap[tagID.String()]; ok {
  556. if _, ok := srcMap["*"]; ok {
  557. return true
  558. }
  559. for tagID := range peer.Tags {
  560. if _, ok := srcMap[tagID.String()]; ok {
  561. return true
  562. }
  563. }
  564. }
  565. if _, ok := srcMap[tagID.String()]; ok {
  566. if _, ok := dstMap["*"]; ok {
  567. return true
  568. }
  569. for tagID := range peer.Tags {
  570. if _, ok := dstMap[tagID.String()]; ok {
  571. return true
  572. }
  573. }
  574. }
  575. }
  576. for tagID := range peer.Tags {
  577. if _, ok := dstMap[tagID.String()]; ok {
  578. if _, ok := srcMap["*"]; ok {
  579. return true
  580. }
  581. for tagID := range node.Tags {
  582. if _, ok := srcMap[tagID.String()]; ok {
  583. return true
  584. }
  585. }
  586. }
  587. if _, ok := srcMap[tagID.String()]; ok {
  588. if _, ok := dstMap["*"]; ok {
  589. return true
  590. }
  591. for tagID := range node.Tags {
  592. if _, ok := dstMap[tagID.String()]; ok {
  593. return true
  594. }
  595. }
  596. }
  597. }
  598. }
  599. return false
  600. }
  601. // IsNodeAllowedToCommunicate - check node is allowed to communicate with the peer
  602. func IsNodeAllowedToCommunicate(node, peer models.Node, checkDefaultPolicy bool) (bool, []models.Acl) {
  603. if node.IsStatic {
  604. node = node.StaticNode.ConvertToStaticNode()
  605. }
  606. if peer.IsStatic {
  607. peer = peer.StaticNode.ConvertToStaticNode()
  608. }
  609. if checkDefaultPolicy {
  610. // check default policy if all allowed return true
  611. defaultPolicy, err := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  612. if err == nil {
  613. if defaultPolicy.Enabled {
  614. return true, []models.Acl{defaultPolicy}
  615. }
  616. }
  617. }
  618. allowedPolicies := []models.Acl{}
  619. // list device policies
  620. policies := listDevicePolicies(models.NetworkID(peer.Network))
  621. srcMap := make(map[string]struct{})
  622. dstMap := make(map[string]struct{})
  623. defer func() {
  624. srcMap = nil
  625. dstMap = nil
  626. }()
  627. for _, policy := range policies {
  628. if !policy.Enabled {
  629. continue
  630. }
  631. srcMap = convAclTagToValueMap(policy.Src)
  632. dstMap = convAclTagToValueMap(policy.Dst)
  633. for tagID := range node.Tags {
  634. allowed := false
  635. if _, ok := dstMap[tagID.String()]; policy.AllowedDirection == models.TrafficDirectionBi && ok {
  636. if _, ok := srcMap["*"]; ok {
  637. allowed = true
  638. allowedPolicies = append(allowedPolicies, policy)
  639. break
  640. }
  641. for tagID := range peer.Tags {
  642. if _, ok := srcMap[tagID.String()]; ok {
  643. allowed = true
  644. break
  645. }
  646. }
  647. }
  648. if allowed {
  649. allowedPolicies = append(allowedPolicies, policy)
  650. break
  651. }
  652. if _, ok := srcMap[tagID.String()]; ok {
  653. if _, ok := dstMap["*"]; ok {
  654. allowed = true
  655. allowedPolicies = append(allowedPolicies, policy)
  656. break
  657. }
  658. for tagID := range peer.Tags {
  659. if _, ok := dstMap[tagID.String()]; ok {
  660. allowed = true
  661. break
  662. }
  663. }
  664. }
  665. if allowed {
  666. allowedPolicies = append(allowedPolicies, policy)
  667. break
  668. }
  669. }
  670. for tagID := range peer.Tags {
  671. allowed := false
  672. if _, ok := dstMap[tagID.String()]; ok {
  673. if _, ok := srcMap["*"]; ok {
  674. allowed = true
  675. allowedPolicies = append(allowedPolicies, policy)
  676. break
  677. }
  678. for tagID := range node.Tags {
  679. if _, ok := srcMap[tagID.String()]; ok {
  680. allowed = true
  681. break
  682. }
  683. }
  684. }
  685. if allowed {
  686. allowedPolicies = append(allowedPolicies, policy)
  687. break
  688. }
  689. if _, ok := srcMap[tagID.String()]; policy.AllowedDirection == models.TrafficDirectionBi && ok {
  690. if _, ok := dstMap["*"]; ok {
  691. allowed = true
  692. allowedPolicies = append(allowedPolicies, policy)
  693. break
  694. }
  695. for tagID := range node.Tags {
  696. if _, ok := dstMap[tagID.String()]; ok {
  697. allowed = true
  698. break
  699. }
  700. }
  701. }
  702. if allowed {
  703. allowedPolicies = append(allowedPolicies, policy)
  704. break
  705. }
  706. }
  707. }
  708. if len(allowedPolicies) > 0 {
  709. return true, allowedPolicies
  710. }
  711. return false, allowedPolicies
  712. }
  713. // SortTagEntrys - Sorts slice of Tag entries by their id
  714. func SortAclEntrys(acls []models.Acl) {
  715. sort.Slice(acls, func(i, j int) bool {
  716. return acls[i].Name < acls[j].Name
  717. })
  718. }
  719. // UpdateDeviceTag - updates device tag on acl policies
  720. func UpdateDeviceTag(OldID, newID models.TagID, netID models.NetworkID) {
  721. acls := listDevicePolicies(netID)
  722. update := false
  723. for _, acl := range acls {
  724. for i, srcTagI := range acl.Src {
  725. if srcTagI.ID == models.DeviceAclID {
  726. if OldID.String() == srcTagI.Value {
  727. acl.Src[i].Value = newID.String()
  728. update = true
  729. }
  730. }
  731. }
  732. for i, dstTagI := range acl.Dst {
  733. if dstTagI.ID == models.DeviceAclID {
  734. if OldID.String() == dstTagI.Value {
  735. acl.Dst[i].Value = newID.String()
  736. update = true
  737. }
  738. }
  739. }
  740. if update {
  741. UpsertAcl(acl)
  742. }
  743. }
  744. }
  745. func CheckIfTagAsActivePolicy(tagID models.TagID, netID models.NetworkID) bool {
  746. acls := listDevicePolicies(netID)
  747. for _, acl := range acls {
  748. for _, srcTagI := range acl.Src {
  749. if srcTagI.ID == models.DeviceAclID {
  750. if tagID.String() == srcTagI.Value {
  751. return true
  752. }
  753. }
  754. }
  755. for _, dstTagI := range acl.Dst {
  756. if dstTagI.ID == models.DeviceAclID {
  757. if tagID.String() == dstTagI.Value {
  758. return true
  759. }
  760. }
  761. }
  762. }
  763. return false
  764. }
  765. // RemoveDeviceTagFromAclPolicies - remove device tag from acl policies
  766. func RemoveDeviceTagFromAclPolicies(tagID models.TagID, netID models.NetworkID) error {
  767. acls := listDevicePolicies(netID)
  768. update := false
  769. for _, acl := range acls {
  770. for i, srcTagI := range acl.Src {
  771. if srcTagI.ID == models.DeviceAclID {
  772. if tagID.String() == srcTagI.Value {
  773. acl.Src = append(acl.Src[:i], acl.Src[i+1:]...)
  774. update = true
  775. }
  776. }
  777. }
  778. for i, dstTagI := range acl.Dst {
  779. if dstTagI.ID == models.DeviceAclID {
  780. if tagID.String() == dstTagI.Value {
  781. acl.Dst = append(acl.Dst[:i], acl.Dst[i+1:]...)
  782. update = true
  783. }
  784. }
  785. }
  786. if update {
  787. UpsertAcl(acl)
  788. }
  789. }
  790. return nil
  791. }
  792. func getUserAclRulesForNode(targetnode *models.Node,
  793. rules map[string]models.AclRule) map[string]models.AclRule {
  794. userNodes := GetStaticUserNodesByNetwork(models.NetworkID(targetnode.Network))
  795. userGrpMap := GetUserGrpMap()
  796. allowedUsers := make(map[string][]models.Acl)
  797. acls := listUserPolicies(models.NetworkID(targetnode.Network))
  798. for nodeTag := range targetnode.Tags {
  799. for _, acl := range acls {
  800. if !acl.Enabled {
  801. continue
  802. }
  803. dstTags := convAclTagToValueMap(acl.Dst)
  804. if _, ok := dstTags[nodeTag.String()]; ok {
  805. // get all src tags
  806. for _, srcAcl := range acl.Src {
  807. if srcAcl.ID == models.UserAclID {
  808. allowedUsers[srcAcl.Value] = append(allowedUsers[srcAcl.Value], acl)
  809. } else if srcAcl.ID == models.UserGroupAclID {
  810. // fetch all users in the group
  811. if usersMap, ok := userGrpMap[models.UserGroupID(srcAcl.Value)]; ok {
  812. for userName := range usersMap {
  813. allowedUsers[userName] = append(allowedUsers[userName], acl)
  814. }
  815. }
  816. }
  817. }
  818. }
  819. }
  820. }
  821. for _, userNode := range userNodes {
  822. if !userNode.StaticNode.Enabled {
  823. continue
  824. }
  825. acls, ok := allowedUsers[userNode.StaticNode.OwnerID]
  826. if !ok {
  827. continue
  828. }
  829. for _, acl := range acls {
  830. if !acl.Enabled {
  831. continue
  832. }
  833. r := models.AclRule{
  834. ID: acl.ID,
  835. AllowedProtocol: acl.Proto,
  836. AllowedPorts: acl.Port,
  837. Direction: acl.AllowedDirection,
  838. Allowed: true,
  839. }
  840. // Get peers in the tags and add allowed rules
  841. if userNode.StaticNode.Address != "" {
  842. r.IPList = append(r.IPList, userNode.StaticNode.AddressIPNet4())
  843. }
  844. if userNode.StaticNode.Address6 != "" {
  845. r.IP6List = append(r.IP6List, userNode.StaticNode.AddressIPNet6())
  846. }
  847. if aclRule, ok := rules[acl.ID]; ok {
  848. aclRule.IPList = append(aclRule.IPList, r.IPList...)
  849. aclRule.IP6List = append(aclRule.IP6List, r.IP6List...)
  850. rules[acl.ID] = aclRule
  851. } else {
  852. rules[acl.ID] = r
  853. }
  854. }
  855. }
  856. return rules
  857. }
  858. func GetAclRulesForNode(targetnode *models.Node) (rules map[string]models.AclRule) {
  859. defer func() {
  860. if !targetnode.IsIngressGateway {
  861. rules = getUserAclRulesForNode(targetnode, rules)
  862. }
  863. }()
  864. rules = make(map[string]models.AclRule)
  865. var taggedNodes map[models.TagID][]models.Node
  866. if targetnode.IsIngressGateway {
  867. taggedNodes = GetTagMapWithNodesByNetwork(models.NetworkID(targetnode.Network), false)
  868. } else {
  869. taggedNodes = GetTagMapWithNodesByNetwork(models.NetworkID(targetnode.Network), true)
  870. }
  871. acls := listDevicePolicies(models.NetworkID(targetnode.Network))
  872. targetnode.Tags["*"] = struct{}{}
  873. for nodeTag := range targetnode.Tags {
  874. for _, acl := range acls {
  875. if !acl.Enabled {
  876. continue
  877. }
  878. srcTags := convAclTagToValueMap(acl.Src)
  879. dstTags := convAclTagToValueMap(acl.Dst)
  880. aclRule := models.AclRule{
  881. ID: acl.ID,
  882. AllowedProtocol: acl.Proto,
  883. AllowedPorts: acl.Port,
  884. Direction: acl.AllowedDirection,
  885. Allowed: true,
  886. }
  887. if acl.AllowedDirection == models.TrafficDirectionBi {
  888. var existsInSrcTag bool
  889. var existsInDstTag bool
  890. if _, ok := srcTags[nodeTag.String()]; ok {
  891. existsInSrcTag = true
  892. }
  893. if _, ok := dstTags[nodeTag.String()]; ok {
  894. existsInDstTag = true
  895. }
  896. if existsInSrcTag && !existsInDstTag {
  897. // get all dst tags
  898. for dst := range dstTags {
  899. if dst == nodeTag.String() {
  900. continue
  901. }
  902. // Get peers in the tags and add allowed rules
  903. nodes := taggedNodes[models.TagID(dst)]
  904. for _, node := range nodes {
  905. if node.ID == targetnode.ID {
  906. continue
  907. }
  908. if node.Address.IP != nil {
  909. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  910. }
  911. if node.Address6.IP != nil {
  912. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  913. }
  914. if node.IsStatic && node.StaticNode.Address != "" {
  915. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  916. }
  917. if node.IsStatic && node.StaticNode.Address6 != "" {
  918. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  919. }
  920. }
  921. }
  922. }
  923. if existsInDstTag && !existsInSrcTag {
  924. // get all src tags
  925. for src := range srcTags {
  926. if src == nodeTag.String() {
  927. continue
  928. }
  929. // Get peers in the tags and add allowed rules
  930. nodes := taggedNodes[models.TagID(src)]
  931. for _, node := range nodes {
  932. if node.ID == targetnode.ID {
  933. continue
  934. }
  935. if node.Address.IP != nil {
  936. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  937. }
  938. if node.Address6.IP != nil {
  939. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  940. }
  941. if node.IsStatic && node.StaticNode.Address != "" {
  942. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  943. }
  944. if node.IsStatic && node.StaticNode.Address6 != "" {
  945. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  946. }
  947. }
  948. }
  949. }
  950. if existsInDstTag && existsInSrcTag {
  951. nodes := taggedNodes[nodeTag]
  952. for _, node := range nodes {
  953. if node.ID == targetnode.ID {
  954. continue
  955. }
  956. if node.Address.IP != nil {
  957. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  958. }
  959. if node.Address6.IP != nil {
  960. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  961. }
  962. if node.IsStatic && node.StaticNode.Address != "" {
  963. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  964. }
  965. if node.IsStatic && node.StaticNode.Address6 != "" {
  966. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  967. }
  968. }
  969. }
  970. } else {
  971. _, all := dstTags["*"]
  972. if _, ok := dstTags[nodeTag.String()]; ok || all {
  973. // get all src tags
  974. for src := range srcTags {
  975. if src == nodeTag.String() {
  976. continue
  977. }
  978. // Get peers in the tags and add allowed rules
  979. nodes := taggedNodes[models.TagID(src)]
  980. for _, node := range nodes {
  981. if node.ID == targetnode.ID {
  982. continue
  983. }
  984. if node.Address.IP != nil {
  985. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  986. }
  987. if node.Address6.IP != nil {
  988. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  989. }
  990. if node.IsStatic && node.StaticNode.Address != "" {
  991. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  992. }
  993. if node.IsStatic && node.StaticNode.Address6 != "" {
  994. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  995. }
  996. }
  997. }
  998. }
  999. }
  1000. if len(aclRule.IPList) > 0 || len(aclRule.IP6List) > 0 {
  1001. rules[acl.ID] = aclRule
  1002. }
  1003. }
  1004. }
  1005. return rules
  1006. }