acls.go 36 KB

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