acls.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  1. package logic
  2. import (
  3. "context"
  4. "errors"
  5. "maps"
  6. "net"
  7. "github.com/gravitl/netmaker/db"
  8. "github.com/gravitl/netmaker/logic"
  9. "github.com/gravitl/netmaker/models"
  10. "github.com/gravitl/netmaker/schema"
  11. )
  12. func getStaticUserNodesByNetwork(network models.NetworkID) (staticNode []models.Node) {
  13. extClients, err := logic.GetAllExtClients()
  14. if err != nil {
  15. return
  16. }
  17. for _, extI := range extClients {
  18. if extI.Network == network.String() {
  19. if extI.RemoteAccessClientID != "" {
  20. n := extI.ConvertToStaticNode()
  21. staticNode = append(staticNode, n)
  22. }
  23. }
  24. }
  25. return
  26. }
  27. func GetFwRulesForUserNodesOnGw(node models.Node, nodes []models.Node) (rules []models.FwRule) {
  28. defaultUserPolicy, _ := logic.GetDefaultPolicy(models.NetworkID(node.Network), models.UserPolicy)
  29. userNodes := getStaticUserNodesByNetwork(models.NetworkID(node.Network))
  30. for _, userNodeI := range userNodes {
  31. if defaultUserPolicy.Enabled {
  32. if userNodeI.StaticNode.Address != "" {
  33. rules = append(rules, models.FwRule{
  34. SrcIP: userNodeI.StaticNode.AddressIPNet4(),
  35. DstIP: net.IPNet{},
  36. AllowedProtocol: models.ALL,
  37. AllowedPorts: []string{},
  38. Allow: true,
  39. })
  40. }
  41. if userNodeI.StaticNode.Address6 != "" {
  42. rules = append(rules, models.FwRule{
  43. SrcIP: userNodeI.StaticNode.AddressIPNet6(),
  44. DstIP: net.IPNet{},
  45. AllowedProtocol: models.ALL,
  46. AllowedPorts: []string{},
  47. Allow: true,
  48. })
  49. }
  50. continue
  51. }
  52. for _, peer := range nodes {
  53. if peer.IsUserNode {
  54. continue
  55. }
  56. if ok, allowedPolicies := IsUserAllowedToCommunicate(userNodeI.StaticNode.OwnerID, peer); ok {
  57. if peer.IsStatic {
  58. peer = peer.StaticNode.ConvertToStaticNode()
  59. }
  60. for _, policy := range allowedPolicies {
  61. if userNodeI.StaticNode.Address != "" {
  62. rules = append(rules, models.FwRule{
  63. SrcIP: userNodeI.StaticNode.AddressIPNet4(),
  64. DstIP: net.IPNet{
  65. IP: peer.Address.IP,
  66. Mask: net.CIDRMask(32, 32),
  67. },
  68. AllowedProtocol: policy.Proto,
  69. AllowedPorts: policy.Port,
  70. Allow: true,
  71. })
  72. }
  73. if userNodeI.StaticNode.Address6 != "" {
  74. rules = append(rules, models.FwRule{
  75. SrcIP: userNodeI.StaticNode.AddressIPNet6(),
  76. DstIP: net.IPNet{
  77. IP: peer.Address6.IP,
  78. Mask: net.CIDRMask(128, 128),
  79. },
  80. AllowedProtocol: policy.Proto,
  81. AllowedPorts: policy.Port,
  82. Allow: true,
  83. })
  84. }
  85. // add egress ranges
  86. for _, dstI := range policy.Dst {
  87. if dstI.Value == "*" {
  88. rules = append(rules, models.FwRule{
  89. SrcIP: userNodeI.StaticNode.AddressIPNet4(),
  90. DstIP: net.IPNet{},
  91. AllowedProtocol: policy.Proto,
  92. AllowedPorts: policy.Port,
  93. Allow: true,
  94. })
  95. break
  96. }
  97. if dstI.ID == models.EgressID {
  98. e := schema.Egress{ID: dstI.Value}
  99. err := e.Get(db.WithContext(context.TODO()))
  100. if err != nil {
  101. continue
  102. }
  103. dstI.Value = e.Range
  104. ip, cidr, err := net.ParseCIDR(dstI.Value)
  105. if err == nil {
  106. if ip.To4() != nil && userNodeI.StaticNode.Address != "" {
  107. rules = append(rules, models.FwRule{
  108. SrcIP: userNodeI.StaticNode.AddressIPNet4(),
  109. DstIP: *cidr,
  110. AllowedProtocol: policy.Proto,
  111. AllowedPorts: policy.Port,
  112. Allow: true,
  113. })
  114. } else if ip.To16() != nil && userNodeI.StaticNode.Address6 != "" {
  115. rules = append(rules, models.FwRule{
  116. SrcIP: userNodeI.StaticNode.AddressIPNet6(),
  117. DstIP: *cidr,
  118. AllowedProtocol: policy.Proto,
  119. AllowedPorts: policy.Port,
  120. Allow: true,
  121. })
  122. }
  123. }
  124. }
  125. }
  126. }
  127. }
  128. }
  129. }
  130. return
  131. }
  132. func GetFwRulesForNodeAndPeerOnGw(node, peer models.Node, allowedPolicies []models.Acl) (rules []models.FwRule) {
  133. for _, policy := range allowedPolicies {
  134. // if static peer dst rule not for ingress node -> skip
  135. if node.Address.IP != nil {
  136. rules = append(rules, models.FwRule{
  137. SrcIP: net.IPNet{
  138. IP: node.Address.IP,
  139. Mask: net.CIDRMask(32, 32),
  140. },
  141. DstIP: net.IPNet{
  142. IP: peer.Address.IP,
  143. Mask: net.CIDRMask(32, 32),
  144. },
  145. AllowedProtocol: policy.Proto,
  146. AllowedPorts: policy.Port,
  147. Allow: true,
  148. })
  149. }
  150. if node.Address6.IP != nil {
  151. rules = append(rules, models.FwRule{
  152. SrcIP: net.IPNet{
  153. IP: node.Address6.IP,
  154. Mask: net.CIDRMask(128, 128),
  155. },
  156. DstIP: net.IPNet{
  157. IP: peer.Address6.IP,
  158. Mask: net.CIDRMask(128, 128),
  159. },
  160. AllowedProtocol: policy.Proto,
  161. AllowedPorts: policy.Port,
  162. Allow: true,
  163. })
  164. }
  165. if policy.AllowedDirection == models.TrafficDirectionBi {
  166. if node.Address.IP != nil {
  167. rules = append(rules, models.FwRule{
  168. SrcIP: net.IPNet{
  169. IP: peer.Address.IP,
  170. Mask: net.CIDRMask(32, 32),
  171. },
  172. DstIP: net.IPNet{
  173. IP: node.Address.IP,
  174. Mask: net.CIDRMask(32, 32),
  175. },
  176. AllowedProtocol: policy.Proto,
  177. AllowedPorts: policy.Port,
  178. Allow: true,
  179. })
  180. }
  181. if node.Address6.IP != nil {
  182. rules = append(rules, models.FwRule{
  183. SrcIP: net.IPNet{
  184. IP: peer.Address6.IP,
  185. Mask: net.CIDRMask(128, 128),
  186. },
  187. DstIP: net.IPNet{
  188. IP: node.Address6.IP,
  189. Mask: net.CIDRMask(128, 128),
  190. },
  191. AllowedProtocol: policy.Proto,
  192. AllowedPorts: policy.Port,
  193. Allow: true,
  194. })
  195. }
  196. }
  197. if len(node.StaticNode.ExtraAllowedIPs) > 0 {
  198. for _, additionalAllowedIPNet := range node.StaticNode.ExtraAllowedIPs {
  199. _, ipNet, err := net.ParseCIDR(additionalAllowedIPNet)
  200. if err != nil {
  201. continue
  202. }
  203. if ipNet.IP.To4() != nil && peer.Address.IP != nil {
  204. rules = append(rules, models.FwRule{
  205. SrcIP: net.IPNet{
  206. IP: peer.Address.IP,
  207. Mask: net.CIDRMask(32, 32),
  208. },
  209. DstIP: *ipNet,
  210. Allow: true,
  211. })
  212. } else if peer.Address6.IP != nil {
  213. rules = append(rules, models.FwRule{
  214. SrcIP: net.IPNet{
  215. IP: peer.Address6.IP,
  216. Mask: net.CIDRMask(128, 128),
  217. },
  218. DstIP: *ipNet,
  219. Allow: true,
  220. })
  221. }
  222. }
  223. }
  224. if len(peer.StaticNode.ExtraAllowedIPs) > 0 {
  225. for _, additionalAllowedIPNet := range peer.StaticNode.ExtraAllowedIPs {
  226. _, ipNet, err := net.ParseCIDR(additionalAllowedIPNet)
  227. if err != nil {
  228. continue
  229. }
  230. if ipNet.IP.To4() != nil && node.Address.IP != nil {
  231. rules = append(rules, models.FwRule{
  232. SrcIP: net.IPNet{
  233. IP: node.Address.IP,
  234. Mask: net.CIDRMask(32, 32),
  235. },
  236. DstIP: *ipNet,
  237. Allow: true,
  238. })
  239. } else if node.Address6.IP != nil {
  240. rules = append(rules, models.FwRule{
  241. SrcIP: net.IPNet{
  242. IP: node.Address6.IP,
  243. Mask: net.CIDRMask(128, 128),
  244. },
  245. DstIP: *ipNet,
  246. Allow: true,
  247. })
  248. }
  249. }
  250. }
  251. // add egress range rules
  252. for _, dstI := range policy.Dst {
  253. if dstI.ID == models.EgressID {
  254. e := schema.Egress{ID: dstI.Value}
  255. err := e.Get(db.WithContext(context.TODO()))
  256. if err != nil {
  257. continue
  258. }
  259. dstI.Value = e.Range
  260. ip, cidr, err := net.ParseCIDR(dstI.Value)
  261. if err == nil {
  262. if ip.To4() != nil {
  263. if node.Address.IP != nil {
  264. rules = append(rules, models.FwRule{
  265. SrcIP: net.IPNet{
  266. IP: node.Address.IP,
  267. Mask: net.CIDRMask(32, 32),
  268. },
  269. DstIP: *cidr,
  270. AllowedProtocol: policy.Proto,
  271. AllowedPorts: policy.Port,
  272. Allow: true,
  273. })
  274. }
  275. } else {
  276. if node.Address6.IP != nil {
  277. rules = append(rules, models.FwRule{
  278. SrcIP: net.IPNet{
  279. IP: node.Address6.IP,
  280. Mask: net.CIDRMask(128, 128),
  281. },
  282. DstIP: *cidr,
  283. AllowedProtocol: policy.Proto,
  284. AllowedPorts: policy.Port,
  285. Allow: true,
  286. })
  287. }
  288. }
  289. }
  290. }
  291. }
  292. }
  293. return
  294. }
  295. func checkIfAclTagisValid(a models.Acl, t models.AclPolicyTag, isSrc bool) (err error) {
  296. switch t.ID {
  297. case models.NodeTagID:
  298. if a.RuleType == models.UserPolicy && isSrc {
  299. return errors.New("user policy source mismatch")
  300. }
  301. // check if tag is valid
  302. _, err := GetTag(models.TagID(t.Value))
  303. if err != nil {
  304. return errors.New("invalid tag " + t.Value)
  305. }
  306. case models.NodeID:
  307. if a.RuleType == models.UserPolicy && isSrc {
  308. return errors.New("user policy source mismatch")
  309. }
  310. _, nodeErr := logic.GetNodeByID(t.Value)
  311. if nodeErr != nil {
  312. _, staticNodeErr := logic.GetExtClient(t.Value, a.NetworkID.String())
  313. if staticNodeErr != nil {
  314. return errors.New("invalid node " + t.Value)
  315. }
  316. }
  317. case models.EgressID, models.EgressRange:
  318. e := schema.Egress{
  319. ID: t.Value,
  320. }
  321. err := e.Get(db.WithContext(context.TODO()))
  322. if err != nil {
  323. return errors.New("invalid egress")
  324. }
  325. case models.UserAclID:
  326. if a.RuleType == models.DevicePolicy {
  327. return errors.New("device policy source mismatch")
  328. }
  329. if !isSrc {
  330. return errors.New("user cannot be added to destination")
  331. }
  332. _, err := logic.GetUser(t.Value)
  333. if err != nil {
  334. return errors.New("invalid user " + t.Value)
  335. }
  336. case models.UserGroupAclID:
  337. if a.RuleType == models.DevicePolicy {
  338. return errors.New("device policy source mismatch")
  339. }
  340. if !isSrc {
  341. return errors.New("user cannot be added to destination")
  342. }
  343. err := IsGroupValid(models.UserGroupID(t.Value))
  344. if err != nil {
  345. return errors.New("invalid user group " + t.Value)
  346. }
  347. // check if group belongs to this network
  348. netGrps := GetUserGroupsInNetwork(a.NetworkID)
  349. if _, ok := netGrps[models.UserGroupID(t.Value)]; !ok {
  350. return errors.New("invalid user group " + t.Value)
  351. }
  352. default:
  353. return errors.New("invalid policy")
  354. }
  355. return nil
  356. }
  357. // IsAclPolicyValid - validates if acl policy is valid
  358. func IsAclPolicyValid(acl models.Acl) (err error) {
  359. //check if src and dst are valid
  360. if acl.AllowedDirection != models.TrafficDirectionBi &&
  361. acl.AllowedDirection != models.TrafficDirectionUni {
  362. return errors.New("invalid traffic direction")
  363. }
  364. switch acl.RuleType {
  365. case models.UserPolicy:
  366. // src list should only contain users
  367. for _, srcI := range acl.Src {
  368. if srcI.Value == "*" {
  369. continue
  370. }
  371. // check if user group is valid
  372. if err = checkIfAclTagisValid(acl, srcI, true); err != nil {
  373. return
  374. }
  375. }
  376. for _, dstI := range acl.Dst {
  377. if dstI.Value == "*" {
  378. continue
  379. }
  380. // check if user group is valid
  381. if err = checkIfAclTagisValid(acl, dstI, false); err != nil {
  382. return
  383. }
  384. }
  385. case models.DevicePolicy:
  386. for _, srcI := range acl.Src {
  387. if srcI.Value == "*" {
  388. continue
  389. }
  390. // check if user group is valid
  391. if err = checkIfAclTagisValid(acl, srcI, true); err != nil {
  392. return err
  393. }
  394. }
  395. for _, dstI := range acl.Dst {
  396. if dstI.Value == "*" {
  397. continue
  398. }
  399. // check if user group is valid
  400. if err = checkIfAclTagisValid(acl, dstI, false); err != nil {
  401. return
  402. }
  403. }
  404. }
  405. return nil
  406. }
  407. // ListUserPolicies - lists all acl policies enforced on an user
  408. func ListUserPolicies(u models.User) []models.Acl {
  409. allAcls := logic.ListAcls()
  410. userAcls := []models.Acl{}
  411. for _, acl := range allAcls {
  412. if acl.RuleType == models.UserPolicy {
  413. srcMap := logic.ConvAclTagToValueMap(acl.Src)
  414. if _, ok := srcMap[u.UserName]; ok {
  415. userAcls = append(userAcls, acl)
  416. } else {
  417. // check for user groups
  418. for gID := range u.UserGroups {
  419. if _, ok := srcMap[gID.String()]; ok {
  420. userAcls = append(userAcls, acl)
  421. break
  422. }
  423. }
  424. }
  425. }
  426. }
  427. return userAcls
  428. }
  429. // listPoliciesOfUser - lists all user acl policies applied to user in an network
  430. func listPoliciesOfUser(user models.User, netID models.NetworkID) []models.Acl {
  431. allAcls := logic.ListAcls()
  432. userAcls := []models.Acl{}
  433. if _, ok := user.UserGroups[globalNetworksAdminGroupID]; ok {
  434. user.UserGroups[GetDefaultNetworkAdminGroupID(netID)] = struct{}{}
  435. }
  436. if _, ok := user.UserGroups[globalNetworksUserGroupID]; ok {
  437. user.UserGroups[GetDefaultNetworkUserGroupID(netID)] = struct{}{}
  438. }
  439. if user.PlatformRoleID == models.AdminRole || user.PlatformRoleID == models.SuperAdminRole {
  440. user.UserGroups[GetDefaultNetworkAdminGroupID(netID)] = struct{}{}
  441. }
  442. for _, acl := range allAcls {
  443. if acl.NetworkID == netID && acl.RuleType == models.UserPolicy {
  444. srcMap := logic.ConvAclTagToValueMap(acl.Src)
  445. if _, ok := srcMap[user.UserName]; ok {
  446. userAcls = append(userAcls, acl)
  447. continue
  448. }
  449. for netRole := range user.NetworkRoles {
  450. if _, ok := srcMap[netRole.String()]; ok {
  451. userAcls = append(userAcls, acl)
  452. continue
  453. }
  454. }
  455. for userG := range user.UserGroups {
  456. if _, ok := srcMap[userG.String()]; ok {
  457. userAcls = append(userAcls, acl)
  458. continue
  459. }
  460. }
  461. }
  462. }
  463. return userAcls
  464. }
  465. // listUserPolicies - lists all user policies in a network
  466. func listUserPolicies(netID models.NetworkID) []models.Acl {
  467. allAcls := logic.ListAcls()
  468. deviceAcls := []models.Acl{}
  469. for _, acl := range allAcls {
  470. if acl.NetworkID == netID && acl.RuleType == models.UserPolicy {
  471. deviceAcls = append(deviceAcls, acl)
  472. }
  473. }
  474. return deviceAcls
  475. }
  476. // IsUserAllowedToCommunicate - check if user is allowed to communicate with peer
  477. func IsUserAllowedToCommunicate(userName string, peer models.Node) (bool, []models.Acl) {
  478. var peerId string
  479. if peer.IsStatic {
  480. peerId = peer.StaticNode.ClientID
  481. peer = peer.StaticNode.ConvertToStaticNode()
  482. } else {
  483. peerId = peer.ID.String()
  484. }
  485. var peerTags map[models.TagID]struct{}
  486. if peer.Mutex != nil {
  487. peer.Mutex.Lock()
  488. peerTags = maps.Clone(peer.Tags)
  489. peer.Mutex.Unlock()
  490. } else {
  491. peerTags = peer.Tags
  492. }
  493. if peerTags == nil {
  494. peerTags = make(map[models.TagID]struct{})
  495. }
  496. peerTags[models.TagID(peerId)] = struct{}{}
  497. peerTags[models.TagID("*")] = struct{}{}
  498. acl, _ := logic.GetDefaultPolicy(models.NetworkID(peer.Network), models.UserPolicy)
  499. if acl.Enabled {
  500. return true, []models.Acl{acl}
  501. }
  502. user, err := logic.GetUser(userName)
  503. if err != nil {
  504. return false, []models.Acl{}
  505. }
  506. allowedPolicies := []models.Acl{}
  507. policies := listPoliciesOfUser(*user, models.NetworkID(peer.Network))
  508. for _, policy := range policies {
  509. if !policy.Enabled {
  510. continue
  511. }
  512. dstMap := logic.ConvAclTagToValueMap(policy.Dst)
  513. for _, dst := range policy.Dst {
  514. if dst.ID == models.EgressID {
  515. e := schema.Egress{ID: dst.Value}
  516. err := e.Get(db.WithContext(context.TODO()))
  517. if err == nil && e.Status {
  518. for nodeID := range e.Nodes {
  519. dstMap[nodeID] = struct{}{}
  520. }
  521. }
  522. }
  523. }
  524. if _, ok := dstMap["*"]; ok {
  525. allowedPolicies = append(allowedPolicies, policy)
  526. continue
  527. }
  528. if _, ok := dstMap[peer.ID.String()]; ok {
  529. allowedPolicies = append(allowedPolicies, policy)
  530. continue
  531. }
  532. for tagID := range peerTags {
  533. if _, ok := dstMap[tagID.String()]; ok {
  534. allowedPolicies = append(allowedPolicies, policy)
  535. break
  536. }
  537. }
  538. }
  539. if len(allowedPolicies) > 0 {
  540. return true, allowedPolicies
  541. }
  542. return false, []models.Acl{}
  543. }
  544. // IsPeerAllowed - checks if peer needs to be added to the interface
  545. func IsPeerAllowed(node, peer models.Node, checkDefaultPolicy bool) bool {
  546. var nodeId, peerId string
  547. // if peer.IsFailOver && node.FailedOverBy != uuid.Nil && node.FailedOverBy == peer.ID {
  548. // return true
  549. // }
  550. // if node.IsFailOver && peer.FailedOverBy != uuid.Nil && peer.FailedOverBy == node.ID {
  551. // return true
  552. // }
  553. // if node.IsGw && peer.IsRelayed && peer.RelayedBy == node.ID.String() {
  554. // return true
  555. // }
  556. // if peer.IsGw && node.IsRelayed && node.RelayedBy == peer.ID.String() {
  557. // return true
  558. // }
  559. if node.IsStatic {
  560. nodeId = node.StaticNode.ClientID
  561. node = node.StaticNode.ConvertToStaticNode()
  562. } else {
  563. nodeId = node.ID.String()
  564. }
  565. if peer.IsStatic {
  566. peerId = peer.StaticNode.ClientID
  567. peer = peer.StaticNode.ConvertToStaticNode()
  568. } else {
  569. peerId = peer.ID.String()
  570. }
  571. var nodeTags, peerTags map[models.TagID]struct{}
  572. if node.Mutex != nil {
  573. node.Mutex.Lock()
  574. nodeTags = maps.Clone(node.Tags)
  575. node.Mutex.Unlock()
  576. } else {
  577. nodeTags = node.Tags
  578. }
  579. if peer.Mutex != nil {
  580. peer.Mutex.Lock()
  581. peerTags = maps.Clone(peer.Tags)
  582. peer.Mutex.Unlock()
  583. } else {
  584. peerTags = peer.Tags
  585. }
  586. if nodeTags == nil {
  587. nodeTags = make(map[models.TagID]struct{})
  588. }
  589. if peerTags == nil {
  590. peerTags = make(map[models.TagID]struct{})
  591. }
  592. nodeTags[models.TagID(nodeId)] = struct{}{}
  593. peerTags[models.TagID(peerId)] = struct{}{}
  594. if checkDefaultPolicy {
  595. // check default policy if all allowed return true
  596. defaultPolicy, err := logic.GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  597. if err == nil {
  598. if defaultPolicy.Enabled {
  599. return true
  600. }
  601. }
  602. }
  603. // list device policies
  604. policies := logic.ListDevicePolicies(models.NetworkID(peer.Network))
  605. srcMap := make(map[string]struct{})
  606. dstMap := make(map[string]struct{})
  607. defer func() {
  608. srcMap = nil
  609. dstMap = nil
  610. }()
  611. for _, policy := range policies {
  612. if !policy.Enabled {
  613. continue
  614. }
  615. srcMap = logic.ConvAclTagToValueMap(policy.Src)
  616. dstMap = logic.ConvAclTagToValueMap(policy.Dst)
  617. for _, dst := range policy.Dst {
  618. if dst.ID == models.EgressID {
  619. e := schema.Egress{ID: dst.Value}
  620. err := e.Get(db.WithContext(context.TODO()))
  621. if err == nil && e.Status {
  622. for nodeID := range e.Nodes {
  623. dstMap[nodeID] = struct{}{}
  624. }
  625. }
  626. }
  627. }
  628. if logic.CheckTagGroupPolicy(srcMap, dstMap, node, peer, nodeTags, peerTags) {
  629. return true
  630. }
  631. }
  632. return false
  633. }
  634. func RemoveUserFromAclPolicy(userName string) {
  635. acls := logic.ListAcls()
  636. for _, acl := range acls {
  637. delete := false
  638. update := false
  639. if acl.RuleType == models.UserPolicy {
  640. for i := len(acl.Src) - 1; i >= 0; i-- {
  641. if acl.Src[i].ID == models.UserAclID && acl.Src[i].Value == userName {
  642. if len(acl.Src) == 1 {
  643. // delete policy
  644. delete = true
  645. break
  646. } else {
  647. acl.Src = append(acl.Src[:i], acl.Src[i+1:]...)
  648. update = true
  649. }
  650. }
  651. }
  652. if delete {
  653. logic.DeleteAcl(acl)
  654. continue
  655. }
  656. if update {
  657. logic.UpsertAcl(acl)
  658. }
  659. }
  660. }
  661. }
  662. // UpdateDeviceTag - updates device tag on acl policies
  663. func UpdateDeviceTag(OldID, newID models.TagID, netID models.NetworkID) {
  664. acls := logic.ListDevicePolicies(netID)
  665. update := false
  666. for _, acl := range acls {
  667. for i, srcTagI := range acl.Src {
  668. if srcTagI.ID == models.NodeTagID {
  669. if OldID.String() == srcTagI.Value {
  670. acl.Src[i].Value = newID.String()
  671. update = true
  672. }
  673. }
  674. }
  675. for i, dstTagI := range acl.Dst {
  676. if dstTagI.ID == models.NodeTagID {
  677. if OldID.String() == dstTagI.Value {
  678. acl.Dst[i].Value = newID.String()
  679. update = true
  680. }
  681. }
  682. }
  683. if update {
  684. logic.UpsertAcl(acl)
  685. }
  686. }
  687. }
  688. func CheckIfTagAsActivePolicy(tagID models.TagID, netID models.NetworkID) bool {
  689. acls := logic.ListDevicePolicies(netID)
  690. for _, acl := range acls {
  691. for _, srcTagI := range acl.Src {
  692. if srcTagI.ID == models.NodeTagID {
  693. if tagID.String() == srcTagI.Value {
  694. return true
  695. }
  696. }
  697. }
  698. for _, dstTagI := range acl.Dst {
  699. if dstTagI.ID == models.NodeTagID {
  700. if tagID.String() == dstTagI.Value {
  701. return true
  702. }
  703. }
  704. }
  705. }
  706. return false
  707. }
  708. // RemoveDeviceTagFromAclPolicies - remove device tag from acl policies
  709. func RemoveDeviceTagFromAclPolicies(tagID models.TagID, netID models.NetworkID) error {
  710. acls := logic.ListDevicePolicies(netID)
  711. update := false
  712. for _, acl := range acls {
  713. for i := len(acl.Src) - 1; i >= 0; i-- {
  714. if acl.Src[i].ID == models.NodeTagID {
  715. if tagID.String() == acl.Src[i].Value {
  716. acl.Src = append(acl.Src[:i], acl.Src[i+1:]...)
  717. update = true
  718. }
  719. }
  720. }
  721. for i := len(acl.Dst) - 1; i >= 0; i-- {
  722. if acl.Dst[i].ID == models.NodeTagID {
  723. if tagID.String() == acl.Dst[i].Value {
  724. acl.Dst = append(acl.Dst[:i], acl.Dst[i+1:]...)
  725. update = true
  726. }
  727. }
  728. }
  729. if update {
  730. logic.UpsertAcl(acl)
  731. }
  732. }
  733. return nil
  734. }
  735. func GetEgressUserRulesForNode(targetnode *models.Node,
  736. rules map[string]models.AclRule) map[string]models.AclRule {
  737. userNodes := getStaticUserNodesByNetwork(models.NetworkID(targetnode.Network))
  738. userGrpMap := GetUserGrpMap()
  739. allowedUsers := make(map[string][]models.Acl)
  740. acls := listUserPolicies(models.NetworkID(targetnode.Network))
  741. var targetNodeTags = make(map[models.TagID]struct{})
  742. targetNodeTags["*"] = struct{}{}
  743. egs, _ := (&schema.Egress{Network: targetnode.Network}).ListByNetwork(db.WithContext(context.TODO()))
  744. if len(egs) == 0 {
  745. return rules
  746. }
  747. defaultPolicy, _ := logic.GetDefaultPolicy(models.NetworkID(targetnode.Network), models.UserPolicy)
  748. for _, egI := range egs {
  749. if !egI.Status {
  750. continue
  751. }
  752. if _, ok := egI.Nodes[targetnode.ID.String()]; ok {
  753. targetNodeTags[models.TagID(egI.Range)] = struct{}{}
  754. targetNodeTags[models.TagID(egI.ID)] = struct{}{}
  755. }
  756. }
  757. if !defaultPolicy.Enabled {
  758. for _, acl := range acls {
  759. if !acl.Enabled {
  760. continue
  761. }
  762. dstTags := logic.ConvAclTagToValueMap(acl.Dst)
  763. for _, dst := range acl.Dst {
  764. if dst.ID == models.EgressID {
  765. e := schema.Egress{ID: dst.Value}
  766. err := e.Get(db.WithContext(context.TODO()))
  767. if err == nil && e.Status {
  768. for nodeID := range e.Nodes {
  769. dstTags[nodeID] = struct{}{}
  770. }
  771. dstTags[e.Range] = struct{}{}
  772. }
  773. }
  774. }
  775. _, all := dstTags["*"]
  776. addUsers := false
  777. if !all {
  778. for nodeTag := range targetNodeTags {
  779. if _, ok := dstTags[nodeTag.String()]; ok {
  780. addUsers = true
  781. break
  782. }
  783. }
  784. } else {
  785. addUsers = true
  786. }
  787. if addUsers {
  788. // get all src tags
  789. for _, srcAcl := range acl.Src {
  790. if srcAcl.ID == models.UserAclID {
  791. allowedUsers[srcAcl.Value] = append(allowedUsers[srcAcl.Value], acl)
  792. } else if srcAcl.ID == models.UserGroupAclID {
  793. // fetch all users in the group
  794. if usersMap, ok := userGrpMap[models.UserGroupID(srcAcl.Value)]; ok {
  795. for userName := range usersMap {
  796. allowedUsers[userName] = append(allowedUsers[userName], acl)
  797. }
  798. }
  799. }
  800. }
  801. }
  802. }
  803. }
  804. if defaultPolicy.Enabled {
  805. r := models.AclRule{
  806. ID: defaultPolicy.ID,
  807. AllowedProtocol: defaultPolicy.Proto,
  808. AllowedPorts: defaultPolicy.Port,
  809. Direction: defaultPolicy.AllowedDirection,
  810. Allowed: true,
  811. }
  812. for _, userNode := range userNodes {
  813. if !userNode.StaticNode.Enabled {
  814. continue
  815. }
  816. // Get peers in the tags and add allowed rules
  817. if userNode.StaticNode.Address != "" {
  818. r.IPList = append(r.IPList, userNode.StaticNode.AddressIPNet4())
  819. }
  820. if userNode.StaticNode.Address6 != "" {
  821. r.IP6List = append(r.IP6List, userNode.StaticNode.AddressIPNet6())
  822. }
  823. }
  824. rules[defaultPolicy.ID] = r
  825. } else {
  826. for _, userNode := range userNodes {
  827. if !userNode.StaticNode.Enabled {
  828. continue
  829. }
  830. acls, ok := allowedUsers[userNode.StaticNode.OwnerID]
  831. if !ok {
  832. continue
  833. }
  834. for _, acl := range acls {
  835. if !acl.Enabled {
  836. continue
  837. }
  838. r := models.AclRule{
  839. ID: acl.ID,
  840. AllowedProtocol: acl.Proto,
  841. AllowedPorts: acl.Port,
  842. Direction: acl.AllowedDirection,
  843. Allowed: true,
  844. }
  845. // Get peers in the tags and add allowed rules
  846. if userNode.StaticNode.Address != "" {
  847. r.IPList = append(r.IPList, userNode.StaticNode.AddressIPNet4())
  848. }
  849. if userNode.StaticNode.Address6 != "" {
  850. r.IP6List = append(r.IP6List, userNode.StaticNode.AddressIPNet6())
  851. }
  852. for _, dstI := range acl.Dst {
  853. if dstI.ID == models.EgressID {
  854. e := schema.Egress{ID: dstI.Value}
  855. err := e.Get(db.WithContext(context.TODO()))
  856. if err != nil {
  857. continue
  858. }
  859. ip, cidr, err := net.ParseCIDR(e.Range)
  860. if err == nil {
  861. if ip.To4() != nil {
  862. r.Dst = append(r.Dst, *cidr)
  863. } else {
  864. r.Dst6 = append(r.Dst6, *cidr)
  865. }
  866. }
  867. }
  868. }
  869. if aclRule, ok := rules[acl.ID]; ok {
  870. aclRule.IPList = append(aclRule.IPList, r.IPList...)
  871. aclRule.IP6List = append(aclRule.IP6List, r.IP6List...)
  872. rules[acl.ID] = aclRule
  873. } else {
  874. rules[acl.ID] = r
  875. }
  876. }
  877. }
  878. }
  879. return rules
  880. }
  881. func GetUserAclRulesForNode(targetnode *models.Node,
  882. rules map[string]models.AclRule) map[string]models.AclRule {
  883. userNodes := getStaticUserNodesByNetwork(models.NetworkID(targetnode.Network))
  884. userGrpMap := GetUserGrpMap()
  885. allowedUsers := make(map[string][]models.Acl)
  886. acls := listUserPolicies(models.NetworkID(targetnode.Network))
  887. var targetNodeTags = make(map[models.TagID]struct{})
  888. if targetnode.Mutex != nil {
  889. targetnode.Mutex.Lock()
  890. targetNodeTags = maps.Clone(targetnode.Tags)
  891. targetnode.Mutex.Unlock()
  892. } else {
  893. targetNodeTags = maps.Clone(targetnode.Tags)
  894. }
  895. if targetNodeTags == nil {
  896. targetNodeTags = make(map[models.TagID]struct{})
  897. }
  898. defaultPolicy, _ := logic.GetDefaultPolicy(models.NetworkID(targetnode.Network), models.UserPolicy)
  899. targetNodeTags[models.TagID(targetnode.ID.String())] = struct{}{}
  900. if !defaultPolicy.Enabled {
  901. for _, acl := range acls {
  902. if !acl.Enabled {
  903. continue
  904. }
  905. dstTags := logic.ConvAclTagToValueMap(acl.Dst)
  906. _, all := dstTags["*"]
  907. addUsers := false
  908. if !all {
  909. for _, dst := range acl.Dst {
  910. if dst.ID == models.EgressID {
  911. e := schema.Egress{ID: dst.Value}
  912. err := e.Get(db.WithContext(context.TODO()))
  913. if err == nil && e.Status && len(e.Nodes) > 0 {
  914. if _, ok := e.Nodes[targetnode.ID.String()]; ok {
  915. dstTags[targetnode.ID.String()] = struct{}{}
  916. }
  917. }
  918. }
  919. }
  920. for nodeTag := range targetNodeTags {
  921. if _, ok := dstTags[nodeTag.String()]; ok {
  922. addUsers = true
  923. break
  924. }
  925. }
  926. } else {
  927. addUsers = true
  928. }
  929. if addUsers {
  930. // get all src tags
  931. for _, srcAcl := range acl.Src {
  932. if srcAcl.ID == models.UserAclID {
  933. allowedUsers[srcAcl.Value] = append(allowedUsers[srcAcl.Value], acl)
  934. } else if srcAcl.ID == models.UserGroupAclID {
  935. // fetch all users in the group
  936. if usersMap, ok := userGrpMap[models.UserGroupID(srcAcl.Value)]; ok {
  937. for userName := range usersMap {
  938. allowedUsers[userName] = append(allowedUsers[userName], acl)
  939. }
  940. }
  941. }
  942. }
  943. }
  944. }
  945. }
  946. if defaultPolicy.Enabled {
  947. r := models.AclRule{
  948. ID: defaultPolicy.ID,
  949. AllowedProtocol: defaultPolicy.Proto,
  950. AllowedPorts: defaultPolicy.Port,
  951. Direction: defaultPolicy.AllowedDirection,
  952. Allowed: true,
  953. }
  954. for _, userNode := range userNodes {
  955. if !userNode.StaticNode.Enabled {
  956. continue
  957. }
  958. // Get peers in the tags and add allowed rules
  959. if userNode.StaticNode.Address != "" {
  960. r.IPList = append(r.IPList, userNode.StaticNode.AddressIPNet4())
  961. }
  962. if userNode.StaticNode.Address6 != "" {
  963. r.IP6List = append(r.IP6List, userNode.StaticNode.AddressIPNet6())
  964. }
  965. }
  966. rules[defaultPolicy.ID] = r
  967. } else {
  968. for _, userNode := range userNodes {
  969. if !userNode.StaticNode.Enabled {
  970. continue
  971. }
  972. acls, ok := allowedUsers[userNode.StaticNode.OwnerID]
  973. if !ok {
  974. continue
  975. }
  976. for _, acl := range acls {
  977. if !acl.Enabled {
  978. continue
  979. }
  980. egressRanges4 := []net.IPNet{}
  981. egressRanges6 := []net.IPNet{}
  982. for _, dst := range acl.Dst {
  983. if dst.Value == "*" {
  984. e := schema.Egress{Network: targetnode.Network}
  985. eli, _ := e.ListByNetwork(db.WithContext(context.Background()))
  986. for _, eI := range eli {
  987. if !eI.Status || len(eI.Nodes) == 0 {
  988. continue
  989. }
  990. if _, ok := eI.Nodes[targetnode.ID.String()]; ok {
  991. if eI.Range != "" {
  992. _, cidr, err := net.ParseCIDR(eI.Range)
  993. if err == nil {
  994. if cidr.IP.To4() != nil {
  995. egressRanges4 = append(egressRanges4, *cidr)
  996. } else {
  997. egressRanges6 = append(egressRanges6, *cidr)
  998. }
  999. }
  1000. }
  1001. }
  1002. }
  1003. break
  1004. }
  1005. if dst.ID == models.EgressID {
  1006. e := schema.Egress{ID: dst.Value}
  1007. err := e.Get(db.WithContext(context.TODO()))
  1008. if err == nil && e.Status && len(e.Nodes) > 0 {
  1009. if _, ok := e.Nodes[targetnode.ID.String()]; ok {
  1010. if e.Range != "" {
  1011. _, cidr, err := net.ParseCIDR(e.Range)
  1012. if err == nil {
  1013. if cidr.IP.To4() != nil {
  1014. egressRanges4 = append(egressRanges4, *cidr)
  1015. } else {
  1016. egressRanges6 = append(egressRanges6, *cidr)
  1017. }
  1018. }
  1019. }
  1020. }
  1021. }
  1022. }
  1023. }
  1024. r := models.AclRule{
  1025. ID: acl.ID,
  1026. AllowedProtocol: acl.Proto,
  1027. AllowedPorts: acl.Port,
  1028. Direction: acl.AllowedDirection,
  1029. Dst: []net.IPNet{targetnode.AddressIPNet4()},
  1030. Dst6: []net.IPNet{targetnode.AddressIPNet6()},
  1031. Allowed: true,
  1032. }
  1033. if len(egressRanges4) > 0 {
  1034. r.Dst = append(r.Dst, egressRanges4...)
  1035. }
  1036. if len(egressRanges6) > 0 {
  1037. r.Dst6 = append(r.Dst6, egressRanges6...)
  1038. }
  1039. // Get peers in the tags and add allowed rules
  1040. if userNode.StaticNode.Address != "" {
  1041. r.IPList = append(r.IPList, userNode.StaticNode.AddressIPNet4())
  1042. }
  1043. if userNode.StaticNode.Address6 != "" {
  1044. r.IP6List = append(r.IP6List, userNode.StaticNode.AddressIPNet6())
  1045. }
  1046. if aclRule, ok := rules[acl.ID]; ok {
  1047. aclRule.IPList = append(aclRule.IPList, r.IPList...)
  1048. aclRule.IP6List = append(aclRule.IP6List, r.IP6List...)
  1049. aclRule.Dst = append(aclRule.Dst, r.Dst...)
  1050. aclRule.Dst6 = append(aclRule.Dst6, r.Dst6...)
  1051. aclRule.IPList = logic.UniqueIPNetList(aclRule.IPList)
  1052. aclRule.IP6List = logic.UniqueIPNetList(aclRule.IP6List)
  1053. aclRule.Dst = logic.UniqueIPNetList(aclRule.Dst)
  1054. aclRule.Dst6 = logic.UniqueIPNetList(aclRule.Dst6)
  1055. rules[acl.ID] = aclRule
  1056. } else {
  1057. r.IPList = logic.UniqueIPNetList(r.IPList)
  1058. r.IP6List = logic.UniqueIPNetList(r.IP6List)
  1059. r.Dst = logic.UniqueIPNetList(r.Dst)
  1060. r.Dst6 = logic.UniqueIPNetList(r.Dst6)
  1061. rules[acl.ID] = r
  1062. }
  1063. }
  1064. }
  1065. }
  1066. return rules
  1067. }
  1068. func CheckIfAnyPolicyisUniDirectional(targetNode models.Node, acls []models.Acl) bool {
  1069. var targetNodeTags = make(map[models.TagID]struct{})
  1070. if targetNode.Mutex != nil {
  1071. targetNode.Mutex.Lock()
  1072. targetNodeTags = maps.Clone(targetNode.Tags)
  1073. targetNode.Mutex.Unlock()
  1074. } else {
  1075. targetNodeTags = maps.Clone(targetNode.Tags)
  1076. }
  1077. if targetNodeTags == nil {
  1078. targetNodeTags = make(map[models.TagID]struct{})
  1079. }
  1080. targetNodeTags[models.TagID(targetNode.ID.String())] = struct{}{}
  1081. targetNodeTags["*"] = struct{}{}
  1082. for _, acl := range acls {
  1083. if !acl.Enabled {
  1084. continue
  1085. }
  1086. if acl.AllowedDirection == models.TrafficDirectionBi && acl.Proto == models.ALL && acl.ServiceType == models.Any {
  1087. continue
  1088. }
  1089. if acl.Proto != models.ALL || acl.ServiceType != models.Any {
  1090. return true
  1091. }
  1092. srcTags := logic.ConvAclTagToValueMap(acl.Src)
  1093. dstTags := logic.ConvAclTagToValueMap(acl.Dst)
  1094. for nodeTag := range targetNodeTags {
  1095. if acl.RuleType == models.DevicePolicy {
  1096. if _, ok := srcTags[nodeTag.String()]; ok {
  1097. return true
  1098. }
  1099. if _, ok := srcTags[targetNode.ID.String()]; ok {
  1100. return true
  1101. }
  1102. }
  1103. if _, ok := dstTags[nodeTag.String()]; ok {
  1104. return true
  1105. }
  1106. if _, ok := dstTags[targetNode.ID.String()]; ok {
  1107. return true
  1108. }
  1109. }
  1110. }
  1111. return false
  1112. }
  1113. func GetTagMapWithNodesByNetwork(netID models.NetworkID, withStaticNodes bool) (tagNodesMap map[models.TagID][]models.Node) {
  1114. tagNodesMap = make(map[models.TagID][]models.Node)
  1115. nodes, _ := logic.GetNetworkNodes(netID.String())
  1116. for _, nodeI := range nodes {
  1117. tagNodesMap[models.TagID(nodeI.ID.String())] = []models.Node{
  1118. nodeI,
  1119. }
  1120. if nodeI.Tags == nil {
  1121. continue
  1122. }
  1123. if nodeI.Mutex != nil {
  1124. nodeI.Mutex.Lock()
  1125. }
  1126. for nodeTagID := range nodeI.Tags {
  1127. if nodeTagID == models.TagID(nodeI.ID.String()) {
  1128. continue
  1129. }
  1130. tagNodesMap[nodeTagID] = append(tagNodesMap[nodeTagID], nodeI)
  1131. }
  1132. if nodeI.Mutex != nil {
  1133. nodeI.Mutex.Unlock()
  1134. }
  1135. }
  1136. tagNodesMap["*"] = nodes
  1137. if !withStaticNodes {
  1138. return
  1139. }
  1140. return AddTagMapWithStaticNodes(netID, tagNodesMap)
  1141. }
  1142. func AddTagMapWithStaticNodes(netID models.NetworkID,
  1143. tagNodesMap map[models.TagID][]models.Node) map[models.TagID][]models.Node {
  1144. extclients, err := logic.GetNetworkExtClients(netID.String())
  1145. if err != nil {
  1146. return tagNodesMap
  1147. }
  1148. for _, extclient := range extclients {
  1149. if extclient.RemoteAccessClientID != "" {
  1150. continue
  1151. }
  1152. tagNodesMap[models.TagID(extclient.ClientID)] = []models.Node{
  1153. {
  1154. IsStatic: true,
  1155. StaticNode: extclient,
  1156. },
  1157. }
  1158. if extclient.Tags == nil {
  1159. continue
  1160. }
  1161. if extclient.Mutex != nil {
  1162. extclient.Mutex.Lock()
  1163. }
  1164. for tagID := range extclient.Tags {
  1165. if tagID == models.TagID(extclient.ClientID) {
  1166. continue
  1167. }
  1168. tagNodesMap[tagID] = append(tagNodesMap[tagID], extclient.ConvertToStaticNode())
  1169. tagNodesMap["*"] = append(tagNodesMap["*"], extclient.ConvertToStaticNode())
  1170. }
  1171. if extclient.Mutex != nil {
  1172. extclient.Mutex.Unlock()
  1173. }
  1174. }
  1175. return tagNodesMap
  1176. }