backend

package
v0.0.0-...-9d1dd97 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2024 License: AGPL-3.0 Imports: 26 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	RedisHandle        redis.UniversalClient //nolint:gochecknoglobals // System wide redis pool
	RedisHandleReplica redis.UniversalClient //nolint:gochecknoglobals // System wide redis pool
)
View Source
var (
	// LDAPEndChan is the quit-channel for LDAP on shutdown.
	LDAPEndChan chan Done //nolint:gochecknoglobals // Quit-Channel for LDAP on shutdown

	// LDAPRequestChan is a channel for sending LDAP requests.
	LDAPRequestChan chan *LDAPRequest //nolint:gochecknoglobals // Needed for LDAP pooling

	// LDAPAuthEndChan is the quit-channel for LDAP authentication on shutdown.
	LDAPAuthEndChan chan Done //nolint:gochecknoglobals // Quit-Channel for LDAP on shutdown

	// LDAPAuthRequestChan is a channel for sending LDAP authentication requests.
	LDAPAuthRequestChan chan *LDAPAuthRequest //nolint:gochecknoglobals // Needed for LDAP pooling
)
View Source
var LuaMainWorkerEndChan chan Done

LuaMainWorkerEndChan is a channel that signals the termination of the main Lua worker.

LuaPool is a pool of Lua state instances.

View Source
var LuaRequestChan chan *LuaRequest

LuaRequestChan is a channel that carries LuaRequest pointers from various sources.

Functions

func GetCacheNames

func GetCacheNames(requestedProtocol string, backends global.CacheNameBackend) (cacheNames config.StringSet)

GetCacheNames returns the set of cache names for the requested protocol and cache backends. It searches for cache names based on the requested protocol and cache backends provided. If backends is CacheAll or CacheLDAP:

  • It retrieves the LDAP search protocol configuration for the requested protocol.
  • If a cache name is found in the LDAP search protocol configuration, it adds it to the cacheNames set.

If backends is CacheAll or CacheSQL:

  • It retrieves the SQL search protocol configuration for the requested protocol.
  • If a cache name is found in the SQL search protocol configuration, it adds it to the cacheNames set.

If backends is CacheAll or CacheLua:

  • It retrieves the Lua search protocol configuration for the requested protocol.
  • If a cache name is found in the Lua search protocol configuration, it adds it to the cacheNames set.

If no cache names are found in the above steps, it sets the default cache name "__default__".

Parameters: - requestedProtocol: The protocol to search for cache names. - backends: The cache backends to include in the search. This can be CacheAll, CacheLDAP, CacheSQL, or CacheLua.

Returns: - cacheNames: The set of cache names found for the requested protocol and cache backends. It can be obtained as a string slice using the GetStringSlice() method.

func LDAPAuthWorker

func LDAPAuthWorker(ctx context.Context)

LDAPAuthWorker is a function that handles LDAP authentication requests. It expects a context.Context parameter. The function initializes a WaitGroup variable ldapWaitGroup to synchronize its operations. It creates an LDAP pool using the NewPool function with the context and LDAPPoolAuth as the poolType. If the LDAP pool creation fails (returns nil), the function returns. It starts the background cleaner process of the LDAP pool using the houseKeeper method in a goroutine. The function enters an infinite loop that selects between two cases:

  1. The context is done. In this case, it closes the LDAP pool, sends a Done value to the LDAPAuthEndChan channel, and returns from the function.
  2. An LDAP authentication request is received from the LDAPAuthRequestChan channel. The function checks if there are enough idle connections in the pool, and if not, it sends an error

func LDAPMainWorker

func LDAPMainWorker(ctx context.Context)

LDAPMainWorker is a function that handles LDAP requests in a worker thread. It takes a context.Context as a parameter. It creates a sync.WaitGroup to wait for all started goroutines to complete. It creates an LDAPPool by calling the NewPool function with the context and global.LDAPPoolLookup. If the LDAPPool is nil, it returns. It starts the houseKeeper goroutine by calling ldapPool.houseKeeper() in a separate goroutine. It starts an infinite loop with a select statement. The select statement waits for either the context to be done or a request to be received from the LDAPRequestChan channel. If the context is done, it closes the LDAP pool, sends a Done struct to the LDAPEndChan channel, and returns. If a request is received from the LDAPRequestChan channel, it checks if there are enough idle connections in the LDAPPool. If not, it sends an error as an LDAPReply to the request's LDAPReplyChan. It then calls ldapPool.handleLookupRequest to handle the LDAP request, passing in the request and the ldapWaitGroup.

func LoadCacheFromRedis

func LoadCacheFromRedis[T RedisCache](key string, cache **T) (isRedisErr bool, err error)

LoadCacheFromRedis loads the cache value from Redis and unmarshals it into the provided cache pointer. If the key does not exist in Redis, it returns isRedisErr=true and err=nil. If there is an error retrieving the value from Redis, it returns isRedisErr=true and err. Otherwise, it unmarshals the value into the cache pointer and returns isRedisErr=false and err=nil. It also logs any error messages using the DefaultErrLogger.

func LookupUserAccountFromRedis

func LookupUserAccountFromRedis(username string) (accountName string, err error)

LookupUserAccountFromRedis returns the user account value from the user Redis hash.

func LuaMainWorker

func LuaMainWorker(ctx context.Context)

LuaMainWorker is responsible for executing Lua scripts using the provided context. It compiles a Lua script from the specified path and waits for incoming requests. When a request is received, it spawns a goroutine to handle the request asynchronously, passing the compiled script, the request, and the context. If the context is canceled, LuaMainWorker will send a Done signal to notify the caller.

func NewLuaBackendResultStatePool

func NewLuaBackendResultStatePool() lualib.LuaBaseStatePool

NewLuaBackendResultStatePool creates a new instance of LuaBackendResultStatePool that implements the LuaBaseStatePool interface. It initializes a LuaStatePool with a New function

func SaveUserDataToRedis

func SaveUserDataToRedis[T RedisCache](guid string, key string, ttl uint, cache *T) error

SaveUserDataToRedis is a generic routine to store a cache object on Redis. The type is a RedisCache, which is a union.

func SaveWebAuthnToRedis

func SaveWebAuthnToRedis(user *User, ttl uint) error

SaveWebAuthnToRedis saves the user's WebAuthn data to Redis with the specified time-to-live (TTL) duration. It serializes the user object using JSON and stores it in Redis under the key "as_webauthn:user:<user id>". If serialization fails, it logs the error and returns it. If saving to Redis fails, it logs the error. Note: User is a struct representing a user in the system.

Types

type BruteForceBucketCache

type BruteForceBucketCache uint

BruteForceBucketCache is a Redis cache. It is a union member of RedisCache.

type DatabaseResult

type DatabaseResult map[string][]any

DatabaseResult is a store for any database retrieved results. The keys are either SQL field names or LDAP attributes, while the values are the results.

type Done

type Done struct{}

Done is the value for channels to finish workers

type LDAPAuthRequest

type LDAPAuthRequest struct {
	// GUID is the unique identifier for the LDAP auth request.
	// It can be nil.
	GUID *string

	// BindDN is the Distinguished Name for binding to the LDAP server.
	BindDN string

	// BindPW is the password for binding to the LDAP server.
	BindPW string

	// LDAPReplyChan is a channel where the LDAP responses will be sent.
	LDAPReplyChan chan *LDAPReply

	// HTTPClientContext is the context for the HTTP client
	// carrying the LDAP auth request.
	HTTPClientContext context.Context
}

LDAPAuthRequest represents a request to authenticate with an LDAP server.

func (*LDAPAuthRequest) GetLDAPReplyChan

func (l *LDAPAuthRequest) GetLDAPReplyChan() chan *LDAPReply

GetLDAPReplyChan returns the channel where replies from the LDAP server are sent. It retrieves and returns the value of the `LDAPReplyChan` field of the `LDAPAuthRequest` struct.

type LDAPConnection

type LDAPConnection struct {

	// Mu is a Mutex used to synchronize access to the Conn field,
	// essential when multiple goroutines need to access or modify the same connection concurrently.
	Mu sync.Mutex

	// Conn is the active LDAP connection. It is a pointer to an ldap.Conn object.
	Conn *ldap.Conn
	// contains filtered or unexported fields
}

LDAPConnection represents the connection with an LDAP server. It encapsulates the LDAP connection state and provides a means to synchronize access to it.

type LDAPModifyAttributes

type LDAPModifyAttributes map[string][]string

LDAPModifyAttributes represents a type that maps attribute names to slices of string values. This structure is typically used in LDAP operations to modify the attributes of uniquely identified objects/entities.

Key (of type string) - Represents the name of the attribute. The key might be the standard or user-defined attribute name. Value (of type []string) - Represents a slice of strings for the attribute values. These are the values that are assigned to the respective attribute.

type LDAPPool

type LDAPPool struct {
	// contains filtered or unexported fields
}

LDAPPool represents a pool of LDAP connections.

func NewPool

func NewPool(ctx context.Context, poolType int) *LDAPPool

NewPool creates a new LDAPPool object based on the provided context and poolType. If config.LoadableConfig.LDAP is nil, it returns nil. The poolType can be global.LDAPPoolLookup, global.LDAPPoolUnknown, or global.LDAPPoolAuth. It initializes the name and poolSize variables based on the poolType. It creates slices for the conn and conf variables based on the poolSize. It iterates through the poolSize and initializes each element of conf and conn. Then it assigns values from config.LoadableConfig to each element of conf and sets the state of each element of conn to global.LDAPStateClosed. Finally, it returns an LDAPPool object with the provided context, name, conn, and conf.

func (*LDAPPool) Close

func (l *LDAPPool) Close()

Close closes all connections in the LDAPPool. It iterates over each connection in the pool and performs the following actions: - If the connection is not nil, it calls the unbind method on the connection. - If the connection is still not nil, it closes the connection. - Logs a debug message indicating that the connection has been closed. After closing all connections, it logs a debug message indicating that the pool has been terminated.

type LDAPReply

type LDAPReply struct {
	// Result holds the result retrieved from the database.
	// It is of type DatabaseResult which can accommodate different types of database operations.
	Result DatabaseResult

	// RawResult holds a list of entries returned by the LDAP operation.
	// It is an array of pointers to ldap.Entry objects.
	// Each ldap.Entry object represents a single directory entry in the LDAP directory.
	RawResult []*ldap.Entry

	// Err holds any error that occurred during the LDAP operation.
	// It is of type 'error', the built-in interface type for representing an error condition.
	Err error
}

LDAPReply encapsulates the result of an LDAP operation. It holds the results from both the database and the LDAP directory, as well as any error that might have occurred during the operation.

type LDAPRequest

type LDAPRequest struct {
	// GUID is the globally unique identifier for this LDAP request, optional.
	GUID *string

	// Filter is the criteria that the LDAP request uses to filter during the search.
	Filter string

	// BaseDN is the base distinguished name used as the search base.
	BaseDN string

	// SearchAttributes are the attributes for which values are to be returned in the search results.
	SearchAttributes []string

	// MacroSource is the source of macros to be used, optional.
	MacroSource *util.MacroSource

	// Scope defines the scope for LDAP search (base, one, or sub).
	Scope config.LDAPScope

	// Command represents the LDAP command to be executed (add, modify, delete, or search).
	Command global.LDAPCommand

	// ModifyAttributes contains attributes information used in modify command.
	ModifyAttributes LDAPModifyAttributes

	// LDAPReplyChan is the channel where reply from LDAP server is sent.
	LDAPReplyChan chan *LDAPReply

	// HTTPClientContext is the context for managing HTTP requests and responses.
	HTTPClientContext context.Context
}

LDAPRequest represents an LDAP request.

func (*LDAPRequest) GetLDAPReplyChan

func (l *LDAPRequest) GetLDAPReplyChan() chan *LDAPReply

GetLDAPReplyChan returns the channel where replies from the LDAP server are sent. It retrieves and returns the value of the `LDAPReplyChan` field of the `LDAPRequest` struct.

type LuaBackendResult

type LuaBackendResult struct {
	// Authenticated represents whether the user is authenticated or not
	Authenticated bool

	// UserFound indicates whether the user was found in the system or not
	UserFound bool

	// AccountField is the field associated with the user's account
	AccountField string

	// TOTPSecretField is the field that holds the user's TOTP Secret
	TOTPSecretField string

	// TOTPRecoveryField is the field for the user's TOTP recovery code
	TOTPRecoveryField string

	// UniqueUserIDField is the unique user id field
	UniqueUserIDField string

	// DisplayNameField is the display name associated with the user's account
	DisplayNameField string

	// Err captures any error that occurred during the backend process
	Err error

	// Attributes holds any other attributes related to the user's account
	Attributes map[any]any

	// Logs is a pointer to a custom log key-value pair associated with the Lua script.
	Logs *lualib.CustomLogKeyValue
}

LuaBackendResult holds the response returned by the Lua backend. Information about user authentication, user account, and error details are encapsulated in this data structure.

type LuaBackendResultStatePool

type LuaBackendResultStatePool struct {
	*lualib.LuaStatePool
}

LuaBackendResultStatePool embeds the LuaStatePool type. It provides methods for retrieving, returning, and shutting down Lua states.

type LuaRequest

type LuaRequest struct {
	// Debug is a flag that is set, if the server is running in debug mode.
	Debug bool

	// NoAuth is a flag that when set as true, implies that the request does not require authentication.
	NoAuth bool

	// Function is the Lua command that will be executed.
	Function global.LuaCommand

	// Session is a pointer to a unique session ID for the current request.
	Session *string

	// Username is the username used for authentication.
	Username string

	// Password is the respective password for the user.
	Password string

	// ClientIP is the IP address of the client making the request.
	ClientIP string

	// ClientPort is the network port of the client making the request.
	ClientPort string

	// ClientHost is the hostname of the client making the request.
	ClientHost string

	// LocalIP is the IP address of the server handling the request.
	LocalIP string

	// LocalPprt is the network port of the server receiving the request.
	LocalPprt string

	// ClientID is the unique identifier for the client making the request.
	ClientID string

	// TOTPSecret is the secret value used in time-based one-time password (TOTP) authentication.
	TOTPSecret string

	// XSSL holds the SSL certificate of the XSSL server.
	XSSL string

	// XSSLSessionID is the unique identifier for the XSSL session.
	XSSLSessionID string

	// XSSLClientVerify verifies the client under XSSL session.
	XSSLClientVerify string

	// XSSLClientDN is the client's DN under XSSL.
	XSSLClientDN string

	// XSSLClientCN is the Client CN under XSSL.
	XSSLClientCN string

	// XSSLIssuer is the issuer of XSSL.
	XSSLIssuer string

	// XSSLClientNotBefore is the starting time before which the certificate is not valid.
	XSSLClientNotBefore string

	// XSSLClientNotAfter is the time after which the certificate is not valid.
	XSSLClientNotAfter string

	// XSSLSubjectDN denotes XSSL subject's distinguished name.
	XSSLSubjectDN string

	// XSSLIssuerDN denotes XSSL issuer's distinguished name.
	XSSLIssuerDN string

	// XSSLClientSubjectDN is the Client Subject DN under XSSL.
	XSSLClientSubjectDN string

	// XSSLClientIssuerDN is the Client Issuer DN under XSSL.
	XSSLClientIssuerDN string

	// XSSLProtocol is the protocol used under XSSL.
	XSSLProtocol string

	// XSSLCipher is the cipher used under XSSL.
	XSSLCipher string

	// UserAgent is a string representing the user agent making the request.
	UserAgent string

	// Service is the specific service requested by the client.
	Service string

	// Protocol points to the protocol that was used by a client to make the request.
	Protocol *config.Protocol

	// Logs points to custom log key-value pairs to help track the request.
	Logs *lualib.CustomLogKeyValue

	// Context provides context for the Lua command request.
	*lualib.Context

	// LuaReplyChan is a channel to receive the response from the Lua backend.
	LuaReplyChan chan *LuaBackendResult
}

LuaRequest is a subset from the Authentication struct. LuaRequest is a struct that includes various information for a request to Lua.

type PasswordHistory

type PasswordHistory map[string]uint

PasswordHistory is a map of hashed passwords with their failure counter.

type PoolRequest

type PoolRequest[T any] interface {
	GetLDAPReplyChan() chan *LDAPReply
}

PoolRequest is an interface that represents a request made to a connection pool. It provides a method to retrieve the channel where the LDAP reply will be sent. The type parameter `T` can be any type.

type PositivePasswordCache

type PositivePasswordCache struct {
	Backend           global.Backend `redis:"passdb_backend"`
	Password          string         `redis:"password"`
	AccountField      *string        `redis:"account_field"`
	TOTPSecretField   *string        `redis:"totp_secret_field"`
	UniqueUserIDField *string        `redis:"webauth_userid_field"`
	DisplayNameField  *string        `redis:"display_name_field"`
	Attributes        DatabaseResult `redis:"attributes"`
}

PositivePasswordCache is a container that stores all kinds of user information upon a successful authentication. It is used for Redis as a short cache object and as proxy structure between Nauthilus instances. The cache object is not refreshed upon continuous requests. If the Redis TTL has expired, the object is removed from cache to force a refresh of the user data from underlying databases.

type RedisCache

type RedisCache interface {
	PositivePasswordCache | BruteForceBucketCache
}

RedisCache is a union that is used for LoadCacheFromRedis and SaveUserDataToRedis Redis routines. These routines are generics.

type User

type User struct {
	Id          string `redis:"Id"`
	Name        string `redis:"name"`
	DisplayName string `redis:"display_name"`

	Credentials []webauthn.Credential `redis:"credentials"`
}

User represents the user model

func GetWebAuthnFromRedis

func GetWebAuthnFromRedis(uniqueUserId string) (user *User, err error)

GetWebAuthnFromRedis returns the user object from Redis based on the unique user ID. It retrieves the Redis value based on the provided key and unmarshals it into a User object. If there is an error during the process, it logs the error and returns nil with the error. Otherwise, it returns the user object.

func NewUser

func NewUser(name string, displayName string, id string) *User

NewUser creates and returns a new User

func (*User) AddCredential

func (u *User) AddCredential(cred webauthn.Credential)

AddCredential associates the credential to the user

func (*User) WebAuthnCredentials

func (u *User) WebAuthnCredentials() []webauthn.Credential

WebAuthnCredentials returns credentials owned by the user

func (*User) WebAuthnDisplayName

func (u *User) WebAuthnDisplayName() string

WebAuthnDisplayName returns the user's display name

func (*User) WebAuthnID

func (u *User) WebAuthnID() []byte

WebAuthnID returns the user's ID

func (*User) WebAuthnIcon

func (u *User) WebAuthnIcon() string

WebAuthnIcon is not (yet) implemented

func (*User) WebAuthnName

func (u *User) WebAuthnName() string

WebAuthnName returns the user's username

Jump to

Keyboard shortcuts

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