2
0

acls.go 47 KB

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