acls.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  1. package logic
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "sort"
  7. "sync"
  8. "time"
  9. "github.com/gravitl/netmaker/database"
  10. "github.com/gravitl/netmaker/models"
  11. "github.com/gravitl/netmaker/servercfg"
  12. )
  13. var (
  14. aclCacheMutex = &sync.RWMutex{}
  15. aclCacheMap = make(map[string]models.Acl)
  16. aclNetCacheMutex = &sync.RWMutex{}
  17. aclNetworkCacheMap = make(map[models.NetworkID]AclNetInfo)
  18. )
  19. type AclNetInfo struct {
  20. DevicePolices []models.Acl
  21. UserPolicies []models.Acl
  22. DefaultDevicePolicy models.Acl
  23. DefaultUserPolicy models.Acl
  24. }
  25. func MigrateAclPolicies() {
  26. acls := ListAcls()
  27. for _, acl := range acls {
  28. if acl.Proto.String() == "" {
  29. acl.Proto = models.ALL
  30. acl.ServiceType = models.Any
  31. acl.Port = []string{}
  32. UpsertAcl(acl)
  33. }
  34. }
  35. }
  36. func loadNetworkAclsIntoCache() {
  37. aclNetCacheMutex.Lock()
  38. defer aclNetCacheMutex.Unlock()
  39. aclNetworkCacheMap = make(map[models.NetworkID]AclNetInfo)
  40. acls := ListAcls()
  41. for _, acl := range acls {
  42. aclNetInfo := aclNetworkCacheMap[acl.NetworkID]
  43. if acl.RuleType == models.DevicePolicy {
  44. aclNetInfo.DevicePolices = append(aclNetInfo.DevicePolices, acl)
  45. } else {
  46. aclNetInfo.UserPolicies = append(aclNetInfo.UserPolicies, acl)
  47. }
  48. aclNetworkCacheMap[acl.NetworkID] = aclNetInfo
  49. }
  50. for netID, aclNetInfo := range aclNetworkCacheMap {
  51. defaultDevicePolicy, err := GetDefaultPolicy(models.NetworkID(netID), models.DevicePolicy)
  52. if err == nil {
  53. aclNetInfo.DefaultDevicePolicy = defaultDevicePolicy
  54. aclNetworkCacheMap[netID] = aclNetInfo
  55. }
  56. defaultUserPolicy, err := GetDefaultPolicy(models.NetworkID(netID), models.UserPolicy)
  57. if err == nil {
  58. aclNetInfo.DefaultUserPolicy = defaultUserPolicy
  59. aclNetworkCacheMap[netID] = aclNetInfo
  60. }
  61. }
  62. }
  63. // CreateDefaultAclNetworkPolicies - create default acl network policies
  64. func CreateDefaultAclNetworkPolicies(netID models.NetworkID) {
  65. if netID.String() == "" {
  66. return
  67. }
  68. _, _ = ListAclsByNetwork(netID)
  69. if !IsAclExists(fmt.Sprintf("%s.%s", netID, "all-nodes")) {
  70. defaultDeviceAcl := models.Acl{
  71. ID: fmt.Sprintf("%s.%s", netID, "all-nodes"),
  72. Name: "All Nodes",
  73. MetaData: "This Policy allows all nodes in the network to communicate with each other",
  74. Default: true,
  75. NetworkID: netID,
  76. Proto: models.ALL,
  77. ServiceType: models.Any,
  78. Port: []string{},
  79. RuleType: models.DevicePolicy,
  80. Src: []models.AclPolicyTag{
  81. {
  82. ID: models.DeviceAclID,
  83. Value: "*",
  84. }},
  85. Dst: []models.AclPolicyTag{
  86. {
  87. ID: models.DeviceAclID,
  88. Value: "*",
  89. }},
  90. AllowedDirection: models.TrafficDirectionBi,
  91. Enabled: true,
  92. CreatedBy: "auto",
  93. CreatedAt: time.Now().UTC(),
  94. }
  95. InsertAcl(defaultDeviceAcl)
  96. }
  97. if !IsAclExists(fmt.Sprintf("%s.%s", netID, "all-users")) {
  98. defaultUserAcl := models.Acl{
  99. ID: fmt.Sprintf("%s.%s", netID, "all-users"),
  100. Default: true,
  101. Name: "All Users",
  102. MetaData: "This policy gives access to everything in the network for an user",
  103. NetworkID: netID,
  104. Proto: models.ALL,
  105. ServiceType: models.Any,
  106. Port: []string{},
  107. RuleType: models.UserPolicy,
  108. Src: []models.AclPolicyTag{
  109. {
  110. ID: models.UserAclID,
  111. Value: "*",
  112. },
  113. },
  114. Dst: []models.AclPolicyTag{{
  115. ID: models.DeviceAclID,
  116. Value: "*",
  117. }},
  118. AllowedDirection: models.TrafficDirectionUni,
  119. Enabled: true,
  120. CreatedBy: "auto",
  121. CreatedAt: time.Now().UTC(),
  122. }
  123. InsertAcl(defaultUserAcl)
  124. }
  125. if !IsAclExists(fmt.Sprintf("%s.%s", netID, "all-remote-access-gws")) {
  126. defaultUserAcl := models.Acl{
  127. ID: fmt.Sprintf("%s.%s", netID, "all-remote-access-gws"),
  128. Default: true,
  129. Name: "All Remote Access Gateways",
  130. NetworkID: netID,
  131. Proto: models.ALL,
  132. ServiceType: models.Any,
  133. Port: []string{},
  134. RuleType: models.DevicePolicy,
  135. Src: []models.AclPolicyTag{
  136. {
  137. ID: models.DeviceAclID,
  138. Value: fmt.Sprintf("%s.%s", netID, models.RemoteAccessTagName),
  139. },
  140. },
  141. Dst: []models.AclPolicyTag{
  142. {
  143. ID: models.DeviceAclID,
  144. Value: "*",
  145. },
  146. },
  147. AllowedDirection: models.TrafficDirectionBi,
  148. Enabled: true,
  149. CreatedBy: "auto",
  150. CreatedAt: time.Now().UTC(),
  151. }
  152. InsertAcl(defaultUserAcl)
  153. }
  154. CreateDefaultUserPolicies(netID)
  155. }
  156. // DeleteDefaultNetworkPolicies - deletes all default network acl policies
  157. func DeleteDefaultNetworkPolicies(netId models.NetworkID) {
  158. acls, _ := ListAclsByNetwork(netId)
  159. for _, acl := range acls {
  160. if acl.NetworkID == netId && acl.Default {
  161. DeleteAcl(acl)
  162. }
  163. }
  164. }
  165. // ValidateCreateAclReq - validates create req for acl
  166. func ValidateCreateAclReq(req models.Acl) error {
  167. // check if acl network exists
  168. _, err := GetNetwork(req.NetworkID.String())
  169. if err != nil {
  170. return errors.New("failed to get network details for " + req.NetworkID.String())
  171. }
  172. // err = CheckIDSyntax(req.Name)
  173. // if err != nil {
  174. // return err
  175. // }
  176. return nil
  177. }
  178. func listAclFromCache() (acls []models.Acl) {
  179. aclCacheMutex.RLock()
  180. defer aclCacheMutex.RUnlock()
  181. for _, acl := range aclCacheMap {
  182. acls = append(acls, acl)
  183. }
  184. return
  185. }
  186. func storeAclInCache(a models.Acl) {
  187. aclCacheMutex.Lock()
  188. defer func() {
  189. aclCacheMutex.Unlock()
  190. go loadNetworkAclsIntoCache()
  191. }()
  192. aclCacheMap[a.ID] = a
  193. }
  194. func removeAclFromCache(a models.Acl) {
  195. aclCacheMutex.Lock()
  196. defer func() {
  197. aclCacheMutex.Unlock()
  198. go loadNetworkAclsIntoCache()
  199. }()
  200. delete(aclCacheMap, a.ID)
  201. }
  202. func getAclFromCache(aID string) (a models.Acl, ok bool) {
  203. aclCacheMutex.RLock()
  204. defer aclCacheMutex.RUnlock()
  205. a, ok = aclCacheMap[aID]
  206. return
  207. }
  208. // InsertAcl - creates acl policy
  209. func InsertAcl(a models.Acl) error {
  210. d, err := json.Marshal(a)
  211. if err != nil {
  212. return err
  213. }
  214. err = database.Insert(a.ID, string(d), database.ACLS_TABLE_NAME)
  215. if err == nil && servercfg.CacheEnabled() {
  216. storeAclInCache(a)
  217. }
  218. return err
  219. }
  220. // GetAcl - gets acl info by id
  221. func GetAcl(aID string) (models.Acl, error) {
  222. a := models.Acl{}
  223. if servercfg.CacheEnabled() {
  224. var ok bool
  225. a, ok = getAclFromCache(aID)
  226. if ok {
  227. return a, nil
  228. }
  229. }
  230. d, err := database.FetchRecord(database.ACLS_TABLE_NAME, aID)
  231. if err != nil {
  232. return a, err
  233. }
  234. err = json.Unmarshal([]byte(d), &a)
  235. if err != nil {
  236. return a, err
  237. }
  238. if servercfg.CacheEnabled() {
  239. storeAclInCache(a)
  240. }
  241. return a, nil
  242. }
  243. // IsAclExists - checks if acl exists
  244. func IsAclExists(aclID string) bool {
  245. _, err := GetAcl(aclID)
  246. return err == nil
  247. }
  248. // IsAclPolicyValid - validates if acl policy is valid
  249. func IsAclPolicyValid(acl models.Acl) bool {
  250. //check if src and dst are valid
  251. if acl.AllowedDirection != models.TrafficDirectionBi &&
  252. acl.AllowedDirection != models.TrafficDirectionUni {
  253. return false
  254. }
  255. switch acl.RuleType {
  256. case models.UserPolicy:
  257. // src list should only contain users
  258. for _, srcI := range acl.Src {
  259. if srcI.ID == "" || srcI.Value == "" {
  260. return false
  261. }
  262. if srcI.Value == "*" {
  263. continue
  264. }
  265. if srcI.ID != models.UserAclID && srcI.ID != models.UserGroupAclID {
  266. return false
  267. }
  268. // check if user group is valid
  269. if srcI.ID == models.UserAclID {
  270. _, err := GetUser(srcI.Value)
  271. if err != nil {
  272. return false
  273. }
  274. } else if srcI.ID == models.UserGroupAclID {
  275. err := IsGroupValid(models.UserGroupID(srcI.Value))
  276. if err != nil {
  277. return false
  278. }
  279. // check if group belongs to this network
  280. netGrps := GetUserGroupsInNetwork(acl.NetworkID)
  281. if _, ok := netGrps[models.UserGroupID(srcI.Value)]; !ok {
  282. return false
  283. }
  284. }
  285. }
  286. for _, dstI := range acl.Dst {
  287. if dstI.ID == "" || dstI.Value == "" {
  288. return false
  289. }
  290. if dstI.ID != models.DeviceAclID {
  291. return false
  292. }
  293. if dstI.Value == "*" {
  294. continue
  295. }
  296. // check if tag is valid
  297. _, err := GetTag(models.TagID(dstI.Value))
  298. if err != nil {
  299. return false
  300. }
  301. }
  302. case models.DevicePolicy:
  303. for _, srcI := range acl.Src {
  304. if srcI.ID == "" || srcI.Value == "" {
  305. return false
  306. }
  307. if srcI.ID != models.DeviceAclID {
  308. return false
  309. }
  310. if srcI.Value == "*" {
  311. continue
  312. }
  313. // check if tag is valid
  314. _, err := GetTag(models.TagID(srcI.Value))
  315. if err != nil {
  316. return false
  317. }
  318. }
  319. for _, dstI := range acl.Dst {
  320. if dstI.ID == "" || dstI.Value == "" {
  321. return false
  322. }
  323. if dstI.ID != models.DeviceAclID {
  324. return false
  325. }
  326. if dstI.Value == "*" {
  327. continue
  328. }
  329. // check if tag is valid
  330. _, err := GetTag(models.TagID(dstI.Value))
  331. if err != nil {
  332. return false
  333. }
  334. }
  335. }
  336. return true
  337. }
  338. // UpdateAcl - updates allowed fields on acls and commits to DB
  339. func UpdateAcl(newAcl, acl models.Acl) error {
  340. if !acl.Default {
  341. acl.Name = newAcl.Name
  342. acl.Src = newAcl.Src
  343. acl.Dst = newAcl.Dst
  344. acl.AllowedDirection = newAcl.AllowedDirection
  345. acl.Port = newAcl.Port
  346. acl.Proto = newAcl.Proto
  347. acl.ServiceType = newAcl.ServiceType
  348. }
  349. if newAcl.ServiceType == models.Any {
  350. acl.Port = []string{}
  351. acl.Proto = models.ALL
  352. }
  353. acl.Enabled = newAcl.Enabled
  354. d, err := json.Marshal(acl)
  355. if err != nil {
  356. return err
  357. }
  358. err = database.Insert(acl.ID, string(d), database.ACLS_TABLE_NAME)
  359. if err == nil && servercfg.CacheEnabled() {
  360. storeAclInCache(acl)
  361. }
  362. return err
  363. }
  364. // UpsertAcl - upserts acl
  365. func UpsertAcl(acl models.Acl) error {
  366. d, err := json.Marshal(acl)
  367. if err != nil {
  368. return err
  369. }
  370. err = database.Insert(acl.ID, string(d), database.ACLS_TABLE_NAME)
  371. if err == nil && servercfg.CacheEnabled() {
  372. storeAclInCache(acl)
  373. }
  374. return err
  375. }
  376. // DeleteAcl - deletes acl policy
  377. func DeleteAcl(a models.Acl) error {
  378. err := database.DeleteRecord(database.ACLS_TABLE_NAME, a.ID)
  379. if err == nil && servercfg.CacheEnabled() {
  380. removeAclFromCache(a)
  381. }
  382. return err
  383. }
  384. // GetDefaultPolicy - fetches default policy in the network by ruleType
  385. func GetDefaultPolicy(netID models.NetworkID, ruleType models.AclPolicyType) (models.Acl, error) {
  386. aclID := "all-users"
  387. if ruleType == models.DevicePolicy {
  388. aclID = "all-nodes"
  389. }
  390. acl, err := GetAcl(fmt.Sprintf("%s.%s", netID, aclID))
  391. if err != nil {
  392. return models.Acl{}, errors.New("default rule not found")
  393. }
  394. if acl.Enabled {
  395. return acl, nil
  396. }
  397. // check if there are any custom all policies
  398. srcMap := make(map[string]struct{})
  399. dstMap := make(map[string]struct{})
  400. defer func() {
  401. srcMap = nil
  402. dstMap = nil
  403. }()
  404. policies, _ := ListAclsByNetwork(netID)
  405. for _, policy := range policies {
  406. if !policy.Enabled {
  407. continue
  408. }
  409. if policy.RuleType == ruleType {
  410. dstMap = convAclTagToValueMap(policy.Dst)
  411. srcMap = convAclTagToValueMap(policy.Src)
  412. if _, ok := srcMap["*"]; ok {
  413. if _, ok := dstMap["*"]; ok {
  414. return policy, nil
  415. }
  416. }
  417. }
  418. }
  419. return acl, nil
  420. }
  421. func ListAcls() (acls []models.Acl) {
  422. if servercfg.CacheEnabled() && len(aclCacheMap) > 0 {
  423. return listAclFromCache()
  424. }
  425. data, err := database.FetchRecords(database.ACLS_TABLE_NAME)
  426. if err != nil && !database.IsEmptyRecord(err) {
  427. return []models.Acl{}
  428. }
  429. for _, dataI := range data {
  430. acl := models.Acl{}
  431. err := json.Unmarshal([]byte(dataI), &acl)
  432. if err != nil {
  433. continue
  434. }
  435. acls = append(acls, acl)
  436. if servercfg.CacheEnabled() {
  437. storeAclInCache(acl)
  438. }
  439. }
  440. return
  441. }
  442. // ListUserPolicies - lists all acl policies enforced on an user
  443. func ListUserPolicies(u models.User) []models.Acl {
  444. allAcls := ListAcls()
  445. userAcls := []models.Acl{}
  446. for _, acl := range allAcls {
  447. if acl.RuleType == models.UserPolicy {
  448. srcMap := convAclTagToValueMap(acl.Src)
  449. if _, ok := srcMap[u.UserName]; ok {
  450. userAcls = append(userAcls, acl)
  451. } else {
  452. // check for user groups
  453. for gID := range u.UserGroups {
  454. if _, ok := srcMap[gID.String()]; ok {
  455. userAcls = append(userAcls, acl)
  456. break
  457. }
  458. }
  459. }
  460. }
  461. }
  462. return userAcls
  463. }
  464. // listPoliciesOfUser - lists all user acl policies applied to user in an network
  465. func listPoliciesOfUser(user models.User, netID models.NetworkID) []models.Acl {
  466. allAcls := ListAcls()
  467. userAcls := []models.Acl{}
  468. for _, acl := range allAcls {
  469. if acl.NetworkID == netID && acl.RuleType == models.UserPolicy {
  470. srcMap := convAclTagToValueMap(acl.Src)
  471. if _, ok := srcMap[user.UserName]; ok {
  472. userAcls = append(userAcls, acl)
  473. continue
  474. }
  475. for netRole := range user.NetworkRoles {
  476. if _, ok := srcMap[netRole.String()]; ok {
  477. userAcls = append(userAcls, acl)
  478. continue
  479. }
  480. }
  481. for userG := range user.UserGroups {
  482. if _, ok := srcMap[userG.String()]; ok {
  483. userAcls = append(userAcls, acl)
  484. continue
  485. }
  486. }
  487. }
  488. }
  489. return userAcls
  490. }
  491. func GetDefaultPolicyFromNetCache(netID models.NetworkID, ruleType models.AclPolicyType) models.Acl {
  492. aclNetCacheMutex.RLock()
  493. defer aclNetCacheMutex.RUnlock()
  494. if aclNetInfo, ok := aclNetworkCacheMap[netID]; ok {
  495. if ruleType == models.DevicePolicy {
  496. return aclNetInfo.DefaultDevicePolicy
  497. } else {
  498. return aclNetInfo.DefaultUserPolicy
  499. }
  500. }
  501. return models.Acl{}
  502. }
  503. func listPolicesFromNetCache(netID models.NetworkID, ruleType models.AclPolicyType) []models.Acl {
  504. aclNetCacheMutex.RLock()
  505. if aclNetInfo, ok := aclNetworkCacheMap[netID]; ok {
  506. if ruleType == models.DevicePolicy {
  507. aclNetCacheMutex.RUnlock()
  508. return aclNetInfo.DevicePolices
  509. } else {
  510. aclNetCacheMutex.RUnlock()
  511. return aclNetInfo.UserPolicies
  512. }
  513. }
  514. aclNetCacheMutex.RUnlock()
  515. if ruleType == models.DevicePolicy {
  516. return listDevicePolicies(netID)
  517. }
  518. return listUserPolicies(netID)
  519. }
  520. // listDevicePolicies - lists all device policies in a network
  521. func listDevicePolicies(netID models.NetworkID) []models.Acl {
  522. allAcls := ListAcls()
  523. deviceAcls := []models.Acl{}
  524. for _, acl := range allAcls {
  525. if acl.NetworkID == netID && acl.RuleType == models.DevicePolicy {
  526. deviceAcls = append(deviceAcls, acl)
  527. }
  528. }
  529. return deviceAcls
  530. }
  531. // listUserPolicies - lists all user policies in a network
  532. func listUserPolicies(netID models.NetworkID) []models.Acl {
  533. allAcls := ListAcls()
  534. deviceAcls := []models.Acl{}
  535. for _, acl := range allAcls {
  536. if acl.NetworkID == netID && acl.RuleType == models.UserPolicy {
  537. deviceAcls = append(deviceAcls, acl)
  538. }
  539. }
  540. return deviceAcls
  541. }
  542. // ListAcls - lists all acl policies
  543. func ListAclsByNetwork(netID models.NetworkID) ([]models.Acl, error) {
  544. allAcls := ListAcls()
  545. netAcls := []models.Acl{}
  546. for _, acl := range allAcls {
  547. if acl.NetworkID == netID {
  548. netAcls = append(netAcls, acl)
  549. }
  550. }
  551. return netAcls, nil
  552. }
  553. func convAclTagToValueMap(acltags []models.AclPolicyTag) map[string]struct{} {
  554. aclValueMap := make(map[string]struct{})
  555. for _, aclTagI := range acltags {
  556. aclValueMap[aclTagI.Value] = struct{}{}
  557. }
  558. return aclValueMap
  559. }
  560. // IsUserAllowedToCommunicate - check if user is allowed to communicate with peer
  561. func IsUserAllowedToCommunicate(userName string, peer models.Node) (bool, []models.Acl) {
  562. if peer.IsStatic {
  563. peer = peer.StaticNode.ConvertToStaticNode()
  564. }
  565. acl, _ := GetDefaultPolicy(models.NetworkID(peer.Network), models.UserPolicy)
  566. if acl.Enabled {
  567. return true, []models.Acl{acl}
  568. }
  569. user, err := GetUser(userName)
  570. if err != nil {
  571. return false, []models.Acl{}
  572. }
  573. allowedPolicies := []models.Acl{}
  574. policies := listPoliciesOfUser(*user, models.NetworkID(peer.Network))
  575. for _, policy := range policies {
  576. if !policy.Enabled {
  577. continue
  578. }
  579. dstMap := convAclTagToValueMap(policy.Dst)
  580. if _, ok := dstMap["*"]; ok {
  581. allowedPolicies = append(allowedPolicies, policy)
  582. continue
  583. }
  584. for tagID := range peer.Tags {
  585. if _, ok := dstMap[tagID.String()]; ok {
  586. allowedPolicies = append(allowedPolicies, policy)
  587. break
  588. }
  589. }
  590. }
  591. if len(allowedPolicies) > 0 {
  592. return true, allowedPolicies
  593. }
  594. return false, []models.Acl{}
  595. }
  596. // IsPeerAllowed - checks if peer needs to be added to the interface
  597. func IsPeerAllowed(node, peer models.Node, checkDefaultPolicy bool) bool {
  598. if node.IsStatic {
  599. node = node.StaticNode.ConvertToStaticNode()
  600. }
  601. if peer.IsStatic {
  602. peer = peer.StaticNode.ConvertToStaticNode()
  603. }
  604. if checkDefaultPolicy {
  605. // check default policy if all allowed return true
  606. defaultPolicy, err := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  607. if err == nil {
  608. if defaultPolicy.Enabled {
  609. return true
  610. }
  611. }
  612. }
  613. // list device policies
  614. policies := listPolicesFromNetCache(models.NetworkID(node.Network), models.DevicePolicy)
  615. srcMap := make(map[string]struct{})
  616. dstMap := make(map[string]struct{})
  617. defer func() {
  618. srcMap = nil
  619. dstMap = nil
  620. }()
  621. for _, policy := range policies {
  622. if !policy.Enabled {
  623. continue
  624. }
  625. srcMap = convAclTagToValueMap(policy.Src)
  626. dstMap = convAclTagToValueMap(policy.Dst)
  627. for tagID := range node.Tags {
  628. if _, ok := dstMap[tagID.String()]; ok {
  629. if _, ok := srcMap["*"]; ok {
  630. return true
  631. }
  632. for tagID := range peer.Tags {
  633. if _, ok := srcMap[tagID.String()]; ok {
  634. return true
  635. }
  636. }
  637. }
  638. if _, ok := srcMap[tagID.String()]; ok {
  639. if _, ok := dstMap["*"]; ok {
  640. return true
  641. }
  642. for tagID := range peer.Tags {
  643. if _, ok := dstMap[tagID.String()]; ok {
  644. return true
  645. }
  646. }
  647. }
  648. }
  649. for tagID := range peer.Tags {
  650. if _, ok := dstMap[tagID.String()]; ok {
  651. if _, ok := srcMap["*"]; ok {
  652. return true
  653. }
  654. for tagID := range node.Tags {
  655. if _, ok := srcMap[tagID.String()]; ok {
  656. return true
  657. }
  658. }
  659. }
  660. if _, ok := srcMap[tagID.String()]; ok {
  661. if _, ok := dstMap["*"]; ok {
  662. return true
  663. }
  664. for tagID := range node.Tags {
  665. if _, ok := dstMap[tagID.String()]; ok {
  666. return true
  667. }
  668. }
  669. }
  670. }
  671. }
  672. return false
  673. }
  674. // IsNodeAllowedToCommunicate - check node is allowed to communicate with the peer
  675. func IsNodeAllowedToCommunicate(node, peer models.Node, checkDefaultPolicy bool) (bool, []models.Acl) {
  676. if node.IsStatic {
  677. node = node.StaticNode.ConvertToStaticNode()
  678. }
  679. if peer.IsStatic {
  680. peer = peer.StaticNode.ConvertToStaticNode()
  681. }
  682. if checkDefaultPolicy {
  683. // check default policy if all allowed return true
  684. defaultPolicy, err := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)
  685. if err == nil {
  686. if defaultPolicy.Enabled {
  687. return true, []models.Acl{defaultPolicy}
  688. }
  689. }
  690. }
  691. allowedPolicies := []models.Acl{}
  692. // list device policies
  693. policies := listDevicePolicies(models.NetworkID(peer.Network))
  694. srcMap := make(map[string]struct{})
  695. dstMap := make(map[string]struct{})
  696. defer func() {
  697. srcMap = nil
  698. dstMap = nil
  699. }()
  700. for _, policy := range policies {
  701. if !policy.Enabled {
  702. continue
  703. }
  704. srcMap = convAclTagToValueMap(policy.Src)
  705. dstMap = convAclTagToValueMap(policy.Dst)
  706. for tagID := range node.Tags {
  707. allowed := false
  708. if _, ok := dstMap[tagID.String()]; policy.AllowedDirection == models.TrafficDirectionBi && ok {
  709. if _, ok := srcMap["*"]; ok {
  710. allowed = true
  711. allowedPolicies = append(allowedPolicies, policy)
  712. break
  713. }
  714. for tagID := range peer.Tags {
  715. if _, ok := srcMap[tagID.String()]; ok {
  716. allowed = true
  717. break
  718. }
  719. }
  720. }
  721. if allowed {
  722. allowedPolicies = append(allowedPolicies, policy)
  723. break
  724. }
  725. if _, ok := srcMap[tagID.String()]; ok {
  726. if _, ok := dstMap["*"]; ok {
  727. allowed = true
  728. allowedPolicies = append(allowedPolicies, policy)
  729. break
  730. }
  731. for tagID := range peer.Tags {
  732. if _, ok := dstMap[tagID.String()]; ok {
  733. allowed = true
  734. break
  735. }
  736. }
  737. }
  738. if allowed {
  739. allowedPolicies = append(allowedPolicies, policy)
  740. break
  741. }
  742. }
  743. for tagID := range peer.Tags {
  744. allowed := false
  745. if _, ok := dstMap[tagID.String()]; ok {
  746. if _, ok := srcMap["*"]; ok {
  747. allowed = true
  748. allowedPolicies = append(allowedPolicies, policy)
  749. break
  750. }
  751. for tagID := range node.Tags {
  752. if _, ok := srcMap[tagID.String()]; ok {
  753. allowed = true
  754. break
  755. }
  756. }
  757. }
  758. if allowed {
  759. allowedPolicies = append(allowedPolicies, policy)
  760. break
  761. }
  762. if _, ok := srcMap[tagID.String()]; policy.AllowedDirection == models.TrafficDirectionBi && ok {
  763. if _, ok := dstMap["*"]; ok {
  764. allowed = true
  765. allowedPolicies = append(allowedPolicies, policy)
  766. break
  767. }
  768. for tagID := range node.Tags {
  769. if _, ok := dstMap[tagID.String()]; ok {
  770. allowed = true
  771. break
  772. }
  773. }
  774. }
  775. if allowed {
  776. allowedPolicies = append(allowedPolicies, policy)
  777. break
  778. }
  779. }
  780. }
  781. if len(allowedPolicies) > 0 {
  782. return true, allowedPolicies
  783. }
  784. return false, allowedPolicies
  785. }
  786. // SortTagEntrys - Sorts slice of Tag entries by their id
  787. func SortAclEntrys(acls []models.Acl) {
  788. sort.Slice(acls, func(i, j int) bool {
  789. return acls[i].Name < acls[j].Name
  790. })
  791. }
  792. // UpdateDeviceTag - updates device tag on acl policies
  793. func UpdateDeviceTag(OldID, newID models.TagID, netID models.NetworkID) {
  794. acls := listDevicePolicies(netID)
  795. update := false
  796. for _, acl := range acls {
  797. for i, srcTagI := range acl.Src {
  798. if srcTagI.ID == models.DeviceAclID {
  799. if OldID.String() == srcTagI.Value {
  800. acl.Src[i].Value = newID.String()
  801. update = true
  802. }
  803. }
  804. }
  805. for i, dstTagI := range acl.Dst {
  806. if dstTagI.ID == models.DeviceAclID {
  807. if OldID.String() == dstTagI.Value {
  808. acl.Dst[i].Value = newID.String()
  809. update = true
  810. }
  811. }
  812. }
  813. if update {
  814. UpsertAcl(acl)
  815. }
  816. }
  817. }
  818. func CheckIfTagAsActivePolicy(tagID models.TagID, netID models.NetworkID) bool {
  819. acls := listDevicePolicies(netID)
  820. for _, acl := range acls {
  821. for _, srcTagI := range acl.Src {
  822. if srcTagI.ID == models.DeviceAclID {
  823. if tagID.String() == srcTagI.Value {
  824. return true
  825. }
  826. }
  827. }
  828. for _, dstTagI := range acl.Dst {
  829. if dstTagI.ID == models.DeviceAclID {
  830. if tagID.String() == dstTagI.Value {
  831. return true
  832. }
  833. }
  834. }
  835. }
  836. return false
  837. }
  838. // RemoveDeviceTagFromAclPolicies - remove device tag from acl policies
  839. func RemoveDeviceTagFromAclPolicies(tagID models.TagID, netID models.NetworkID) error {
  840. acls := listDevicePolicies(netID)
  841. update := false
  842. for _, acl := range acls {
  843. for i, srcTagI := range acl.Src {
  844. if srcTagI.ID == models.DeviceAclID {
  845. if tagID.String() == srcTagI.Value {
  846. acl.Src = append(acl.Src[:i], acl.Src[i+1:]...)
  847. update = true
  848. }
  849. }
  850. }
  851. for i, dstTagI := range acl.Dst {
  852. if dstTagI.ID == models.DeviceAclID {
  853. if tagID.String() == dstTagI.Value {
  854. acl.Dst = append(acl.Dst[:i], acl.Dst[i+1:]...)
  855. update = true
  856. }
  857. }
  858. }
  859. if update {
  860. UpsertAcl(acl)
  861. }
  862. }
  863. return nil
  864. }
  865. func getUserAclRulesForNode(targetnode *models.Node,
  866. rules map[string]models.AclRule) map[string]models.AclRule {
  867. userNodes := GetStaticUserNodesByNetwork(models.NetworkID(targetnode.Network))
  868. userGrpMap := GetUserGrpMap()
  869. allowedUsers := make(map[string][]models.Acl)
  870. acls := listUserPolicies(models.NetworkID(targetnode.Network))
  871. for nodeTag := range targetnode.Tags {
  872. for _, acl := range acls {
  873. if !acl.Enabled {
  874. continue
  875. }
  876. dstTags := convAclTagToValueMap(acl.Dst)
  877. if _, ok := dstTags[nodeTag.String()]; ok {
  878. // get all src tags
  879. for _, srcAcl := range acl.Src {
  880. if srcAcl.ID == models.UserAclID {
  881. allowedUsers[srcAcl.Value] = append(allowedUsers[srcAcl.Value], acl)
  882. } else if srcAcl.ID == models.UserGroupAclID {
  883. // fetch all users in the group
  884. if usersMap, ok := userGrpMap[models.UserGroupID(srcAcl.Value)]; ok {
  885. for userName := range usersMap {
  886. allowedUsers[userName] = append(allowedUsers[userName], acl)
  887. }
  888. }
  889. }
  890. }
  891. }
  892. }
  893. }
  894. for _, userNode := range userNodes {
  895. if !userNode.StaticNode.Enabled {
  896. continue
  897. }
  898. acls, ok := allowedUsers[userNode.StaticNode.OwnerID]
  899. if !ok {
  900. continue
  901. }
  902. for _, acl := range acls {
  903. if !acl.Enabled {
  904. continue
  905. }
  906. r := models.AclRule{
  907. ID: acl.ID,
  908. AllowedProtocol: acl.Proto,
  909. AllowedPorts: acl.Port,
  910. Direction: acl.AllowedDirection,
  911. Allowed: true,
  912. }
  913. // Get peers in the tags and add allowed rules
  914. if userNode.StaticNode.Address != "" {
  915. r.IPList = append(r.IPList, userNode.StaticNode.AddressIPNet4())
  916. }
  917. if userNode.StaticNode.Address6 != "" {
  918. r.IP6List = append(r.IP6List, userNode.StaticNode.AddressIPNet6())
  919. }
  920. if aclRule, ok := rules[acl.ID]; ok {
  921. aclRule.IPList = append(aclRule.IPList, r.IPList...)
  922. aclRule.IP6List = append(aclRule.IP6List, r.IP6List...)
  923. rules[acl.ID] = aclRule
  924. } else {
  925. rules[acl.ID] = r
  926. }
  927. }
  928. }
  929. return rules
  930. }
  931. func GetAclRulesForNode(targetnode *models.Node) (rules map[string]models.AclRule) {
  932. defer func() {
  933. if !targetnode.IsIngressGateway {
  934. rules = getUserAclRulesForNode(targetnode, rules)
  935. }
  936. }()
  937. rules = make(map[string]models.AclRule)
  938. var taggedNodes map[models.TagID][]models.Node
  939. if targetnode.IsIngressGateway {
  940. taggedNodes = GetTagMapWithNodesByNetwork(models.NetworkID(targetnode.Network), false)
  941. } else {
  942. taggedNodes = GetTagMapWithNodesByNetwork(models.NetworkID(targetnode.Network), true)
  943. }
  944. acls := listDevicePolicies(models.NetworkID(targetnode.Network))
  945. targetnode.Tags["*"] = struct{}{}
  946. for nodeTag := range targetnode.Tags {
  947. for _, acl := range acls {
  948. if !acl.Enabled {
  949. continue
  950. }
  951. srcTags := convAclTagToValueMap(acl.Src)
  952. dstTags := convAclTagToValueMap(acl.Dst)
  953. aclRule := models.AclRule{
  954. ID: acl.ID,
  955. AllowedProtocol: acl.Proto,
  956. AllowedPorts: acl.Port,
  957. Direction: acl.AllowedDirection,
  958. Allowed: true,
  959. }
  960. if acl.AllowedDirection == models.TrafficDirectionBi {
  961. var existsInSrcTag bool
  962. var existsInDstTag bool
  963. if _, ok := srcTags[nodeTag.String()]; ok {
  964. existsInSrcTag = true
  965. }
  966. if _, ok := dstTags[nodeTag.String()]; ok {
  967. existsInDstTag = true
  968. }
  969. if existsInSrcTag && !existsInDstTag {
  970. // get all dst tags
  971. for dst := range dstTags {
  972. if dst == nodeTag.String() {
  973. continue
  974. }
  975. // Get peers in the tags and add allowed rules
  976. nodes := taggedNodes[models.TagID(dst)]
  977. for _, node := range nodes {
  978. if node.ID == targetnode.ID {
  979. continue
  980. }
  981. if node.Address.IP != nil {
  982. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  983. }
  984. if node.Address6.IP != nil {
  985. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  986. }
  987. if node.IsStatic && node.StaticNode.Address != "" {
  988. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  989. }
  990. if node.IsStatic && node.StaticNode.Address6 != "" {
  991. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  992. }
  993. }
  994. }
  995. }
  996. if existsInDstTag && !existsInSrcTag {
  997. // get all src tags
  998. for src := range srcTags {
  999. if src == nodeTag.String() {
  1000. continue
  1001. }
  1002. // Get peers in the tags and add allowed rules
  1003. nodes := taggedNodes[models.TagID(src)]
  1004. for _, node := range nodes {
  1005. if node.ID == targetnode.ID {
  1006. continue
  1007. }
  1008. if node.Address.IP != nil {
  1009. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  1010. }
  1011. if node.Address6.IP != nil {
  1012. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  1013. }
  1014. if node.IsStatic && node.StaticNode.Address != "" {
  1015. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  1016. }
  1017. if node.IsStatic && node.StaticNode.Address6 != "" {
  1018. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  1019. }
  1020. }
  1021. }
  1022. }
  1023. if existsInDstTag && existsInSrcTag {
  1024. nodes := taggedNodes[nodeTag]
  1025. for _, node := range nodes {
  1026. if node.ID == targetnode.ID {
  1027. continue
  1028. }
  1029. if node.Address.IP != nil {
  1030. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  1031. }
  1032. if node.Address6.IP != nil {
  1033. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  1034. }
  1035. if node.IsStatic && node.StaticNode.Address != "" {
  1036. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  1037. }
  1038. if node.IsStatic && node.StaticNode.Address6 != "" {
  1039. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  1040. }
  1041. }
  1042. }
  1043. } else {
  1044. _, all := dstTags["*"]
  1045. if _, ok := dstTags[nodeTag.String()]; ok || all {
  1046. // get all src tags
  1047. for src := range srcTags {
  1048. if src == nodeTag.String() {
  1049. continue
  1050. }
  1051. // Get peers in the tags and add allowed rules
  1052. nodes := taggedNodes[models.TagID(src)]
  1053. for _, node := range nodes {
  1054. if node.ID == targetnode.ID {
  1055. continue
  1056. }
  1057. if node.Address.IP != nil {
  1058. aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())
  1059. }
  1060. if node.Address6.IP != nil {
  1061. aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())
  1062. }
  1063. if node.IsStatic && node.StaticNode.Address != "" {
  1064. aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())
  1065. }
  1066. if node.IsStatic && node.StaticNode.Address6 != "" {
  1067. aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())
  1068. }
  1069. }
  1070. }
  1071. }
  1072. }
  1073. if len(aclRule.IPList) > 0 || len(aclRule.IP6List) > 0 {
  1074. rules[acl.ID] = aclRule
  1075. }
  1076. }
  1077. }
  1078. return rules
  1079. }