| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067 | package logicimport (	"encoding/json"	"errors"	"fmt"	"sort"	"sync"	"time"	"github.com/gravitl/netmaker/database"	"github.com/gravitl/netmaker/models"	"github.com/gravitl/netmaker/servercfg")var (	aclCacheMutex = &sync.RWMutex{}	aclCacheMap   = make(map[string]models.Acl))func MigrateAclPolicies() {	acls := ListAcls()	for _, acl := range acls {		if acl.Proto.String() == "" {			acl.Proto = models.ALL			acl.ServiceType = models.Any			acl.Port = []string{}			UpsertAcl(acl)		}	}}// CreateDefaultAclNetworkPolicies - create default acl network policiesfunc CreateDefaultAclNetworkPolicies(netID models.NetworkID) {	if netID.String() == "" {		return	}	_, _ = ListAclsByNetwork(netID)	if !IsAclExists(fmt.Sprintf("%s.%s", netID, "all-nodes")) {		defaultDeviceAcl := models.Acl{			ID:        fmt.Sprintf("%s.%s", netID, "all-nodes"),			Name:      "All Nodes",			MetaData:  "This Policy allows all nodes in the network to communicate with each other",			Default:   true,			NetworkID: netID,			Proto:     models.ALL,			Port:      []string{},			RuleType:  models.DevicePolicy,			Src: []models.AclPolicyTag{				{					ID:    models.DeviceAclID,					Value: "*",				}},			Dst: []models.AclPolicyTag{				{					ID:    models.DeviceAclID,					Value: "*",				}},			AllowedDirection: models.TrafficDirectionBi,			Enabled:          true,			CreatedBy:        "auto",			CreatedAt:        time.Now().UTC(),		}		InsertAcl(defaultDeviceAcl)	}	if !IsAclExists(fmt.Sprintf("%s.%s", netID, "all-users")) {		defaultUserAcl := models.Acl{			ID:        fmt.Sprintf("%s.%s", netID, "all-users"),			Default:   true,			Name:      "All Users",			MetaData:  "This policy gives access to everything in the network for an user",			NetworkID: netID,			Proto:     models.ALL,			Port:      []string{},			RuleType:  models.UserPolicy,			Src: []models.AclPolicyTag{				{					ID:    models.UserAclID,					Value: "*",				},			},			Dst: []models.AclPolicyTag{{				ID:    models.DeviceAclID,				Value: "*",			}},			AllowedDirection: models.TrafficDirectionUni,			Enabled:          true,			CreatedBy:        "auto",			CreatedAt:        time.Now().UTC(),		}		InsertAcl(defaultUserAcl)	}	if !IsAclExists(fmt.Sprintf("%s.%s", netID, "all-remote-access-gws")) {		defaultUserAcl := models.Acl{			ID:        fmt.Sprintf("%s.%s", netID, "all-remote-access-gws"),			Default:   true,			Name:      "All Remote Access Gateways",			NetworkID: netID,			Proto:     models.ALL,			Port:      []string{},			RuleType:  models.DevicePolicy,			Src: []models.AclPolicyTag{				{					ID:    models.DeviceAclID,					Value: fmt.Sprintf("%s.%s", netID, models.RemoteAccessTagName),				},			},			Dst: []models.AclPolicyTag{				{					ID:    models.DeviceAclID,					Value: "*",				},			},			AllowedDirection: models.TrafficDirectionBi,			Enabled:          true,			CreatedBy:        "auto",			CreatedAt:        time.Now().UTC(),		}		InsertAcl(defaultUserAcl)	}	CreateDefaultUserPolicies(netID)}// DeleteDefaultNetworkPolicies - deletes all default network acl policiesfunc DeleteDefaultNetworkPolicies(netId models.NetworkID) {	acls, _ := ListAclsByNetwork(netId)	for _, acl := range acls {		if acl.NetworkID == netId && acl.Default {			DeleteAcl(acl)		}	}}// ValidateCreateAclReq - validates create req for aclfunc ValidateCreateAclReq(req models.Acl) error {	// check if acl network exists	_, err := GetNetwork(req.NetworkID.String())	if err != nil {		return errors.New("failed to get network details for " + req.NetworkID.String())	}	// err = CheckIDSyntax(req.Name)	// if err != nil {	// 	return err	// }	return nil}func listAclFromCache() (acls []models.Acl) {	aclCacheMutex.RLock()	defer aclCacheMutex.RUnlock()	for _, acl := range aclCacheMap {		acls = append(acls, acl)	}	return}func storeAclInCache(a models.Acl) {	aclCacheMutex.Lock()	defer aclCacheMutex.Unlock()	aclCacheMap[a.ID] = a}func removeAclFromCache(a models.Acl) {	aclCacheMutex.Lock()	defer aclCacheMutex.Unlock()	delete(aclCacheMap, a.ID)}func getAclFromCache(aID string) (a models.Acl, ok bool) {	aclCacheMutex.RLock()	defer aclCacheMutex.RUnlock()	a, ok = aclCacheMap[aID]	return}// InsertAcl - creates acl policyfunc InsertAcl(a models.Acl) error {	d, err := json.Marshal(a)	if err != nil {		return err	}	err = database.Insert(a.ID, string(d), database.ACLS_TABLE_NAME)	if err == nil && servercfg.CacheEnabled() {		storeAclInCache(a)	}	return err}// GetAcl - gets acl info by idfunc GetAcl(aID string) (models.Acl, error) {	a := models.Acl{}	if servercfg.CacheEnabled() {		var ok bool		a, ok = getAclFromCache(aID)		if ok {			return a, nil		}	}	d, err := database.FetchRecord(database.ACLS_TABLE_NAME, aID)	if err != nil {		return a, err	}	err = json.Unmarshal([]byte(d), &a)	if err != nil {		return a, err	}	if servercfg.CacheEnabled() {		storeAclInCache(a)	}	return a, nil}// IsAclExists - checks if acl existsfunc IsAclExists(aclID string) bool {	_, err := GetAcl(aclID)	return err == nil}// IsAclPolicyValid - validates if acl policy is validfunc IsAclPolicyValid(acl models.Acl) bool {	//check if src and dst are valid	if acl.AllowedDirection != models.TrafficDirectionBi &&		acl.AllowedDirection != models.TrafficDirectionUni {		return false	}	switch acl.RuleType {	case models.UserPolicy:		// src list should only contain users		for _, srcI := range acl.Src {			if srcI.ID == "" || srcI.Value == "" {				return false			}			if srcI.Value == "*" {				continue			}			if srcI.ID != models.UserAclID && srcI.ID != models.UserGroupAclID {				return false			}			// check if user group is valid			if srcI.ID == models.UserAclID {				_, err := GetUser(srcI.Value)				if err != nil {					return false				}			} else if srcI.ID == models.UserGroupAclID {				err := IsGroupValid(models.UserGroupID(srcI.Value))				if err != nil {					return false				}				// check if group belongs to this network				netGrps := GetUserGroupsInNetwork(acl.NetworkID)				if _, ok := netGrps[models.UserGroupID(srcI.Value)]; !ok {					return false				}			}		}		for _, dstI := range acl.Dst {			if dstI.ID == "" || dstI.Value == "" {				return false			}			if dstI.ID != models.DeviceAclID {				return false			}			if dstI.Value == "*" {				continue			}			// check if tag is valid			_, err := GetTag(models.TagID(dstI.Value))			if err != nil {				return false			}		}	case models.DevicePolicy:		for _, srcI := range acl.Src {			if srcI.ID == "" || srcI.Value == "" {				return false			}			if srcI.ID != models.DeviceAclID {				return false			}			if srcI.Value == "*" {				continue			}			// check if tag is valid			_, err := GetTag(models.TagID(srcI.Value))			if err != nil {				return false			}		}		for _, dstI := range acl.Dst {			if dstI.ID == "" || dstI.Value == "" {				return false			}			if dstI.ID != models.DeviceAclID {				return false			}			if dstI.Value == "*" {				continue			}			// check if tag is valid			_, err := GetTag(models.TagID(dstI.Value))			if err != nil {				return false			}		}	}	return true}// UpdateAcl - updates allowed fields on acls and commits to DBfunc UpdateAcl(newAcl, acl models.Acl) error {	if !acl.Default {		acl.Name = newAcl.Name		acl.Src = newAcl.Src		acl.Dst = newAcl.Dst		acl.AllowedDirection = newAcl.AllowedDirection		acl.Port = newAcl.Port		acl.Proto = newAcl.Proto		acl.ServiceType = newAcl.ServiceType	}	if newAcl.ServiceType == models.Any {		acl.Port = []string{}		acl.Proto = models.ALL	}	acl.Enabled = newAcl.Enabled	d, err := json.Marshal(acl)	if err != nil {		return err	}	err = database.Insert(acl.ID, string(d), database.ACLS_TABLE_NAME)	if err == nil && servercfg.CacheEnabled() {		storeAclInCache(acl)	}	return err}// UpsertAcl - upserts aclfunc UpsertAcl(acl models.Acl) error {	d, err := json.Marshal(acl)	if err != nil {		return err	}	err = database.Insert(acl.ID, string(d), database.ACLS_TABLE_NAME)	if err == nil && servercfg.CacheEnabled() {		storeAclInCache(acl)	}	return err}// DeleteAcl - deletes acl policyfunc DeleteAcl(a models.Acl) error {	err := database.DeleteRecord(database.ACLS_TABLE_NAME, a.ID)	if err == nil && servercfg.CacheEnabled() {		removeAclFromCache(a)	}	return err}// GetDefaultPolicy - fetches default policy in the network by ruleTypefunc GetDefaultPolicy(netID models.NetworkID, ruleType models.AclPolicyType) (models.Acl, error) {	aclID := "all-users"	if ruleType == models.DevicePolicy {		aclID = "all-nodes"	}	acl, err := GetAcl(fmt.Sprintf("%s.%s", netID, aclID))	if err != nil {		return models.Acl{}, errors.New("default rule not found")	}	if acl.Enabled {		return acl, nil	}	// check if there are any custom all policies	srcMap := make(map[string]struct{})	dstMap := make(map[string]struct{})	defer func() {		srcMap = nil		dstMap = nil	}()	policies, _ := ListAclsByNetwork(netID)	for _, policy := range policies {		if !policy.Enabled {			continue		}		if policy.RuleType == ruleType {			dstMap = convAclTagToValueMap(policy.Dst)			srcMap = convAclTagToValueMap(policy.Src)			if _, ok := srcMap["*"]; ok {				if _, ok := dstMap["*"]; ok {					return policy, nil				}			}		}	}	return acl, nil}func ListAcls() (acls []models.Acl) {	if servercfg.CacheEnabled() && len(aclCacheMap) > 0 {		return listAclFromCache()	}	data, err := database.FetchRecords(database.ACLS_TABLE_NAME)	if err != nil && !database.IsEmptyRecord(err) {		return []models.Acl{}	}	for _, dataI := range data {		acl := models.Acl{}		err := json.Unmarshal([]byte(dataI), &acl)		if err != nil {			continue		}		acls = append(acls, acl)		if servercfg.CacheEnabled() {			storeAclInCache(acl)		}	}	return}// ListUserPolicies - lists all acl policies enforced on an userfunc ListUserPolicies(u models.User) []models.Acl {	allAcls := ListAcls()	userAcls := []models.Acl{}	for _, acl := range allAcls {		if acl.RuleType == models.UserPolicy {			srcMap := convAclTagToValueMap(acl.Src)			if _, ok := srcMap[u.UserName]; ok {				userAcls = append(userAcls, acl)			} else {				// check for user groups				for gID := range u.UserGroups {					if _, ok := srcMap[gID.String()]; ok {						userAcls = append(userAcls, acl)						break					}				}			}		}	}	return userAcls}// listPoliciesOfUser - lists all user acl policies applied to user in an networkfunc listPoliciesOfUser(user models.User, netID models.NetworkID) []models.Acl {	allAcls := ListAcls()	userAcls := []models.Acl{}	for _, acl := range allAcls {		if acl.NetworkID == netID && acl.RuleType == models.UserPolicy {			srcMap := convAclTagToValueMap(acl.Src)			if _, ok := srcMap[user.UserName]; ok {				userAcls = append(userAcls, acl)				continue			}			for netRole := range user.NetworkRoles {				if _, ok := srcMap[netRole.String()]; ok {					userAcls = append(userAcls, acl)					continue				}			}			for userG := range user.UserGroups {				if _, ok := srcMap[userG.String()]; ok {					userAcls = append(userAcls, acl)					continue				}			}		}	}	return userAcls}// listDevicePolicies - lists all device policies in a networkfunc listDevicePolicies(netID models.NetworkID) []models.Acl {	allAcls := ListAcls()	deviceAcls := []models.Acl{}	for _, acl := range allAcls {		if acl.NetworkID == netID && acl.RuleType == models.DevicePolicy {			deviceAcls = append(deviceAcls, acl)		}	}	return deviceAcls}// listUserPolicies - lists all user policies in a networkfunc listUserPolicies(netID models.NetworkID) []models.Acl {	allAcls := ListAcls()	deviceAcls := []models.Acl{}	for _, acl := range allAcls {		if acl.NetworkID == netID && acl.RuleType == models.UserPolicy {			deviceAcls = append(deviceAcls, acl)		}	}	return deviceAcls}// ListAcls - lists all acl policiesfunc ListAclsByNetwork(netID models.NetworkID) ([]models.Acl, error) {	allAcls := ListAcls()	netAcls := []models.Acl{}	for _, acl := range allAcls {		if acl.NetworkID == netID {			netAcls = append(netAcls, acl)		}	}	return netAcls, nil}func convAclTagToValueMap(acltags []models.AclPolicyTag) map[string]struct{} {	aclValueMap := make(map[string]struct{})	for _, aclTagI := range acltags {		aclValueMap[aclTagI.Value] = struct{}{}	}	return aclValueMap}// IsUserAllowedToCommunicate - check if user is allowed to communicate with peerfunc IsUserAllowedToCommunicate(userName string, peer models.Node) (bool, []models.Acl) {	if peer.IsStatic {		peer = peer.StaticNode.ConvertToStaticNode()	}	acl, _ := GetDefaultPolicy(models.NetworkID(peer.Network), models.UserPolicy)	if acl.Enabled {		return true, []models.Acl{acl}	}	user, err := GetUser(userName)	if err != nil {		return false, []models.Acl{}	}	allowedPolicies := []models.Acl{}	policies := listPoliciesOfUser(*user, models.NetworkID(peer.Network))	for _, policy := range policies {		if !policy.Enabled {			continue		}		dstMap := convAclTagToValueMap(policy.Dst)		if _, ok := dstMap["*"]; ok {			allowedPolicies = append(allowedPolicies, policy)			continue		}		for tagID := range peer.Tags {			if _, ok := dstMap[tagID.String()]; ok {				allowedPolicies = append(allowedPolicies, policy)				break			}		}	}	if len(allowedPolicies) > 0 {		return true, allowedPolicies	}	return false, []models.Acl{}}// IsPeerAllowed - checks if peer needs to be added to the interfacefunc IsPeerAllowed(node, peer models.Node, checkDefaultPolicy bool) bool {	if node.IsStatic {		node = node.StaticNode.ConvertToStaticNode()	}	if peer.IsStatic {		peer = peer.StaticNode.ConvertToStaticNode()	}	if checkDefaultPolicy {		// check default policy if all allowed return true		defaultPolicy, err := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)		if err == nil {			if defaultPolicy.Enabled {				return true			}		}	}	// list device policies	policies := listDevicePolicies(models.NetworkID(peer.Network))	srcMap := make(map[string]struct{})	dstMap := make(map[string]struct{})	defer func() {		srcMap = nil		dstMap = nil	}()	for _, policy := range policies {		if !policy.Enabled {			continue		}		srcMap = convAclTagToValueMap(policy.Src)		dstMap = convAclTagToValueMap(policy.Dst)		for tagID := range node.Tags {			if _, ok := dstMap[tagID.String()]; ok {				if _, ok := srcMap["*"]; ok {					return true				}				for tagID := range peer.Tags {					if _, ok := srcMap[tagID.String()]; ok {						return true					}				}			}			if _, ok := srcMap[tagID.String()]; ok {				if _, ok := dstMap["*"]; ok {					return true				}				for tagID := range peer.Tags {					if _, ok := dstMap[tagID.String()]; ok {						return true					}				}			}		}		for tagID := range peer.Tags {			if _, ok := dstMap[tagID.String()]; ok {				if _, ok := srcMap["*"]; ok {					return true				}				for tagID := range node.Tags {					if _, ok := srcMap[tagID.String()]; ok {						return true					}				}			}			if _, ok := srcMap[tagID.String()]; ok {				if _, ok := dstMap["*"]; ok {					return true				}				for tagID := range node.Tags {					if _, ok := dstMap[tagID.String()]; ok {						return true					}				}			}		}	}	return false}// IsNodeAllowedToCommunicate - check node is allowed to communicate with the peerfunc IsNodeAllowedToCommunicate(node, peer models.Node, checkDefaultPolicy bool) (bool, []models.Acl) {	if node.IsStatic {		node = node.StaticNode.ConvertToStaticNode()	}	if peer.IsStatic {		peer = peer.StaticNode.ConvertToStaticNode()	}	if checkDefaultPolicy {		// check default policy if all allowed return true		defaultPolicy, err := GetDefaultPolicy(models.NetworkID(node.Network), models.DevicePolicy)		if err == nil {			if defaultPolicy.Enabled {				return true, []models.Acl{defaultPolicy}			}		}	}	allowedPolicies := []models.Acl{}	// list device policies	policies := listDevicePolicies(models.NetworkID(peer.Network))	srcMap := make(map[string]struct{})	dstMap := make(map[string]struct{})	defer func() {		srcMap = nil		dstMap = nil	}()	for _, policy := range policies {		if !policy.Enabled {			continue		}		srcMap = convAclTagToValueMap(policy.Src)		dstMap = convAclTagToValueMap(policy.Dst)		for tagID := range node.Tags {			allowed := false			if _, ok := dstMap[tagID.String()]; policy.AllowedDirection == models.TrafficDirectionBi && ok {				if _, ok := srcMap["*"]; ok {					allowed = true					allowedPolicies = append(allowedPolicies, policy)					break				}				for tagID := range peer.Tags {					if _, ok := srcMap[tagID.String()]; ok {						allowed = true						break					}				}			}			if allowed {				allowedPolicies = append(allowedPolicies, policy)				break			}			if _, ok := srcMap[tagID.String()]; ok {				if _, ok := dstMap["*"]; ok {					allowed = true					allowedPolicies = append(allowedPolicies, policy)					break				}				for tagID := range peer.Tags {					if _, ok := dstMap[tagID.String()]; ok {						allowed = true						break					}				}			}			if allowed {				allowedPolicies = append(allowedPolicies, policy)				break			}		}		for tagID := range peer.Tags {			allowed := false			if _, ok := dstMap[tagID.String()]; ok {				if _, ok := srcMap["*"]; ok {					allowed = true					allowedPolicies = append(allowedPolicies, policy)					break				}				for tagID := range node.Tags {					if _, ok := srcMap[tagID.String()]; ok {						allowed = true						break					}				}			}			if allowed {				allowedPolicies = append(allowedPolicies, policy)				break			}			if _, ok := srcMap[tagID.String()]; policy.AllowedDirection == models.TrafficDirectionBi && ok {				if _, ok := dstMap["*"]; ok {					allowed = true					allowedPolicies = append(allowedPolicies, policy)					break				}				for tagID := range node.Tags {					if _, ok := dstMap[tagID.String()]; ok {						allowed = true						break					}				}			}			if allowed {				allowedPolicies = append(allowedPolicies, policy)				break			}		}	}	if len(allowedPolicies) > 0 {		return true, allowedPolicies	}	return false, allowedPolicies}// SortTagEntrys - Sorts slice of Tag entries by their idfunc SortAclEntrys(acls []models.Acl) {	sort.Slice(acls, func(i, j int) bool {		return acls[i].Name < acls[j].Name	})}// UpdateDeviceTag - updates device tag on acl policiesfunc UpdateDeviceTag(OldID, newID models.TagID, netID models.NetworkID) {	acls := listDevicePolicies(netID)	update := false	for _, acl := range acls {		for i, srcTagI := range acl.Src {			if srcTagI.ID == models.DeviceAclID {				if OldID.String() == srcTagI.Value {					acl.Src[i].Value = newID.String()					update = true				}			}		}		for i, dstTagI := range acl.Dst {			if dstTagI.ID == models.DeviceAclID {				if OldID.String() == dstTagI.Value {					acl.Dst[i].Value = newID.String()					update = true				}			}		}		if update {			UpsertAcl(acl)		}	}}func CheckIfTagAsActivePolicy(tagID models.TagID, netID models.NetworkID) bool {	acls := listDevicePolicies(netID)	for _, acl := range acls {		for _, srcTagI := range acl.Src {			if srcTagI.ID == models.DeviceAclID {				if tagID.String() == srcTagI.Value {					return true				}			}		}		for _, dstTagI := range acl.Dst {			if dstTagI.ID == models.DeviceAclID {				if tagID.String() == dstTagI.Value {					return true				}			}		}	}	return false}// RemoveDeviceTagFromAclPolicies - remove device tag from acl policiesfunc RemoveDeviceTagFromAclPolicies(tagID models.TagID, netID models.NetworkID) error {	acls := listDevicePolicies(netID)	update := false	for _, acl := range acls {		for i, srcTagI := range acl.Src {			if srcTagI.ID == models.DeviceAclID {				if tagID.String() == srcTagI.Value {					acl.Src = append(acl.Src[:i], acl.Src[i+1:]...)					update = true				}			}		}		for i, dstTagI := range acl.Dst {			if dstTagI.ID == models.DeviceAclID {				if tagID.String() == dstTagI.Value {					acl.Dst = append(acl.Dst[:i], acl.Dst[i+1:]...)					update = true				}			}		}		if update {			UpsertAcl(acl)		}	}	return nil}func getUserAclRulesForNode(targetnode *models.Node,	rules map[string]models.AclRule) map[string]models.AclRule {	userNodes := GetStaticUserNodesByNetwork(models.NetworkID(targetnode.Network))	userGrpMap := GetUserGrpMap()	allowedUsers := make(map[string][]models.Acl)	acls := listUserPolicies(models.NetworkID(targetnode.Network))	for nodeTag := range targetnode.Tags {		for _, acl := range acls {			if !acl.Enabled {				continue			}			dstTags := convAclTagToValueMap(acl.Dst)			if _, ok := dstTags[nodeTag.String()]; ok {				// get all src tags				for _, srcAcl := range acl.Src {					if srcAcl.ID == models.UserAclID {						allowedUsers[srcAcl.Value] = append(allowedUsers[srcAcl.Value], acl)					} else if srcAcl.ID == models.UserGroupAclID {						// fetch all users in the group						if usersMap, ok := userGrpMap[models.UserGroupID(srcAcl.Value)]; ok {							for userName := range usersMap {								allowedUsers[userName] = append(allowedUsers[userName], acl)							}						}					}				}			}		}	}	for _, userNode := range userNodes {		if !userNode.StaticNode.Enabled {			continue		}		acls, ok := allowedUsers[userNode.StaticNode.OwnerID]		if !ok {			continue		}		for _, acl := range acls {			if !acl.Enabled {				continue			}			r := models.AclRule{				ID:              acl.ID,				AllowedProtocol: acl.Proto,				AllowedPorts:    acl.Port,				Direction:       acl.AllowedDirection,				Allowed:         true,			}			// Get peers in the tags and add allowed rules			if userNode.StaticNode.Address != "" {				r.IPList = append(r.IPList, userNode.StaticNode.AddressIPNet4())			}			if userNode.StaticNode.Address6 != "" {				r.IP6List = append(r.IP6List, userNode.StaticNode.AddressIPNet6())			}			if aclRule, ok := rules[acl.ID]; ok {				aclRule.IPList = append(aclRule.IPList, r.IPList...)				aclRule.IP6List = append(aclRule.IP6List, r.IP6List...)				rules[acl.ID] = aclRule			} else {				rules[acl.ID] = r			}		}	}	return rules}func GetAclRulesForNode(targetnode *models.Node) (rules map[string]models.AclRule) {	defer func() {		if !targetnode.IsIngressGateway {			rules = getUserAclRulesForNode(targetnode, rules)		}	}()	rules = make(map[string]models.AclRule)	var taggedNodes map[models.TagID][]models.Node	if targetnode.IsIngressGateway {		taggedNodes = GetTagMapWithNodesByNetwork(models.NetworkID(targetnode.Network), false)	} else {		taggedNodes = GetTagMapWithNodesByNetwork(models.NetworkID(targetnode.Network), true)	}	acls := listDevicePolicies(models.NetworkID(targetnode.Network))	targetnode.Tags["*"] = struct{}{}	for nodeTag := range targetnode.Tags {		for _, acl := range acls {			if !acl.Enabled {				continue			}			srcTags := convAclTagToValueMap(acl.Src)			dstTags := convAclTagToValueMap(acl.Dst)			aclRule := models.AclRule{				ID:              acl.ID,				AllowedProtocol: acl.Proto,				AllowedPorts:    acl.Port,				Direction:       acl.AllowedDirection,				Allowed:         true,			}			if acl.AllowedDirection == models.TrafficDirectionBi {				var existsInSrcTag bool				var existsInDstTag bool				if _, ok := srcTags[nodeTag.String()]; ok {					existsInSrcTag = true				}				if _, ok := dstTags[nodeTag.String()]; ok {					existsInDstTag = true				}				if existsInSrcTag && !existsInDstTag {					// get all dst tags					for dst := range dstTags {						if dst == nodeTag.String() {							continue						}						// Get peers in the tags and add allowed rules						nodes := taggedNodes[models.TagID(dst)]						for _, node := range nodes {							if node.ID == targetnode.ID {								continue							}							if node.Address.IP != nil {								aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())							}							if node.Address6.IP != nil {								aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())							}							if node.IsStatic && node.StaticNode.Address != "" {								aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())							}							if node.IsStatic && node.StaticNode.Address6 != "" {								aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())							}						}					}				}				if existsInDstTag && !existsInSrcTag {					// get all src tags					for src := range srcTags {						if src == nodeTag.String() {							continue						}						// Get peers in the tags and add allowed rules						nodes := taggedNodes[models.TagID(src)]						for _, node := range nodes {							if node.ID == targetnode.ID {								continue							}							if node.Address.IP != nil {								aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())							}							if node.Address6.IP != nil {								aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())							}							if node.IsStatic && node.StaticNode.Address != "" {								aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())							}							if node.IsStatic && node.StaticNode.Address6 != "" {								aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())							}						}					}				}				if existsInDstTag && existsInSrcTag {					nodes := taggedNodes[nodeTag]					for _, node := range nodes {						if node.ID == targetnode.ID {							continue						}						if node.Address.IP != nil {							aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())						}						if node.Address6.IP != nil {							aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())						}						if node.IsStatic && node.StaticNode.Address != "" {							aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())						}						if node.IsStatic && node.StaticNode.Address6 != "" {							aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())						}					}				}			} else {				_, all := dstTags["*"]				if _, ok := dstTags[nodeTag.String()]; ok || all {					// get all src tags					for src := range srcTags {						if src == nodeTag.String() {							continue						}						// Get peers in the tags and add allowed rules						nodes := taggedNodes[models.TagID(src)]						for _, node := range nodes {							if node.ID == targetnode.ID {								continue							}							if node.Address.IP != nil {								aclRule.IPList = append(aclRule.IPList, node.AddressIPNet4())							}							if node.Address6.IP != nil {								aclRule.IP6List = append(aclRule.IP6List, node.AddressIPNet6())							}							if node.IsStatic && node.StaticNode.Address != "" {								aclRule.IPList = append(aclRule.IPList, node.StaticNode.AddressIPNet4())							}							if node.IsStatic && node.StaticNode.Address6 != "" {								aclRule.IP6List = append(aclRule.IP6List, node.StaticNode.AddressIPNet6())							}						}					}				}			}			if len(aclRule.IPList) > 0 || len(aclRule.IP6List) > 0 {				rules[acl.ID] = aclRule			}		}	}	return rules}
 |