acls.go 50 KB

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