acls.go 39 KB

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