acls.go 48 KB

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