acls.go 54 KB

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