acls.go 33 KB

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