acls.go 38 KB

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