acls.go 50 KB

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