acls.go 47 KB

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