acls.go 27 KB

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