logic

package
v0.30.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 17, 2024 License: Apache-2.0 Imports: 45 Imported by: 4

Documentation

Overview

package for logicing client and server code

Index

Constants

View Source
const (
	// RELAY_NODE_ERR - error to return if relay node is unfound
	RELAY_NODE_ERR = "could not find relay for node"
	// NodePurgeTime time to wait for node to response to a NODE_DELETE actions
	NodePurgeTime = time.Second * 10
	// NodePurgeCheckTime is how often to check nodes for Pending Delete
	NodePurgeCheckTime = time.Second * 30
)
View Source
const (
	MasterUser       = "masteradministrator"
	Forbidden_Msg    = "forbidden"
	Forbidden_Err    = models.Error(Forbidden_Msg)
	Unauthorized_Msg = "unauthorized"
	Unauthorized_Err = models.Error(Unauthorized_Msg)
)
View Source
const (
	// ZOMBIE_TIMEOUT - timeout in hours for checking zombie status
	ZOMBIE_TIMEOUT = 6
	// ZOMBIE_DELETE_TIME - timeout in minutes for zombie node deletion
	ZOMBIE_DELETE_TIME = 10
)
View Source
const KUBERNETES_LISTEN_PORT = 31821

KUBERNETES_LISTEN_PORT - starting port for Kubernetes in order to use NodePort range

View Source
const KUBERNETES_SERVER_MTU = 1024

KUBERNETES_SERVER_MTU - ideal mtu for kubernetes deployments right now

View Source
const MinVersion = "v0.17.0"

Variables

View Source
var (
	// DenyClientNodeAccess - function to handle adding a node to an ext client's denied node set
	DenyClientNodeAccess = func(ec *models.ExtClient, clientOrNodeID string) bool {
		return true
	}
	// IsClientNodeAllowed - function to check if an ext client's denied node set contains a node ID
	IsClientNodeAllowed = func(ec *models.ExtClient, clientOrNodeID string) bool {
		return true
	}
	// AllowClientNodeAccess - function to handle removing a node ID from ext client's denied nodes, thus allowing it
	AllowClientNodeAccess = func(ec *models.ExtClient, clientOrNodeID string) bool {
		return true
	}
	SetClientDefaultACLs = func(ec *models.ExtClient) error {

		networkAcls := acls.ACLContainer{}
		networkAcls, err := networkAcls.Get(acls.ContainerID(ec.Network))
		if err != nil {
			slog.Error("failed to get network acls", "error", err)
			return err
		}
		networkAcls[acls.AclID(ec.ClientID)] = make(acls.ACL)
		for objId := range networkAcls {
			networkAcls[objId][acls.AclID(ec.ClientID)] = acls.Allowed
			networkAcls[acls.AclID(ec.ClientID)][objId] = acls.Allowed
		}
		delete(networkAcls[acls.AclID(ec.ClientID)], acls.AclID(ec.ClientID))
		if _, err = networkAcls.Save(acls.ContainerID(ec.Network)); err != nil {
			slog.Error("failed to update network acls", "error", err)
			return err
		}
		return nil
	}
	SetClientACLs = func(ec *models.ExtClient, newACLs map[string]struct{}) {
	}
	UpdateProNodeACLs = func(node *models.Node) error {
		return nil
	}
)
View Source
var (
	// ErrHostExists error indicating that host exists when trying to create new host
	ErrHostExists error = errors.New("host already exists")
	// ErrInvalidHostID
	ErrInvalidHostID error = errors.New("invalid host id")
)
View Source
var (
	// ResetFailOver - function to reset failOvered peers on this node
	ResetFailOver = func(failOverNode *models.Node) error {
		return nil
	}
	// ResetFailedOverPeer - removes failed over node from network peers
	ResetFailedOverPeer = func(failedOverNode *models.Node) error {
		return nil
	}
	// FailOverExists - check if failover node existed or not
	FailOverExists = func(network string) (failOverNode models.Node, exists bool) {
		return failOverNode, exists
	}
	// GetFailOverPeerIps - gets failover peerips
	GetFailOverPeerIps = func(peer, node *models.Node) []net.IPNet {
		return []net.IPNet{}
	}
	// CreateFailOver - creates failover in a network
	CreateFailOver = func(node models.Node) error {
		return nil
	}

	// SetDefaulGw
	SetDefaultGw = func(node models.Node, peerUpdate models.HostPeerUpdate) models.HostPeerUpdate {
		return peerUpdate
	}
	SetDefaultGwForRelayedUpdate = func(relayed, relay models.Node, peerUpdate models.HostPeerUpdate) models.HostPeerUpdate {
		return peerUpdate
	}
	// UnsetInternetGw
	UnsetInternetGw = func(node *models.Node) {
		node.IsInternetGateway = false
	}
	// SetInternetGw
	SetInternetGw = func(node *models.Node, req models.InetNodeReq) {
		node.IsInternetGateway = true
	}
	// GetAllowedIpForInetNodeClient
	GetAllowedIpForInetNodeClient = func(node, peer *models.Node) []net.IPNet {
		return []net.IPNet{}
	}
)
View Source
var (
	// NetworksLimit - dummy var for community
	NetworksLimit = 1000000000
	// UsersLimit - dummy var for community
	UsersLimit = 1000000000
	// MachinesLimit - dummy var for community
	MachinesLimit = 1000000000
	// IngressesLimit - dummy var for community
	IngressesLimit = 1000000000
	// EgressesLimit - dummy var for community
	EgressesLimit = 1000000000
	// FreeTier - specifies if free tier
	FreeTier = false
	// DefaultTrialEndDate - is a placeholder date for not applicable trial end dates
	DefaultTrialEndDate, _ = time.Parse("2006-Jan-02", "2021-Apr-01")

	GetTrialEndDate = func() (time.Time, error) {
		return DefaultTrialEndDate, nil
	}
)
View Source
var AddGlobalNetRolesToAdmins = func(u models.User) {}
View Source
var AdminPermissionTemplate = models.UserRolePermissionTemplate{
	ID:         models.AdminRole,
	Default:    true,
	FullAccess: true,
}
View Source
var CreateDefaultNetworkRolesAndGroups = func(netID models.NetworkID) {}
View Source
var CreateDefaultUserPolicies = func(netID models.NetworkID) {}
View Source
var CreateRole = func(r models.UserRolePermissionTemplate) error {
	return nil
}
View Source
var DeleteMetrics = func(string) error {
	return nil
}
View Source
var DeleteNetworkRoles = func(netID string) {}
View Source
var DeleteRole = func(r models.UserRoleID, force bool) error {
	return nil
}
View Source
var EnrollmentErrors = struct {
	InvalidCreate      error
	NoKeyFound         error
	InvalidKey         error
	NoUsesRemaining    error
	FailedToTokenize   error
	FailedToDeTokenize error
}{
	InvalidCreate:      fmt.Errorf("failed to create enrollment key. paramters invalid"),
	NoKeyFound:         fmt.Errorf("no enrollmentkey found"),
	InvalidKey:         fmt.Errorf("invalid key provided"),
	NoUsesRemaining:    fmt.Errorf("no uses remaining"),
	FailedToTokenize:   fmt.Errorf("failed to tokenize"),
	FailedToDeTokenize: fmt.Errorf("failed to detokenize"),
}

EnrollmentErrors - struct for holding EnrollmentKey error messages

View Source
var EnterpriseCheckFuncs []func()

EnterpriseCheckFuncs - can be set to run functions for EE

View Source
var FilterNetworksByRole = func(allnetworks []models.Network, user models.User) []models.Network {
	return allnetworks
}
View Source
var GetAllowedIpsForRelayed = func(relayed, relay *models.Node) []net.IPNet {
	return []net.IPNet{}
}
View Source
var GetFilteredNodesByUserAccess = func(user models.User, nodes []models.Node) (filteredNodes []models.Node) {
	return
}
View Source
var GetMetrics = func(string) (*models.Metrics, error) {
	var metrics models.Metrics
	return &metrics, nil
}
View Source
var GetNodeStatus = getNodeStatus
View Source
var GetRelays = func() ([]models.Node, error) {
	return []models.Node{}, nil
}
View Source
var GetUserGroupsInNetwork = func(netID models.NetworkID) (networkGrps map[models.UserGroupID]models.UserGroup) { return }
View Source
var GlobalPermissionsCheck = func(username string, r *http.Request) error { return nil }
View Source
var HookManagerCh = make(chan models.HookDetails, 3)

HookManagerCh - channel to add any new hooks

View Source
var InitialiseRoles = userRolesInit
View Source
var IntialiseGroups = func() {}
View Source
var IsGroupValid = func(groupID models.UserGroupID) error {
	return nil
}
View Source
var IsGroupsValid = func(groups map[models.UserGroupID]struct{}) error {
	return nil
}
View Source
var IsNetworkRolesValid = func(networkRoles map[models.NetworkID]map[models.UserRoleID]struct{}) error {
	return nil
}
View Source
var MigrateUserRoleAndGroups = func(u models.User) {

}
View Source
var NetworkPermissionsCheck = func(username string, r *http.Request) error { return nil }
View Source
var RelayUpdates = func(currentNode, newNode *models.Node) bool {
	return false
}
View Source
var RelayedAllowedIPs = func(peer, node *models.Node) []net.IPNet {
	return []net.IPNet{}
}
View Source
var SetRelayedNodes = func(setRelayed bool, relay string, relayed []string) []models.Node {
	return []models.Node{}
}
View Source
var SuperAdminPermissionTemplate = models.UserRolePermissionTemplate{
	ID:         models.SuperAdminRole,
	Default:    true,
	FullAccess: true,
}

Pre-Define Permission Templates for default Roles

View Source
var UpdateMetrics = func(string, *models.Metrics) error {
	return nil
}
View Source
var UpdateRelayed = func(currentNode, newNode *models.Node) {
}
View Source
var UpdateRole = func(r models.UserRolePermissionTemplate) error { return nil }
View Source
var UpdateUserGwAccess = func(currentUser, changeUser models.User) {}
View Source
var ValidateRelay = func(relay models.RelayRequest, update bool) error {
	return nil
}

Functions

func AddHook

func AddHook(ifaceToAdd interface{})

AddHook - adds a hook function to run every 24hrs

func AddIpToAllocatedIpMap added in v0.25.0

func AddIpToAllocatedIpMap(networkName string, ip net.IP)

func AddNetworkToAllocatedIpMap added in v0.25.0

func AddNetworkToAllocatedIpMap(networkName string)

AddNetworkToAllocatedIpMap - add network to allocated ip map when network is added

func AddStaticNodesWithTag added in v0.26.0

func AddStaticNodesWithTag(tag models.Tag, nMap map[string]models.Node) map[string]models.Node

func AddStaticNodestoList added in v0.26.0

func AddStaticNodestoList(nodes []models.Node) []models.Node

func AddStatusToNodes added in v0.30.0

func AddStatusToNodes(nodes []models.Node) (nodesWithStatus []models.Node)

func AddTagMapWithStaticNodes added in v0.26.0

func AddTagMapWithStaticNodes(netID models.NetworkID,
	tagNodesMap map[models.TagID][]models.Node) map[models.TagID][]models.Node

func AddTagMapWithStaticNodesWithUsers added in v0.30.0

func AddTagMapWithStaticNodesWithUsers(netID models.NetworkID,
	tagNodesMap map[models.TagID][]models.Node) map[models.TagID][]models.Node

func AssociateNodeToHost

func AssociateNodeToHost(n *models.Node, h *models.Host) error

AssociateNodeToHost - associates and creates a node with a given host should be the only way nodes get created as of 0.18

func CheckAndRemoveLegacyNode

func CheckAndRemoveLegacyNode(nodeID string) bool

CheckAndRemoveLegacyNode - checks for legacy node and removes

func CheckEndpoint

func CheckEndpoint(endpoint string) bool

CheckEndpoint - checks if an endpoint is valid

func CheckHostPorts

func CheckHostPorts(h *models.Host)

CheckHostPort checks host endpoints to ensures that hosts on the same server with the same endpoint have different listen ports in the case of 64535 hosts or more with same endpoint, ports will not be changed

func CheckIDSyntax added in v0.26.0

func CheckIDSyntax(id string) error

func CheckIfFileExists

func CheckIfFileExists(filePath string) bool

CheckIfFileExists - checks if file exists or not in the given path

func CheckIfTagAsActivePolicy added in v0.30.0

func CheckIfTagAsActivePolicy(tagID models.TagID, netID models.NetworkID) bool

func CheckZombies

func CheckZombies(newnode *models.Node)

CheckZombies - checks if new node has same hostid as existing node if so, existing node is added to zombie node quarantine list also cleans up nodes past their expiration date

func ClearAllocatedIpMap added in v0.25.0

func ClearAllocatedIpMap()

ClearAllocatedIpMap - set allocatedIpMap to nil

func ClearNodeCache

func ClearNodeCache()

func ClearSuperUserCache added in v0.25.0

func ClearSuperUserCache()

func ContainsCIDR added in v0.24.3

func ContainsCIDR(net1, net2 string) bool

func ContinueIfUserMatch

func ContinueIfUserMatch(next http.Handler) http.HandlerFunc

func ConvHostPassToHash

func ConvHostPassToHash(hostPass string) string

ConvHostPassToHash - converts password to md5 hash

func CreateDNS

func CreateDNS(entry models.DNSEntry) (models.DNSEntry, error)

CreateDNS - creates a DNS entry

func CreateDefaultAclNetworkPolicies added in v0.26.0

func CreateDefaultAclNetworkPolicies(netID models.NetworkID)

CreateDefaultAclNetworkPolicies - create default acl network policies

func CreateDefaultTags added in v0.26.0

func CreateDefaultTags(netID models.NetworkID)

func CreateEgressGateway

func CreateEgressGateway(gateway models.EgressGatewayRequest) (models.Node, error)

CreateEgressGateway - creates an egress gateway

func CreateEnrollmentKey

func CreateEnrollmentKey(uses int, expiration time.Time, networks, tags []string, groups []models.TagID, unlimited bool, relay uuid.UUID, defaultKey bool) (*models.EnrollmentKey, error)

CreateEnrollmentKey - creates a new enrollment key in db

func CreateExtClient

func CreateExtClient(extclient *models.ExtClient) error

CreateExtClient - creates and saves an extclient

func CreateHost

func CreateHost(h *models.Host) error

CreateHost - creates a host if not exist

func CreateIngressGateway

func CreateIngressGateway(netid string, nodeid string, ingress models.IngressRequest) (models.Node, error)

CreateIngressGateway - creates an ingress gateway

func CreateJWT

func CreateJWT(uuid string, macAddress string, network string) (response string, err error)

CreateJWT func will used to create the JWT while signing in and signing out

func CreateNetwork

func CreateNetwork(network models.Network) (models.Network, error)

CreateNetwork - creates a network in database

func CreateSuperAdmin

func CreateSuperAdmin(u *models.User) error

CreateSuperAdmin - creates an super admin user

func CreateUser

func CreateUser(user *models.User) error

CreateUser - creates a user

func CreateUserJWT

func CreateUserJWT(username string, role models.UserRoleID) (response string, err error)

CreateUserJWT - creates a user jwt token

func DeTokenize

func DeTokenize(b64Token string) (*models.EnrollmentKey, error)

DeTokenize - detokenizes a base64 encoded string and finds the associated enrollment key

func DeleteAcl added in v0.26.0

func DeleteAcl(a models.Acl) error

DeleteAcl - deletes acl policy

func DeleteDNS

func DeleteDNS(domain string, network string) error

DeleteDNS - deletes a DNS entry

func DeleteDefaultNetworkPolicies added in v0.26.0

func DeleteDefaultNetworkPolicies(netId models.NetworkID)

DeleteDefaultNetworkPolicies - deletes all default network acl policies

func DeleteEgressGateway

func DeleteEgressGateway(network, nodeid string) (models.Node, error)

DeleteEgressGateway - deletes egress from node

func DeleteEnrollmentKey

func DeleteEnrollmentKey(value string, force bool) error

DeleteEnrollmentKey - delete's a given enrollment key by value

func DeleteExpiredNodes

func DeleteExpiredNodes(ctx context.Context, peerUpdate chan *models.Node)

DeleteExpiredNodes - goroutine which deletes nodes which are expired

func DeleteExtClient

func DeleteExtClient(network string, clientid string) error

DeleteExtClient - deletes an existing ext client

func DeleteExtClientAndCleanup added in v0.24.1

func DeleteExtClientAndCleanup(extClient models.ExtClient) error

DeleteExtClientAndCleanup - deletes an existing ext client and update ACLs

func DeleteGatewayExtClients

func DeleteGatewayExtClients(gatewayID string, networkName string) error

DeleteGatewayExtClients - deletes ext clients based on gateway (mac) of ingress node and network

func DeleteIngressGateway

func DeleteIngressGateway(nodeid string) (models.Node, []models.ExtClient, error)

DeleteIngressGateway - deletes an ingress gateway

func DeleteNetwork

func DeleteNetwork(network string) error

DeleteNetwork - deletes a network

func DeleteNode

func DeleteNode(node *models.Node, purge bool) error

DeleteNode - marks node for deletion (and adds to zombie list) if called by UI or deletes node if called by node

func DeleteNodeByID added in v0.21.2

func DeleteNodeByID(node *models.Node) error

DeleteNodeByID - deletes a node from database

func DeletePendingUser added in v0.24.0

func DeletePendingUser(username string) error

func DeleteTag added in v0.26.0

func DeleteTag(tagID models.TagID, removeFromPolicy bool) error

DeleteTag - delete tag, will also untag hosts

func DeleteUser

func DeleteUser(user string) (bool, error)

DeleteUser - deletes a given user

func DeleteUserInvite added in v0.25.0

func DeleteUserInvite(email string) error

func DisassociateAllNodesFromHost

func DisassociateAllNodesFromHost(hostID string) error

DisassociateAllNodesFromHost - deletes all nodes of the host

func DissasociateNodeFromHost

func DissasociateNodeFromHost(n *models.Node, h *models.Host) error

DissasociateNodeFromHost - deletes a node and removes from host nodes should be the only way nodes are deleted as of 0.18

func EnterpriseCheck

func EnterpriseCheck()

EnterpriseCheck - Runs enterprise functions if presented

func FetchAuthSecret

func FetchAuthSecret() (string, error)

FetchAuthSecret - manages secrets for oauth

func FetchJWTSecret

func FetchJWTSecret() (string, error)

FetchJWTSecret - fetches jwt secret from db

func FetchPassValue added in v0.25.0

func FetchPassValue(newValue string) (string, error)

func FetchTelemetryData added in v0.23.0

func FetchTelemetryData() telemetryData

FetchTelemetryData - fetches telemetry data: count of various object types in DB

func FetchTelemetryRecord added in v0.23.0

func FetchTelemetryRecord() (models.Telemetry, error)

FetchTelemetryRecord - get the existing UUID and Timestamp from the DB

func FileExists

func FileExists(f string) bool

FileExists - checks if local file exists

func FindRelay

func FindRelay(node *models.Node) *models.Node

FindRelay - returns the node that is the relay for a relayed node

func FormatError

func FormatError(err error, errType string) models.ErrorResponse

FormatError - takes ErrorResponse and uses correct code

func GenerateNodeName added in v0.30.0

func GenerateNodeName(network string) (string, error)

GenerateNodeName - generates a random node name

func GetAcl added in v0.26.0

func GetAcl(aID string) (models.Acl, error)

GetAcl - gets acl info by id

func GetAclRulesForNode added in v0.30.0

func GetAclRulesForNode(targetnode *models.Node) (rules map[string]models.AclRule)

func GetAllDNS

func GetAllDNS() ([]models.DNSEntry, error)

GetAllDNS - gets all dns entries

func GetAllEgresses

func GetAllEgresses() ([]models.Node, error)

GetAllEgresses - gets all the nodes that are egresses

func GetAllEnrollmentKeys

func GetAllEnrollmentKeys() ([]models.EnrollmentKey, error)

GetAllEnrollmentKeys - fetches all enrollment keys from DB TODO drop double pointer

func GetAllExtClients

func GetAllExtClients() ([]models.ExtClient, error)

GetAllExtClients - gets all ext clients from DB

func GetAllFailOvers added in v0.24.0

func GetAllFailOvers() ([]models.Node, error)

GetAllFailOvers - gets all the nodes that are failovers

func GetAllHosts

func GetAllHosts() ([]models.Host, error)

GetAllHosts - returns all hosts in flat list or error

func GetAllHostsAPI

func GetAllHostsAPI(hosts []models.Host) []models.ApiHost

GetAllHostsAPI - get's all the hosts in an API usable format

func GetAllIngresses

func GetAllIngresses() ([]models.Node, error)

GetAllIngresses - gets all the nodes that are ingresses

func GetAllNodes

func GetAllNodes() ([]models.Node, error)

GetAllNodes - returns all nodes in the DB

func GetAllNodesAPI

func GetAllNodesAPI(nodes []models.Node) []models.ApiNode

GetAllNodesAPI - get all nodes for api usage

func GetAllowedIPs

func GetAllowedIPs(node, peer *models.Node, metrics *models.Metrics) []net.IPNet

GetAllowedIPs - calculates the wireguard allowedip field for a peer of a node based on the peer and node settings

func GetCustomDNS

func GetCustomDNS(network string) ([]models.DNSEntry, error)

GetCustomDNS - gets the custom DNS of a network

func GetDNS

func GetDNS(network string) ([]models.DNSEntry, error)

GetDNS - gets the DNS of a current network

func GetDNSEntryNum

func GetDNSEntryNum(domain string, network string) (int, error)

GetDNSEntryNum - gets which entry the dns was

func GetDefaultHosts

func GetDefaultHosts() []models.Host

GetDefaultHosts - retrieve all hosts marked as default from DB

func GetDefaultPolicy added in v0.26.0

func GetDefaultPolicy(netID models.NetworkID, ruleType models.AclPolicyType) (models.Acl, error)

GetDefaultPolicy - fetches default policy in the network by ruleType

func GetDeletedNodeByID

func GetDeletedNodeByID(uuid string) (models.Node, error)

GetDeletedNodeByID - get a deleted node

func GetEgressIPs

func GetEgressIPs(peer *models.Node) []net.IPNet

func GetEgressRangesOnNetwork

func GetEgressRangesOnNetwork(client *models.ExtClient) ([]string, error)

ExtClient.GetEgressRangesOnNetwork - returns the egress ranges on network of ext client

func GetEnrollmentKey

func GetEnrollmentKey(value string) (key models.EnrollmentKey, err error)

GetEnrollmentKey - fetches a single enrollment key returns nil and error if not found

func GetExtClient

func GetExtClient(clientid string, network string) (models.ExtClient, error)

GetExtClient - gets a single ext client on a network

func GetExtClientByName

func GetExtClientByName(ID string) (models.ExtClient, error)

GetExtClientByName - gets an ext client by name

func GetExtClientByPubKey

func GetExtClientByPubKey(publicKey string, network string) (*models.ExtClient, error)

GetExtClient - gets a single ext client on a network

func GetExtClientsByID

func GetExtClientsByID(nodeid, network string) ([]models.ExtClient, error)

GetExtClientsByID - gets the clients of attached gateway

func GetExtPeers added in v0.24.2

func GetExtPeers(node, peer *models.Node) ([]wgtypes.PeerConfig, []models.IDandAddr, []models.EgressNetworkRoutes, error)

func GetExtclientAllowedIPs added in v0.22.0

func GetExtclientAllowedIPs(client models.ExtClient) (allowedIPs []string)

func GetExtclientDNS added in v0.22.0

func GetExtclientDNS() []models.DNSEntry

GetExtclientDNS - gets all extclients dns entries

func GetFwRulesOnIngressGateway added in v0.26.0

func GetFwRulesOnIngressGateway(node models.Node) (rules []models.FwRule)

func GetGwExtclients added in v0.21.2

func GetGwExtclients(nodeID, network string) []models.ExtClient

GetGwExtclients - return all ext clients attached to the passed gw id

func GetHost

func GetHost(hostid string) (*models.Host, error)

GetHost - gets a host from db given id

func GetHostByNodeID

func GetHostByNodeID(id string) *models.Host

GetHostByNodeID - returns a host if found to have a node's ID, else nil

func GetHostByPubKey added in v0.22.0

func GetHostByPubKey(hostPubKey string) (*models.Host, error)

GetHostByPubKey - gets a host from db given pubkey

func GetHostNetworks

func GetHostNetworks(hostID string) []string

GetHostNetworks - fetches all the networks

func GetHostNodes

func GetHostNodes(host *models.Host) []models.Node

GetHostNodes - fetches all nodes part of the host

func GetHostsMap

func GetHostsMap() (map[string]models.Host, error)

GetHostsMap - gets all the current hosts on machine in a map

func GetIngressGwUsers

func GetIngressGwUsers(node models.Node) (models.IngressGwUsers, error)

GetIngressGwUsers - lists the users having to access to ingressGW

func GetInternetGateways

func GetInternetGateways() ([]models.Node, error)

GetInternetGateways - gets all the nodes that are internet gateways

func GetNetwork

func GetNetwork(networkname string) (models.Network, error)

GetNetwork - gets a network from database

func GetNetworkByNode

func GetNetworkByNode(node *models.Node) (models.Network, error)

GetNetworkByNode - gets the network model from a node

func GetNetworkExtClients

func GetNetworkExtClients(network string) ([]models.ExtClient, error)

GetNetworkExtClients - gets the ext clients of given network

func GetNetworkNodes

func GetNetworkNodes(network string) ([]models.Node, error)

GetNetworkNodes - gets the nodes of a network

func GetNetworkNodesMemory

func GetNetworkNodesMemory(allNodes []models.Node, network string) []models.Node

GetNetworkNodesMemory - gets all nodes belonging to a network from list in memory

func GetNetworkNonServerNodeCount

func GetNetworkNonServerNodeCount(networkName string) (int, error)

GetNetworkNonServerNodeCount - get number of network non server nodes

func GetNetworkSettings

func GetNetworkSettings(networkname string) (models.Network, error)

GetNetworkSettings - get parent network

func GetNetworks

func GetNetworks() ([]models.Network, error)

GetNetworks - returns all networks from database

func GetNodeByHostRef added in v0.21.2

func GetNodeByHostRef(hostid, network string) (node models.Node, err error)

GetNodeByHostRef - gets the node by host id and network

func GetNodeByID

func GetNodeByID(uuid string) (models.Node, error)

func GetNodeDNS

func GetNodeDNS(network string) ([]models.DNSEntry, error)

GetNodeDNS - gets the DNS of a network node

func GetNodesWithTag added in v0.26.0

func GetNodesWithTag(tagID models.TagID) map[string]models.Node

func GetParentNetwork

func GetParentNetwork(networkname string) (models.Network, error)

GetParentNetwork - get parent network

func GetPeerListenPort

func GetPeerListenPort(host *models.Host) int

GetPeerListenPort - given a host, retrieve it's appropriate listening port

func GetPeerUpdateForHost

func GetPeerUpdateForHost(network string, host *models.Host, allNodes []models.Node,
	deletedNode *models.Node, deletedClients []models.ExtClient) (models.HostPeerUpdate, error)

GetPeerUpdateForHost - gets the consolidated peer update for the host from all networks

func GetRecordKey

func GetRecordKey(id string, network string) (string, error)

GetRecordKey - get record key depricated

func GetRelatedHosts

func GetRelatedHosts(hostID string) []models.Host

GetRelatedHosts - fetches related hosts of a given host

func GetReturnUser

func GetReturnUser(username string) (models.ReturnUser, error)

GetReturnUser - gets a user

func GetRole added in v0.25.0

GetRole - fetches role template by id

func GetState

func GetState(state string) (*models.SsoState, error)

GetState - gets an SsoState from DB, if expired returns error

func GetStaticNodeIps added in v0.26.0

func GetStaticNodeIps(node models.Node) (ips []net.IP)

func GetStaticNodeWithTag added in v0.26.0

func GetStaticNodeWithTag(tagID models.TagID) map[string]models.Node

func GetStaticNodesByGw added in v0.26.0

func GetStaticNodesByGw(gwNode models.Node) (staticNode []models.Node)

func GetStaticNodesByNetwork added in v0.26.0

func GetStaticNodesByNetwork(network models.NetworkID, onlyWg bool) (staticNode []models.Node)

func GetStaticUserNodesByNetwork added in v0.26.0

func GetStaticUserNodesByNetwork(network models.NetworkID) (staticNode []models.Node)

func GetSuperAdmin

func GetSuperAdmin() (models.ReturnUser, error)

GetSuperAdmin - fetches superadmin user

func GetTag added in v0.26.0

func GetTag(tagID models.TagID) (models.Tag, error)

GetTag - fetches tag info

func GetTagMapWithNodes added in v0.26.0

func GetTagMapWithNodes() (tagNodesMap map[models.TagID][]models.Node)

func GetTagMapWithNodesByNetwork added in v0.26.0

func GetTagMapWithNodesByNetwork(netID models.NetworkID, withStaticNodes bool) (tagNodesMap map[models.TagID][]models.Node)

func GetUser

func GetUser(username string) (*models.User, error)

GetUser - gets a user TODO support "masteradmin"

func GetUserGrpMap added in v0.30.0

func GetUserGrpMap() map[models.UserGroupID]map[string]struct{}

func GetUserInvite added in v0.25.0

func GetUserInvite(email string) (in models.UserInvite, err error)

func GetUserMap added in v0.25.0

func GetUserMap() (map[string]models.User, error)

func GetUserNameFromToken added in v0.25.0

func GetUserNameFromToken(authtoken string) (username string, err error)

func GetUsers

func GetUsers() ([]models.ReturnUser, error)

GetUsers - gets users

func GetUsersDB added in v0.21.2

func GetUsersDB() ([]models.User, error)

GetUsersDB - gets users

func HasSuperAdmin

func HasSuperAdmin() (bool, error)

HasSuperAdmin - checks if server has an superadmin/owner

func HostExists

func HostExists(h *models.Host) bool

HostExists - checks if given host already exists

func IfaceDelta

func IfaceDelta(currentNode *models.Node, newNode *models.Node) bool

IfaceDelta - checks if the new node causes an interface change

func InitializeZombies

func InitializeZombies()

InitializeZombies - populates the zombie quarantine list (should be called from initialization)

func InsertAcl added in v0.26.0

func InsertAcl(a models.Acl) error

InsertAcl - creates acl policy

func InsertPendingUser added in v0.24.0

func InsertPendingUser(u *models.User) error

func InsertTag added in v0.26.0

func InsertTag(tag models.Tag) error

InsertTag - creates new tag

func InsertUserInvite added in v0.25.0

func InsertUserInvite(invite models.UserInvite) error

func IsAclExists added in v0.26.0

func IsAclExists(aclID string) bool

IsAclExists - checks if acl exists

func IsAclPolicyValid added in v0.26.0

func IsAclPolicyValid(acl models.Acl) bool

IsAclPolicyValid - validates if acl policy is valid

func IsAddressInCIDR

func IsAddressInCIDR(address net.IP, cidr string) bool

IsAddressInCIDR - util to see if an address is in a cidr or not

func IsBase64

func IsBase64(s string) bool

IsBase64 - checks if a string is in base64 format This is used to validate public keys (make sure they're base64 encoded like all public keys should be).

func IsDNSEntryValid added in v0.30.0

func IsDNSEntryValid(d string) bool

IsNetworkNameValid - checks if a netid of a network uses valid characters

func IsIPUnique

func IsIPUnique(network string, ip string, tableName string, isIpv6 bool) bool

IsIPUnique - checks if an IP is unique

func IsInternetGw added in v0.22.0

func IsInternetGw(node models.Node) bool

IsInternetGw - checks if node is acting as internet gw

func IsLegacyNode

func IsLegacyNode(nodeID string) bool

IsLegacyNode - checks if a node is legacy or not

func IsNetworkCIDRUnique added in v0.21.2

func IsNetworkCIDRUnique(cidr4 *net.IPNet, cidr6 *net.IPNet) bool

func IsNetworkNameUnique

func IsNetworkNameUnique(network *models.Network) (bool, error)

IsNetworkNameUnique - checks to see if any other networks have the same name (id)

func IsNodeAllowedToCommunicate added in v0.26.0

func IsNodeAllowedToCommunicate(node, peer models.Node, checkDefaultPolicy bool) (bool, []models.Acl)

IsNodeAllowedToCommunicate - check node is allowed to communicate with the peer

func IsNodeIDUnique

func IsNodeIDUnique(node *models.Node) (bool, error)

IsNodeIDUnique - checks if node id is unique

func IsOauthUser added in v0.25.0

func IsOauthUser(user *models.User) error

IsOauthUser - returns

func IsPeerAllowed added in v0.30.0

func IsPeerAllowed(node, peer models.Node, checkDefaultPolicy bool) bool

IsPeerAllowed - checks if peer needs to be added to the interface

func IsPendingUser added in v0.24.0

func IsPendingUser(username string) bool

func IsSlicesEqual added in v0.22.0

func IsSlicesEqual(a, b []string) bool

IsSlicesEqual tells whether a and b contain the same elements. A nil argument is equivalent to an empty slice.

func IsStateValid

func IsStateValid(state string) (string, bool)

IsStateValid - checks if given state is valid or not deletes state after call is made to clean up, should only be called once per sign-in

func IsUserAllowedAccessToExtClient

func IsUserAllowedAccessToExtClient(username string, client models.ExtClient) bool

IsUserAllowedAccessToExtClient - checks if user has permission to access extclient

func IsUserAllowedToCommunicate added in v0.26.0

func IsUserAllowedToCommunicate(userName string, peer models.Node) (bool, []models.Acl)

IsUserAllowedToCommunicate - check if user is allowed to communicate with peer

func IsVersionCompatible added in v0.24.1

func IsVersionCompatible(ver string) bool

IsVersionCompatible checks that the version passed is compabtible (>=) with MinVersion

func ListAcls added in v0.26.0

func ListAcls() (acls []models.Acl)

func ListAclsByNetwork added in v0.30.0

func ListAclsByNetwork(netID models.NetworkID) ([]models.Acl, error)

ListAcls - lists all acl policies

func ListNetworkTags added in v0.26.0

func ListNetworkTags(netID models.NetworkID) ([]models.Tag, error)

ListTags - lists all tags from DB

func ListPendingUsers added in v0.24.0

func ListPendingUsers() ([]models.ReturnUser, error)

func ListPlatformRoles added in v0.25.0

func ListPlatformRoles() ([]models.UserRolePermissionTemplate, error)

ListPlatformRoles - lists user platform roles permission templates

func ListTags added in v0.26.0

func ListTags() ([]models.Tag, error)

ListTags - lists all tags from DB

func ListTagsWithNodes added in v0.26.0

func ListTagsWithNodes(netID models.NetworkID) ([]models.TagListResp, error)

ListTagsWithHosts - lists all tags with tagged hosts

func ListUserInvites added in v0.25.0

func ListUserInvites() ([]models.UserInvite, error)

func ListUserPolicies added in v0.26.0

func ListUserPolicies(u models.User) []models.Acl

ListUserPolicies - lists all acl policies enforced on an user

func ManageZombies

func ManageZombies(ctx context.Context, peerUpdate chan *models.Node)

ManageZombies - goroutine which adds/removes/deletes nodes from the zombie node quarantine list

func MigrateAclPolicies added in v0.30.0

func MigrateAclPolicies()

func NetIDInNetworkCharSet

func NetIDInNetworkCharSet(network *models.Network) bool

NetIDInNetworkCharSet - checks if a netid of a network uses valid characters

func NetworkExists

func NetworkExists(name string) (bool, error)

NetworkExists - check if network exists

func NormalizeCIDR

func NormalizeCIDR(address string) (string, error)

NormalizeCIDR - returns the first address of CIDR

func ParseNetwork

func ParseNetwork(value string) (models.Network, error)

ParseNetwork - parses a network into a model

func RandomString

func RandomString(length int) string

RandomString - returns a random string in a charset

func RemoveAllLegacyNodes

func RemoveAllLegacyNodes() error

RemoveAllLegacyNodes - fetches all legacy nodes from DB and removes

func RemoveDeviceTagFromAclPolicies added in v0.26.0

func RemoveDeviceTagFromAclPolicies(tagID models.TagID, netID models.NetworkID) error

RemoveDeviceTagFromAclPolicies - remove device tag from acl policies

func RemoveHost

func RemoveHost(h *models.Host, forceDelete bool) error

RemoveHost - removes a given host from server

func RemoveHostByID

func RemoveHostByID(hostID string) error

RemoveHostByID - removes a given host by id from server

func RemoveIpFromAllocatedIpMap added in v0.25.0

func RemoveIpFromAllocatedIpMap(networkName string, ip string)

func RemoveNetworkFromAllocatedIpMap added in v0.25.0

func RemoveNetworkFromAllocatedIpMap(networkName string)

RemoveNetworkFromAllocatedIpMap - remove network from allocated ip map when network is deleted

func RemoveStringSlice

func RemoveStringSlice(slice []string, i int) []string

RemoveStringSlice - removes an element at given index i from a given string slice

func RemoveTagFromEnrollmentKeys added in v0.26.0

func RemoveTagFromEnrollmentKeys(deletedTagID models.TagID)

func RetrievePrivateTrafficKey

func RetrievePrivateTrafficKey() ([]byte, error)

RetrievePrivateTrafficKey - retrieves private key of server

func RetrievePublicTrafficKey

func RetrievePublicTrafficKey() ([]byte, error)

RetrievePublicTrafficKey - retrieves public key of server

func ReturnErrorResponse

func ReturnErrorResponse(response http.ResponseWriter, request *http.Request, errorMessage models.ErrorResponse)

ReturnErrorResponse - processes error and adds header

func ReturnSuccessResponse

func ReturnSuccessResponse(response http.ResponseWriter, request *http.Request, message string)

ReturnSuccessResponse - processes message and adds header

func ReturnSuccessResponseWithJson added in v0.22.0

func ReturnSuccessResponseWithJson(response http.ResponseWriter, request *http.Request, res interface{}, message string)

ReturnSuccessResponseWithJson - processes message and adds header

func SaveExtClient

func SaveExtClient(extclient *models.ExtClient) error

SaveExtClient - saves an ext client to database

func SaveNetwork

func SaveNetwork(network *models.Network) error

SaveNetwork - save network struct to database

func SecurityCheck

func SecurityCheck(reqAdmin bool, next http.Handler) http.HandlerFunc

SecurityCheck - Check if user has appropriate permissions

func SetAllocatedIpMap added in v0.25.0

func SetAllocatedIpMap() error

SetAllocatedIpMap - set allocated ip map for networks

func SetAuthSecret added in v0.24.0

func SetAuthSecret(secret string) error

func SetCorefile

func SetCorefile(domains string) error

SetCorefile - sets the core file of the system

func SetDNS

func SetDNS() error

SetDNS - sets the dns on file

func SetFreeTierForTelemetry

func SetFreeTierForTelemetry(freeTierFlag bool)

setFreeTierForTelemetry - store free tier flag without having an import cycle when used for telemetry (as the pro package needs the logic package as currently written).

func SetFreeTierLimits

func SetFreeTierLimits()

SetFreeTierLimits - sets limits for free tier

func SetJWTSecret

func SetJWTSecret()

SetJWTSecret - sets the jwt secret on server startup

func SetNetworkNodesLastModified

func SetNetworkNodesLastModified(networkName string) error

SetNetworkNodesLastModified - sets the network nodes last modified

func SetNodeDefaults

func SetNodeDefaults(node *models.Node, resetConnected bool)

SetNodeDefaults - sets the defaults of a node to avoid empty fields

func SetState

func SetState(state string) error

SetState - sets a state with new expiration

func SetUserDefaults

func SetUserDefaults(user *models.User)

SetUserDefaults - sets the defaults of a user to avoid empty fields

func SortAclEntrys added in v0.26.0

func SortAclEntrys(acls []models.Acl)

SortTagEntrys - Sorts slice of Tag entries by their id

func SortApiHosts

func SortApiHosts(unsortedHosts []models.ApiHost)

SortApiHosts - Sorts slice of ApiHosts by their ID alphabetically with numbers first

func SortApiNodes

func SortApiNodes(unsortedNodes []models.ApiNode)

SortApiNodes - Sorts slice of ApiNodes by their ID alphabetically with numbers first

func SortDNSEntrys

func SortDNSEntrys(unsortedDNSEntrys []models.DNSEntry)

SortDNSEntrys - Sorts slice of DNSEnteys by their Address alphabetically with numbers first

func SortExtClient

func SortExtClient(unsortedExtClient []models.ExtClient)

SortExtClient - Sorts slice of ExtClients by their ClientID alphabetically with numbers first

func SortNetworks

func SortNetworks(unsortedNetworks []models.Network)

SortNetworks - Sorts slice of Networks by their NetID alphabetically with numbers first

func SortTagEntrys added in v0.26.0

func SortTagEntrys(tags []models.TagListResp)

SortTagEntrys - Sorts slice of Tag entries by their id

func SortUsers

func SortUsers(unsortedUsers []models.ReturnUser)

SortUsers - Sorts slice of Users by username

func StartCPUProfiling added in v0.26.0

func StartCPUProfiling() *os.File

func StartHookManager

func StartHookManager(ctx context.Context, wg *sync.WaitGroup)

StartHookManager - listens on `HookManagerCh` to run any hook

func StartMemProfiling added in v0.30.0

func StartMemProfiling()

func StopCPUProfiling added in v0.26.0

func StopCPUProfiling(f *os.File)

func StoreJWTSecret

func StoreJWTSecret(privateKey string) error

StoreJWTSecret - stores server jwt secret if needed

func StringDifference

func StringDifference(a, b []string) []string

StringDifference - returns the elements in `a` that aren't in `b`.

func StringSliceContains

func StringSliceContains(slice []string, item string) bool

StringSliceContains - sees if a string slice contains a string element

func TimerCheckpoint

func TimerCheckpoint() error

TimerCheckpoint - Checks if 24 hours has passed since telemetry was last sent. If so, sends telemetry data to posthog

func ToReturnUser

func ToReturnUser(user models.User) models.ReturnUser

ToReturnUser - gets a user as a return user

func ToggleExtClientConnectivity

func ToggleExtClientConnectivity(client *models.ExtClient, enable bool) (models.ExtClient, error)

ToggleExtClientConnectivity - enables or disables an ext client

func Tokenize

func Tokenize(k *models.EnrollmentKey, serverAddr string) error

Tokenize - tokenizes an enrollment key to be used via registration and attaches it to the Token field on the struct

func TryToUseEnrollmentKey

func TryToUseEnrollmentKey(k *models.EnrollmentKey) bool

TryToUseEnrollmentKey - checks first if key can be decremented returns true if it is decremented or isvalid

func UniqueAddress

func UniqueAddress(networkName string, reverse bool) (net.IP, error)

UniqueAddress - get a unique ipv4 address

func UniqueAddress6

func UniqueAddress6(networkName string, reverse bool) (net.IP, error)

UniqueAddress6 - see if ipv6 address is unique

func UpdateAcl added in v0.26.0

func UpdateAcl(newAcl, acl models.Acl) error

UpdateAcl - updates allowed fields on acls and commits to DB

func UpdateDeviceTag added in v0.26.0

func UpdateDeviceTag(OldID, newID models.TagID, netID models.NetworkID)

UpdateDeviceTag - updates device tag on acl policies

func UpdateEnrollmentKey added in v0.21.2

func UpdateEnrollmentKey(keyId string, relayId uuid.UUID, groups []models.TagID) (*models.EnrollmentKey, error)

UpdateEnrollmentKey - updates an existing enrollment key's associated relay

func UpdateExtClient

func UpdateExtClient(old *models.ExtClient, update *models.CustomExtClient) models.ExtClient

UpdateExtClient - updates an ext client with new values

func UpdateHost

func UpdateHost(newHost, currentHost *models.Host)

UpdateHost - updates host data by field

func UpdateHostFromClient

func UpdateHostFromClient(newHost, currHost *models.Host) (sendPeerUpdate bool)

UpdateHostFromClient - used for updating host on server with update recieved from client

func UpdateHostNetwork

func UpdateHostNetwork(h *models.Host, network string, add bool) (*models.Node, error)

UpdateHostNetwork - adds/deletes host from a network

func UpdateNetwork

func UpdateNetwork(currentNetwork *models.Network, newNetwork *models.Network) (bool, bool, bool, error)

UpdateNetwork - updates a network with another network's fields

func UpdateNode

func UpdateNode(currentNode *models.Node, newNode *models.Node) error

UpdateNode - takes a node and updates another node with it's values

func UpdateNodeCheckin

func UpdateNodeCheckin(node *models.Node) error

UpdateNodeCheckin - updates the checkin time of a node

func UpdateTag added in v0.26.0

func UpdateTag(req models.UpdateTagReq, newID models.TagID)

UpdateTag - updates and syncs hosts with tag update

func UpdateUser

func UpdateUser(userchange, user *models.User) (*models.User, error)

UpdateUser - updates a given user

func UpsertAcl added in v0.26.0

func UpsertAcl(acl models.Acl) error

UpsertAcl - upserts acl

func UpsertHost

func UpsertHost(h *models.Host) error

UpsertHost - upserts into DB a given host model, does not check for existence*

func UpsertNode

func UpsertNode(newNode *models.Node) error

UpsertNode - updates node in the DB

func UpsertUser

func UpsertUser(user models.User) error

UpsertUser - updates user in the db

func UserPermissions

func UserPermissions(reqAdmin bool, token string) (string, error)

UserPermissions - checks token stuff

func ValidateAndApproveUserInvite added in v0.25.0

func ValidateAndApproveUserInvite(email, code string) error

func ValidateCreateAclReq added in v0.26.0

func ValidateCreateAclReq(req models.Acl) error

ValidateCreateAclReq - validates create req for acl

func ValidateDNSCreate

func ValidateDNSCreate(entry models.DNSEntry) error

ValidateDNSCreate - checks if an entry is valid

func ValidateDNSUpdate

func ValidateDNSUpdate(change models.DNSEntry, entry models.DNSEntry) error

ValidateDNSUpdate - validates a DNS update

func ValidateEgressGateway

func ValidateEgressGateway(gateway models.EgressGatewayRequest) error

ValidateEgressGateway - validates the egress gateway model

func ValidateEgressRange added in v0.24.3

func ValidateEgressRange(gateway models.EgressGatewayRequest) error

func ValidateNetwork

func ValidateNetwork(network *models.Network, isUpdate bool) error

Validate - validates fields of an network struct

func ValidateNode

func ValidateNode(node *models.Node, isUpdate bool) error

ValidateNode - validates node values

func ValidateNodeIp added in v0.30.0

func ValidateNodeIp(currentNode *models.Node, newNode *models.ApiNode) error

func ValidateParams added in v0.23.0

func ValidateParams(nodeid, netid string) (models.Node, error)

func ValidateUser

func ValidateUser(user *models.User) error

ValidateUser - validates a user model

func VerifyAuthRequest

func VerifyAuthRequest(authRequest models.UserAuthParams) (string, error)

VerifyAuthRequest - verifies an auth request

func VerifyHostToken

func VerifyHostToken(tokenString string) (hostID string, mac string, network string, err error)

VerifyHostToken - [hosts] Only

func VerifyJWT

func VerifyJWT(bearerToken string) (username string, issuperadmin, isadmin bool, err error)

VerifyJWT verifies Auth Header

func VerifyUserToken

func VerifyUserToken(tokenString string) (username string, issuperadmin, isadmin bool, err error)

VerifyUserToken func will used to Verify the JWT Token while using APIS

func VersionLessThan added in v0.30.0

func VersionLessThan(v1, v2 string) (bool, error)

VersionLessThan checks if v1 < v2 semantically dev is the latest version

Types

This section is empty.

Directories

Path Synopsis
pro

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL