acls.go 39 KB

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