acls.go 40 KB

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