acls.go 27 KB

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