| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610 | package logicimport (	"encoding/json"	"errors"	"fmt"	"sort"	"time"	"github.com/gravitl/netmaker/database"	"github.com/gravitl/netmaker/models")// CreateDefaultAclNetworkPolicies - create default acl network policiesfunc CreateDefaultAclNetworkPolicies(netID models.NetworkID) {	if netID.String() == "" {		return	}	if !IsAclExists(models.AclID(fmt.Sprintf("%s.%s", netID, "all-nodes"))) {		defaultDeviceAcl := models.Acl{			ID:        models.AclID(fmt.Sprintf("%s.%s", netID, "all-nodes")),			Name:      "all-nodes",			Default:   true,			NetworkID: netID,			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(models.AclID(fmt.Sprintf("%s.%s", netID, "all-users"))) {		defaultUserAcl := models.Acl{			ID:        models.AclID(fmt.Sprintf("%s.%s", netID, "all-users")),			Default:   true,			Name:      "all-users",			NetworkID: netID,			RuleType:  models.UserPolicy,			Src: []models.AclPolicyTag{				{					ID:    models.UserAclID,					Value: "*",				},				{					ID:    models.UserGroupAclID,					Value: "*",				},				{					ID:    models.UserRoleAclID,					Value: "*",				},			},			Dst: []models.AclPolicyTag{{				ID:    models.DeviceAclID,				Value: "*",			}},			AllowedDirection: models.TrafficDirectionUni,			Enabled:          true,			CreatedBy:        "auto",			CreatedAt:        time.Now().UTC(),		}		InsertAcl(defaultUserAcl)	}	if !IsAclExists(models.AclID(fmt.Sprintf("%s.%s", netID, "all-remote-access-gws"))) {		defaultUserAcl := models.Acl{			ID:        models.AclID(fmt.Sprintf("%s.%s", netID, "all-remote-access-gws")),			Default:   true,			Name:      "all-remote-access-gws",			NetworkID: netID,			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, _ := ListAcls(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	}	req.GetID(req.NetworkID, req.Name)	_, err = GetAcl(req.ID)	if err == nil {		return errors.New("acl exists already with name " + req.Name)	}	return nil}// InsertAcl - creates acl policyfunc InsertAcl(a models.Acl) error {	d, err := json.Marshal(a)	if err != nil {		return err	}	return database.Insert(a.ID.String(), string(d), database.ACLS_TABLE_NAME)}// GetAcl - gets acl info by idfunc GetAcl(aID models.AclID) (models.Acl, error) {	a := models.Acl{}	d, err := database.FetchRecord(database.ACLS_TABLE_NAME, aID.String())	if err != nil {		return a, err	}	err = json.Unmarshal([]byte(d), &a)	if err != nil {		return a, err	}	return a, nil}// IsAclExists - checks if acl existsfunc IsAclExists(aclID models.AclID) 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	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 && srcI.ID != models.UserRoleAclID {				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.UserRoleAclID {				_, err := GetRole(models.UserRoleID(srcI.Value))				if err != nil {					return false				}			} else if srcI.ID == models.UserGroupAclID {				err := IsGroupValid(models.UserGroupID(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			}		}	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.Enabled = newAcl.Enabled	if acl.ID != newAcl.ID {		database.DeleteRecord(database.ACLS_TABLE_NAME, acl.ID.String())		acl.ID = newAcl.ID	}	d, err := json.Marshal(acl)	if err != nil {		return err	}	return database.Insert(acl.ID.String(), string(d), database.ACLS_TABLE_NAME)}// UpsertAcl - upserts aclfunc UpsertAcl(acl models.Acl) error {	d, err := json.Marshal(acl)	if err != nil {		return err	}	return database.Insert(acl.ID.String(), string(d), database.ACLS_TABLE_NAME)}// DeleteAcl - deletes acl policyfunc DeleteAcl(a models.Acl) error {	return database.DeleteRecord(database.ACLS_TABLE_NAME, a.ID.String())}// 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(models.AclID(fmt.Sprintf("%s.%s", netID, aclID)))	if err != nil {		return models.Acl{}, errors.New("default rule not found")	}	return acl, nil}// ListUserPolicies - lists all acl policies enforced on an userfunc ListUserPolicies(u models.User) []models.Acl {	data, err := database.FetchRecords(database.ACLS_TABLE_NAME)	if err != nil && !database.IsEmptyRecord(err) {		return []models.Acl{}	}	acls := []models.Acl{}	for _, dataI := range data {		acl := models.Acl{}		err := json.Unmarshal([]byte(dataI), &acl)		if err != nil {			continue		}		if acl.RuleType == models.UserPolicy {			srcMap := convAclTagToValueMap(acl.Src)			if _, ok := srcMap[u.UserName]; ok {				acls = append(acls, acl)			} else {				// check for user groups				for gID := range u.UserGroups {					if _, ok := srcMap[gID.String()]; ok {						acls = append(acls, acl)						break					}				}			}		}	}	return acls}// listPoliciesOfUser - lists all user acl policies applied to user in an networkfunc listPoliciesOfUser(user models.User, netID models.NetworkID) []models.Acl {	data, err := database.FetchRecords(database.ACLS_TABLE_NAME)	if err != nil && !database.IsEmptyRecord(err) {		return []models.Acl{}	}	acls := []models.Acl{}	for _, dataI := range data {		acl := models.Acl{}		err := json.Unmarshal([]byte(dataI), &acl)		if err != nil {			continue		}		if acl.NetworkID == netID && acl.RuleType == models.UserPolicy {			srcMap := convAclTagToValueMap(acl.Src)			if _, ok := srcMap[user.UserName]; ok {				acls = append(acls, acl)				continue			}			for netRole := range user.NetworkRoles {				if _, ok := srcMap[netRole.String()]; ok {					acls = append(acls, acl)					continue				}			}			for userG := range user.UserGroups {				if _, ok := srcMap[userG.String()]; ok {					acls = append(acls, acl)					continue				}			}		}	}	return acls}// listUserPoliciesByNetwork - lists all acl user policies in a networkfunc listUserPoliciesByNetwork(netID models.NetworkID) []models.Acl {	data, err := database.FetchRecords(database.ACLS_TABLE_NAME)	if err != nil && !database.IsEmptyRecord(err) {		return []models.Acl{}	}	acls := []models.Acl{}	for _, dataI := range data {		acl := models.Acl{}		err := json.Unmarshal([]byte(dataI), &acl)		if err != nil {			continue		}		if acl.NetworkID == netID && acl.RuleType == models.UserPolicy {			acls = append(acls, acl)		}	}	return acls}// listDevicePolicies - lists all device policies in a networkfunc listDevicePolicies(netID models.NetworkID) []models.Acl {	data, err := database.FetchRecords(database.ACLS_TABLE_NAME)	if err != nil && !database.IsEmptyRecord(err) {		return []models.Acl{}	}	acls := []models.Acl{}	for _, dataI := range data {		acl := models.Acl{}		err := json.Unmarshal([]byte(dataI), &acl)		if err != nil {			continue		}		if acl.NetworkID == netID && acl.RuleType == models.DevicePolicy {			acls = append(acls, acl)		}	}	return acls}// ListAcls - lists all acl policiesfunc ListAcls(netID models.NetworkID) ([]models.Acl, error) {	data, err := database.FetchRecords(database.ACLS_TABLE_NAME)	if err != nil && !database.IsEmptyRecord(err) {		return []models.Acl{}, err	}	acls := []models.Acl{}	for _, dataI := range data {		acl := models.Acl{}		err := json.Unmarshal([]byte(dataI), &acl)		if err != nil {			continue		}		if acl.NetworkID == netID {			acls = append(acls, acl)		}	}	return acls, 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 {	acl, _ := GetDefaultPolicy(models.NetworkID(peer.Network), models.UserPolicy)	if acl.Enabled {		return true	}	user, err := GetUser(userName)	if err != nil {		return false	}	if peer.IsStatic {		peer = peer.StaticNode.ConvertToStaticNode()	}	policies := listPoliciesOfUser(*user, models.NetworkID(peer.Network))	for _, policy := range policies {		if !policy.Enabled {			continue		}		dstMap := convAclTagToValueMap(policy.Dst)		if _, ok := dstMap["*"]; ok {			return true		}		for tagID := range peer.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) bool {	// 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		}	}	if node.IsStatic {		node = node.StaticNode.ConvertToStaticNode()	}	if peer.IsStatic {		peer = peer.StaticNode.ConvertToStaticNode()	}	// list device policies	policies := listDevicePolicies(models.NetworkID(peer.Network))	for _, policy := range policies {		if !policy.Enabled {			continue		}		srcMap := convAclTagToValueMap(policy.Src)		dstMap := convAclTagToValueMap(policy.Dst)		fmt.Printf("\n======> SRCMAP: %+v\n", srcMap)		fmt.Printf("\n======> DSTMAP: %+v\n", dstMap)		fmt.Printf("\n======> node Tags: %+v\n", node.Tags)		fmt.Printf("\n======> peer Tags: %+v\n", peer.Tags)		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}// 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)		}	}}// 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}
 |