acls.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614
  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. for _, src := range req.Src {
  1283. if src.ID == models.UserGroupAclID {
  1284. userGroup, err := GetUserGroup(models.UserGroupID(src.Value))
  1285. if err != nil {
  1286. return err
  1287. }
  1288. _, ok := userGroup.NetworkRoles[req.NetworkID]
  1289. if !ok {
  1290. return fmt.Errorf("user group %s does not have access to network %s", src.Value, req.NetworkID)
  1291. }
  1292. }
  1293. }
  1294. return nil
  1295. }
  1296. func listAclFromCache() (acls []models.Acl) {
  1297. aclCacheMutex.RLock()
  1298. defer aclCacheMutex.RUnlock()
  1299. for _, acl := range aclCacheMap {
  1300. acls = append(acls, acl)
  1301. }
  1302. return
  1303. }
  1304. func storeAclInCache(a models.Acl) {
  1305. aclCacheMutex.Lock()
  1306. defer aclCacheMutex.Unlock()
  1307. aclCacheMap[a.ID] = a
  1308. }
  1309. func removeAclFromCache(a models.Acl) {
  1310. aclCacheMutex.Lock()
  1311. defer aclCacheMutex.Unlock()
  1312. delete(aclCacheMap, a.ID)
  1313. }
  1314. func getAclFromCache(aID string) (a models.Acl, ok bool) {
  1315. aclCacheMutex.RLock()
  1316. defer aclCacheMutex.RUnlock()
  1317. a, ok = aclCacheMap[aID]
  1318. return
  1319. }
  1320. // InsertAcl - creates acl policy
  1321. func InsertAcl(a models.Acl) error {
  1322. d, err := json.Marshal(a)
  1323. if err != nil {
  1324. return err
  1325. }
  1326. err = database.Insert(a.ID, string(d), database.ACLS_TABLE_NAME)
  1327. if err == nil && servercfg.CacheEnabled() {
  1328. storeAclInCache(a)
  1329. }
  1330. return err
  1331. }
  1332. // GetAcl - gets acl info by id
  1333. func GetAcl(aID string) (models.Acl, error) {
  1334. a := models.Acl{}
  1335. if servercfg.CacheEnabled() {
  1336. var ok bool
  1337. a, ok = getAclFromCache(aID)
  1338. if ok {
  1339. return a, nil
  1340. }
  1341. }
  1342. d, err := database.FetchRecord(database.ACLS_TABLE_NAME, aID)
  1343. if err != nil {
  1344. return a, err
  1345. }
  1346. err = json.Unmarshal([]byte(d), &a)
  1347. if err != nil {
  1348. return a, err
  1349. }
  1350. if servercfg.CacheEnabled() {
  1351. storeAclInCache(a)
  1352. }
  1353. return a, nil
  1354. }
  1355. // IsAclExists - checks if acl exists
  1356. func IsAclExists(aclID string) bool {
  1357. _, err := GetAcl(aclID)
  1358. return err == nil
  1359. }
  1360. func RemoveNodeFromAclPolicy(node models.Node) {
  1361. var nodeID string
  1362. if node.IsStatic {
  1363. nodeID = node.StaticNode.ClientID
  1364. } else {
  1365. nodeID = node.ID.String()
  1366. }
  1367. acls, _ := ListAclsByNetwork(models.NetworkID(node.Network))
  1368. for _, acl := range acls {
  1369. delete := false
  1370. update := false
  1371. if acl.RuleType == models.DevicePolicy {
  1372. for i := len(acl.Src) - 1; i >= 0; i-- {
  1373. if acl.Src[i].ID == models.NodeID && acl.Src[i].Value == nodeID {
  1374. if len(acl.Src) == 1 {
  1375. // delete policy
  1376. delete = true
  1377. break
  1378. } else {
  1379. acl.Src = append(acl.Src[:i], acl.Src[i+1:]...)
  1380. update = true
  1381. }
  1382. }
  1383. }
  1384. if delete {
  1385. DeleteAcl(acl)
  1386. continue
  1387. }
  1388. for i := len(acl.Dst) - 1; i >= 0; i-- {
  1389. if acl.Dst[i].ID == models.NodeID && acl.Dst[i].Value == nodeID {
  1390. if len(acl.Dst) == 1 {
  1391. // delete policy
  1392. delete = true
  1393. break
  1394. } else {
  1395. acl.Dst = append(acl.Dst[:i], acl.Dst[i+1:]...)
  1396. update = true
  1397. }
  1398. }
  1399. }
  1400. if delete {
  1401. DeleteAcl(acl)
  1402. continue
  1403. }
  1404. if update {
  1405. UpsertAcl(acl)
  1406. }
  1407. }
  1408. if acl.RuleType == models.UserPolicy {
  1409. for i := len(acl.Dst) - 1; i >= 0; i-- {
  1410. if acl.Dst[i].ID == models.NodeID && acl.Dst[i].Value == nodeID {
  1411. if len(acl.Dst) == 1 {
  1412. // delete policy
  1413. delete = true
  1414. break
  1415. } else {
  1416. acl.Dst = append(acl.Dst[:i], acl.Dst[i+1:]...)
  1417. update = true
  1418. }
  1419. }
  1420. }
  1421. if delete {
  1422. DeleteAcl(acl)
  1423. continue
  1424. }
  1425. if update {
  1426. UpsertAcl(acl)
  1427. }
  1428. }
  1429. }
  1430. }
  1431. // CreateDefaultAclNetworkPolicies - create default acl network policies
  1432. func CreateDefaultAclNetworkPolicies(netID models.NetworkID) {
  1433. if netID.String() == "" {
  1434. return
  1435. }
  1436. _, _ = ListAclsByNetwork(netID)
  1437. if !IsAclExists(fmt.Sprintf("%s.%s", netID, "all-nodes")) {
  1438. defaultDeviceAcl := models.Acl{
  1439. ID: fmt.Sprintf("%s.%s", netID, "all-nodes"),
  1440. Name: "All Nodes",
  1441. MetaData: "This Policy allows all nodes in the network to communicate with each other",
  1442. Default: true,
  1443. NetworkID: netID,
  1444. Proto: models.ALL,
  1445. ServiceType: models.Any,
  1446. Port: []string{},
  1447. RuleType: models.DevicePolicy,
  1448. Src: []models.AclPolicyTag{
  1449. {
  1450. ID: models.NodeTagID,
  1451. Value: "*",
  1452. }},
  1453. Dst: []models.AclPolicyTag{
  1454. {
  1455. ID: models.NodeTagID,
  1456. Value: "*",
  1457. }},
  1458. AllowedDirection: models.TrafficDirectionBi,
  1459. Enabled: true,
  1460. CreatedBy: "auto",
  1461. CreatedAt: time.Now().UTC(),
  1462. }
  1463. InsertAcl(defaultDeviceAcl)
  1464. }
  1465. if !IsAclExists(fmt.Sprintf("%s.%s", netID, "all-gateways")) {
  1466. defaultUserAcl := models.Acl{
  1467. ID: fmt.Sprintf("%s.%s", netID, "all-gateways"),
  1468. Default: true,
  1469. Name: "All Gateways",
  1470. NetworkID: netID,
  1471. Proto: models.ALL,
  1472. ServiceType: models.Any,
  1473. Port: []string{},
  1474. RuleType: models.DevicePolicy,
  1475. Src: []models.AclPolicyTag{
  1476. {
  1477. ID: models.NodeTagID,
  1478. Value: fmt.Sprintf("%s.%s", netID, models.GwTagName),
  1479. },
  1480. },
  1481. Dst: []models.AclPolicyTag{
  1482. {
  1483. ID: models.NodeTagID,
  1484. Value: "*",
  1485. },
  1486. },
  1487. AllowedDirection: models.TrafficDirectionBi,
  1488. Enabled: true,
  1489. CreatedBy: "auto",
  1490. CreatedAt: time.Now().UTC(),
  1491. }
  1492. InsertAcl(defaultUserAcl)
  1493. }
  1494. CreateDefaultUserPolicies(netID)
  1495. }