acls.go 32 KB

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