auth

package
v0.0.0-...-32afe36 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2025 License: MIT Imports: 41 Imported by: 0

Documentation

Overview

Package auth provides authentication and security functionality for GoVPN

Index

Constants

View Source
const (
	// OpenVPN protocol constants (opcodes)
	OpvnP_CONTROL_HARD_RESET_CLIENT_V1 byte = 1
	OpvnP_CONTROL_HARD_RESET_SERVER_V1 byte = 2
	OpvnP_CONTROL_SOFT_RESET_V1        byte = 3
	OpvnP_CONTROL_V1                   byte = 4
	OpvnP_ACK_V1                       byte = 5
	OpvnP_DATA_V1                      byte = 6
	OpvnP_CONTROL_HARD_RESET_CLIENT_V2 byte = 7
	OpvnP_CONTROL_HARD_RESET_SERVER_V2 byte = 8
	OpvnP_DATA_V2                      byte = 9  // Data packet V2
	OpvnP_CONTROL_HARD_RESET_CLIENT_V3 byte = 10 // Client hard reset V3

	// OpenVPN 2.6+ extended opcodes
	OpvnP_CONTROL_WKC_V1 byte = 11 // WKC (Wrapped Key Control)

	// Additional opcodes for future compatibility
	OpvnP_RESERVED_12 byte = 12
	OpvnP_RESERVED_13 byte = 13
	OpvnP_RESERVED_14 byte = 14
	OpvnP_RESERVED_15 byte = 15

	// Key constants
	KEY_METHOD_2 byte = 2

	// Session ID length
	SESSION_ID_LENGTH = 8

	// TLS authentication key length (2048 bits)
	TLS_AUTH_KEY_LENGTH = 256
)

Variables

View Source
var (
	// ErrInvalidCertificate is returned when a certificate is invalid
	ErrInvalidCertificate = errors.New("invalid certificate")

	// ErrInvalidKey is returned when a key is invalid
	ErrInvalidKey = errors.New("invalid key")

	// ErrCertificateNotFound is returned when a certificate file is not found
	ErrCertificateNotFound = errors.New("certificate file not found")

	// ErrKeyNotFound is returned when a key file is not found
	ErrKeyNotFound = errors.New("key file not found")
)
View Source
var (
	// ErrInvalidCipherMode is returned when an invalid cipher mode is specified
	ErrInvalidCipherMode = errors.New("invalid cipher mode")

	// ErrInvalidKeySize is returned when an invalid key size is provided
	ErrInvalidKeySize = errors.New("invalid key size")

	// ErrInvalidAuthDigest is returned when an invalid authentication digest is specified
	ErrInvalidAuthDigest = errors.New("invalid authentication digest")

	// ErrInsecureMode is returned when an insecure cipher mode is requested
	ErrInsecureMode = errors.New("insecure cipher mode requested")

	// ErrInsecureDigest is returned when an insecure digest is requested
	ErrInsecureDigest = errors.New("insecure authentication digest requested")
)
View Source
var (
	// ErrPacketTooSmall is returned when a packet is too small to be valid
	ErrPacketTooSmall = errors.New("packet too small to be a valid OpenVPN packet")

	// ErrHMACVerificationFailed is returned when HMAC verification fails
	ErrHMACVerificationFailed = errors.New("HMAC verification failed")
)

Functions

func DeriveKeys

func DeriveKeys(masterSecret []byte, salt []byte, keySize int) (encKey, hmacKey []byte, err error)

DeriveKeys derives encryption and HMAC keys from a master secret

func GenerateSelfSignedCertificate

func GenerateSelfSignedCertificate(certPath, keyPath string) error

GenerateSelfSignedCertificate generates a self-signed certificate and key for testing

Types

type AttemptCounter

type AttemptCounter struct {
	UserID      string    `json:"user_id"`
	Attempts    int       `json:"attempts"`
	LastAttempt time.Time `json:"last_attempt"`
	LockedUntil time.Time `json:"locked_until"`
}

AttemptCounter attempt counter for brute force protection

type AuthCache

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

AuthCache provides caching for authentication operations

func NewAuthCache

func NewAuthCache(config *CacheConfig) *AuthCache

NewAuthCache creates a new authentication cache

func (*AuthCache) CachePasswordVerification

func (ac *AuthCache) CachePasswordVerification(username, passwordHash, salt string)

CachePasswordVerification caches a successful password verification

func (*AuthCache) CacheSession

func (ac *AuthCache) CacheSession(sessionID string, session *SessionCacheEntry)

CacheSession stores a session in cache

func (*AuthCache) ClearCache

func (ac *AuthCache) ClearCache()

ClearCache clears all cache entries

func (*AuthCache) ClearUserCache

func (ac *AuthCache) ClearUserCache(username string)

ClearUserCache clears cache entries for a specific user

func (*AuthCache) Close

func (ac *AuthCache) Close()

Close stops the cache and cleanup goroutines

func (*AuthCache) GetCacheStats

func (ac *AuthCache) GetCacheStats() map[string]interface{}

GetCacheStats returns comprehensive cache statistics

func (*AuthCache) GetCachedSession

func (ac *AuthCache) GetCachedSession(sessionID string) (*SessionCacheEntry, bool)

GetCachedSession retrieves a cached session

func (*AuthCache) InvalidateSession

func (ac *AuthCache) InvalidateSession(sessionID string)

InvalidateSession removes a session from cache

func (*AuthCache) IsMFATokenUsed

func (ac *AuthCache) IsMFATokenUsed(username, token string) bool

IsMFATokenUsed checks if an MFA token was recently used (replay protection)

func (*AuthCache) MarkMFATokenUsed

func (ac *AuthCache) MarkMFATokenUsed(username, token string)

MarkMFATokenUsed marks an MFA token as used

func (*AuthCache) Stats

func (ac *AuthCache) Stats() CacheStats

Stats returns cache statistics

func (*AuthCache) VerifyPasswordCached

func (ac *AuthCache) VerifyPasswordCached(username, password, expectedHash, salt string) (bool, bool)

VerifyPasswordCached checks if password verification can be served from cache

func (*AuthCache) WarmupCache

func (ac *AuthCache) WarmupCache(users []string, authManager interface{})

WarmupCache pre-populates cache with frequently used data

type AuthConfig

type AuthConfig struct {
	HashMethod       string      `json:"hash_method"`       // "argon2" or "pbkdf2"
	Argon2Memory     uint32      `json:"argon2_memory"`     // Memory for Argon2 (KB)
	Argon2Time       uint32      `json:"argon2_time"`       // Time for Argon2 (iterations)
	Argon2Threads    uint8       `json:"argon2_threads"`    // Threads for Argon2
	Argon2KeyLength  uint32      `json:"argon2_key_length"` // Key length for Argon2
	PBKDF2Iterations int         `json:"pbkdf2_iterations"` // Iterations for PBKDF2
	PBKDF2KeyLength  int         `json:"pbkdf2_key_length"` // Key length for PBKDF2
	SaltLength       int         `json:"salt_length"`       // Salt length
	SessionTimeout   int         `json:"session_timeout"`   // Session timeout in seconds
	EnableMFA        bool        `json:"enable_mfa"`        // Enable MFA
	EnableOIDC       bool        `json:"enable_oidc"`       // Enable OIDC
	EnableLDAP       bool        `json:"enable_ldap"`       // Enable LDAP
	MFA              *MFAConfig  `json:"mfa,omitempty"`
	OIDC             *OIDCConfig `json:"oidc,omitempty"`
	LDAP             *LDAPConfig `json:"ldap,omitempty"`

	// OIDC fallback settings
	OIDCPrimary           bool     `json:"oidc_primary"`            // OIDC is primary auth method
	AllowPasswordFallback bool     `json:"allow_password_fallback"` // Allow password fallback for admin users
	AdminUsernames        []string `json:"admin_usernames"`         // List of admin usernames allowed password fallback
	RequireAdminMFA       bool     `json:"require_admin_mfa"`       // Require MFA for admin users
}

AuthConfig configuration for authentication system

func DefaultAuthConfig

func DefaultAuthConfig() *AuthConfig

DefaultAuthConfig returns default configuration

type AuthDigest

type AuthDigest string

AuthDigest represents the authentication digest algorithm

const (
	// AuthSHA256 represents SHA256 digest (recommended by OWASP)
	AuthSHA256 AuthDigest = "SHA256"

	// AuthSHA512 represents SHA512 digest (recommended by OWASP)
	AuthSHA512 AuthDigest = "SHA512"

	// AuthSHA1 represents SHA1 digest (deprecated, not recommended)
	AuthSHA1 AuthDigest = "SHA1"
)

func RecommendedAuthDigest

func RecommendedAuthDigest() AuthDigest

RecommendedAuthDigest returns the recommended authentication algorithm

type AuthManager

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

AuthManager manages user authentication

func NewAuthManager

func NewAuthManager(config *AuthConfig) (*AuthManager, error)

NewAuthManager creates a new authentication manager

func (*AuthManager) AddUserRole

func (am *AuthManager) AddUserRole(username, role string) error

AddUserRole adds role to user

func (*AuthManager) AuthenticateOIDCUser

func (am *AuthManager) AuthenticateOIDCUser(session *OIDCSession) (*AuthenticateResult, error)

AuthenticateOIDCUser creates or updates user from OIDC session

func (*AuthManager) AuthenticateUser

func (am *AuthManager) AuthenticateUser(username, password string) (*AuthenticateResult, error)

AuthenticateUser authenticates user with multiple provider support

func (*AuthManager) Close

func (am *AuthManager) Close() error

Close closes all providers

func (*AuthManager) CreateUser

func (am *AuthManager) CreateUser(username, password string) (*User, error)

CreateUser creates new user

func (*AuthManager) DeleteUser

func (am *AuthManager) DeleteUser(username string) error

DeleteUser deletes user

func (*AuthManager) GetLDAPUser

func (am *AuthManager) GetLDAPUser(username string) (*LDAPUser, error)

GetLDAPUser gets user information from LDAP

func (*AuthManager) GetMFAStatus

func (am *AuthManager) GetMFAStatus(username string) map[string]interface{}

GetMFAStatus returns MFA status for user

func (*AuthManager) GetOIDCAuthURL

func (am *AuthManager) GetOIDCAuthURL(userID string) (string, error)

GetOIDCAuthURL gets URL for OIDC authentication

func (*AuthManager) GetUser

func (am *AuthManager) GetUser(username string) (*User, bool)

GetUser returns user by username

func (*AuthManager) HandleOIDCCallback

func (am *AuthManager) HandleOIDCCallback(code, state string) (*OIDCSession, error)

HandleOIDCCallback handles OIDC callback

func (*AuthManager) ListUsers

func (am *AuthManager) ListUsers() map[string]*User

ListUsers returns list of all users

func (*AuthManager) RemoveUserRole

func (am *AuthManager) RemoveUserRole(username, role string) error

RemoveUserRole removes role from user

func (*AuthManager) SetUserActive

func (am *AuthManager) SetUserActive(username string, active bool) error

SetUserActive activates/deactivates user

func (*AuthManager) SetupMFA

func (am *AuthManager) SetupMFA(username, accountName string) (*TOTPData, error)

SetupMFA sets up MFA for user

func (*AuthManager) UpdatePassword

func (am *AuthManager) UpdatePassword(username, newPassword string) error

UpdatePassword updates user password

func (*AuthManager) ValidateMFA

func (am *AuthManager) ValidateMFA(username, code string) (*MFAValidationResult, error)

ValidateMFA validates MFA code

func (*AuthManager) VerifyMFASetup

func (am *AuthManager) VerifyMFASetup(username, code string) error

VerifyMFASetup verifies and activates MFA

type AuthResult

type AuthResult struct {
	Success     bool      `json:"success"`
	User        *LDAPUser `json:"user,omitempty"`
	Error       string    `json:"error,omitempty"`
	Groups      []string  `json:"groups,omitempty"`
	IsAdmin     bool      `json:"is_admin"`
	Permissions []string  `json:"permissions,omitempty"`
}

AuthResult LDAP authentication result

type AuthState

type AuthState struct {
	State           string    `json:"state"`
	CodeVerifier    string    `json:"code_verifier"`
	CodeChallenge   string    `json:"code_challenge"`
	RedirectURI     string    `json:"redirect_uri"`
	Scopes          []string  `json:"scopes"`
	CreatedAt       time.Time `json:"created_at"`
	ExpiresAt       time.Time `json:"expires_at"`
	UserID          string    `json:"user_id,omitempty"`
	DeviceCode      string    `json:"device_code,omitempty"`
	UserCode        string    `json:"user_code,omitempty"`
	VerificationURI string    `json:"verification_uri,omitempty"`
}

AuthState represents OAuth2 authorization state

type AuthenticateResult

type AuthenticateResult struct {
	User         *User                  `json:"user"`
	RequiresMFA  bool                   `json:"requires_mfa"`
	MFAChallenge *TOTPData              `json:"mfa_challenge,omitempty"`
	Source       string                 `json:"source"`
	Metadata     map[string]interface{} `json:"metadata,omitempty"`
	SessionID    string                 `json:"session_id,omitempty"`
}

AuthenticateResult authentication result

type CacheConfig

type CacheConfig struct {
	PasswordCacheTTL time.Duration
	SessionCacheTTL  time.Duration
	MFACacheTTL      time.Duration
	MaxEntries       int
	CleanupInterval  time.Duration
}

CacheConfig configures the authentication cache

func DefaultCacheConfig

func DefaultCacheConfig() *CacheConfig

DefaultCacheConfig returns default cache configuration

type CacheStats

type CacheStats struct {
	PasswordCacheSize int
	SessionCacheSize  int
	MFACacheSize      int
	PasswordCacheHits int64
}

CacheStats represents cache statistics

type CachedGroup

type CachedGroup struct {
	Group     *LDAPGroup `json:"group"`
	CachedAt  time.Time  `json:"cached_at"`
	ExpiresAt time.Time  `json:"expires_at"`
}

CachedGroup cached group information

type CachedUser

type CachedUser struct {
	User      *LDAPUser `json:"user"`
	CachedAt  time.Time `json:"cached_at"`
	ExpiresAt time.Time `json:"expires_at"`
}

CachedUser cached user information

type CertificateManager

type CertificateManager struct {
	CAPath      string // Path to CA certificate
	CertPath    string // Path to server certificate
	KeyPath     string // Path to server key
	CRLPath     string // Path to Certificate Revocation List
	DhPath      string // Path to Diffie-Hellman parameters
	TLSAuthPath string // Path to TLS auth key
	// contains filtered or unexported fields
}

CertificateManager handles certificates and keys for OpenVPN compatibility

func NewCertificateManager

func NewCertificateManager(opts ...CertificateOption) *CertificateManager

NewCertificateManager creates a new certificate manager

func (*CertificateManager) GetClientCommonName

func (cm *CertificateManager) GetClientCommonName(rawCerts [][]byte) (string, error)

GetClientCommonName extracts the common name from a certificate

func (*CertificateManager) GetTLSAuthKey

func (cm *CertificateManager) GetTLSAuthKey() []byte

GetTLSAuthKey returns the TLS auth key

func (*CertificateManager) GetTLSConfig

func (cm *CertificateManager) GetTLSConfig() (*tls.Config, error)

GetTLSConfig returns a TLS configuration for OpenVPN compatibility

func (*CertificateManager) LoadCertificates

func (cm *CertificateManager) LoadCertificates() error

LoadCertificates loads all certificates and keys

func (*CertificateManager) VerifyClientCertificate

func (cm *CertificateManager) VerifyClientCertificate(rawCerts [][]byte) error

VerifyClientCertificate verifies a client certificate against CA and CRL

type CertificateOption

type CertificateOption func(*CertificateManager)

CertificateOption is a functional option for CertificateManager

func WithCAPath

func WithCAPath(path string) CertificateOption

WithCAPath sets the CA path

func WithCRLPath

func WithCRLPath(path string) CertificateOption

WithCRLPath sets the CRL path

func WithCertPath

func WithCertPath(path string) CertificateOption

WithCertPath sets the certificate path

func WithDhPath

func WithDhPath(path string) CertificateOption

WithDhPath sets the Diffie-Hellman parameters path

func WithKeyPath

func WithKeyPath(path string) CertificateOption

WithKeyPath sets the key path

func WithTLSAuthPath

func WithTLSAuthPath(path string) CertificateOption

WithTLSAuthPath sets the TLS auth key path

type CipherContext

type CipherContext struct {
	CipherMode  CipherMode
	AuthDigest  AuthDigest
	Key         []byte
	IV          []byte
	HMAC        hash.Hash
	BlockCipher cipher.Block
	GCM         cipher.AEAD
	IsGCM       bool
}

CipherContext holds the cipher configuration for encryption/decryption

func NewCipherContext

func NewCipherContext(mode CipherMode, digest AuthDigest, key []byte) (*CipherContext, error)

NewCipherContext creates a new cipher context with the specified mode and digest

func (*CipherContext) Decrypt

func (c *CipherContext) Decrypt(ciphertext []byte) ([]byte, error)

Decrypt decrypts ciphertext data

func (*CipherContext) Encrypt

func (c *CipherContext) Encrypt(plaintext []byte) ([]byte, error)

Encrypt encrypts plaintext data

func (*CipherContext) InitIV

func (c *CipherContext) InitIV() error

InitIV initializes a random IV for the cipher context

func (*CipherContext) SetIV

func (c *CipherContext) SetIV(iv []byte) error

SetIV sets the IV for the cipher context

type CipherMode

type CipherMode string

CipherMode represents the cipher mode for OpenVPN

const (
	// CipherAES128GCM represents AES-128-GCM mode
	CipherAES128GCM CipherMode = "AES-128-GCM"

	// CipherAES192GCM represents AES-192-GCM mode
	CipherAES192GCM CipherMode = "AES-192-GCM"

	// CipherAES256GCM represents AES-256-GCM mode
	CipherAES256GCM CipherMode = "AES-256-GCM"

	// CipherAES128CBC represents AES-128-CBC mode (legacy)
	CipherAES128CBC CipherMode = "AES-128-CBC"

	// CipherAES192CBC represents AES-192-CBC mode (legacy)
	CipherAES192CBC CipherMode = "AES-192-CBC"

	// CipherAES256CBC represents AES-256-CBC mode (legacy)
	CipherAES256CBC CipherMode = "AES-256-CBC"

	// CipherChacha20Poly1305 represents ChaCha20-Poly1305 mode
	CipherChacha20Poly1305 CipherMode = "CHACHA20-POLY1305"
)

func RecommendedCipherMode

func RecommendedCipherMode() CipherMode

RecommendedCipherMode returns the recommended cipher mode

type ClaimMappings

type ClaimMappings struct {
	Username    string `json:"username"`     // Claim for username
	Email       string `json:"email"`        // Claim for email
	FirstName   string `json:"first_name"`   // Claim for first name
	LastName    string `json:"last_name"`    // Claim for last name
	Groups      string `json:"groups"`       // Claim for groups
	Roles       string `json:"roles"`        // Claim for roles
	DisplayName string `json:"display_name"` // Claim for display name
}

ClaimMappings mapping of OIDC claims to local user attributes

type DeviceAuthResponse

type DeviceAuthResponse struct {
	DeviceCode              string `json:"device_code"`
	UserCode                string `json:"user_code"`
	VerificationURI         string `json:"verification_uri"`
	VerificationURIComplete string `json:"verification_uri_complete,omitempty"`
	ExpiresIn               int    `json:"expires_in"`
	Interval                int    `json:"interval"`
}

DeviceAuthResponse represents device authorization endpoint response

type GroupAttributes

type GroupAttributes struct {
	Name        string `json:"name"`        // cn
	Description string `json:"description"` // description
	Members     string `json:"members"`     // member
	DN          string `json:"dn"`          // distinguishedName
}

GroupAttributes mapping of LDAP group attributes

type HOTPSettings

type HOTPSettings struct {
	Digits    otp.Digits    `json:"digits"`    // Number of digits in code (using standard library type)
	Algorithm otp.Algorithm `json:"algorithm"` // SHA1, SHA256, SHA512 (using standard library type)
	Lookahead int           `json:"lookahead"` // Number of attempts ahead
}

HOTPSettings settings for HMAC-based OTP using standard library

type LDAPConfig

type LDAPConfig struct {
	Enabled            bool            `json:"enabled"`
	Server             string          `json:"server"`
	Port               int             `json:"port"`
	UseSSL             bool            `json:"use_ssl"`
	UseTLS             bool            `json:"use_tls"`
	SkipVerify         bool            `json:"skip_verify"`
	Timeout            time.Duration   `json:"timeout"`
	BindDN             string          `json:"bind_dn"`
	BindPassword       string          `json:"bind_password"`
	BaseDN             string          `json:"base_dn"`
	UserFilter         string          `json:"user_filter"`
	GroupFilter        string          `json:"group_filter"`
	UserSearchBase     string          `json:"user_search_base"`
	GroupSearchBase    string          `json:"group_search_base"`
	UserAttributes     UserAttributes  `json:"user_attributes"`
	GroupAttributes    GroupAttributes `json:"group_attributes"`
	RequiredGroups     []string        `json:"required_groups"`
	AdminGroups        []string        `json:"admin_groups"`
	ConnectionPoolSize int             `json:"connection_pool_size"`
	MaxRetries         int             `json:"max_retries"`
	RetryDelay         time.Duration   `json:"retry_delay"`
	CacheTimeout       time.Duration   `json:"cache_timeout"`
	CacheEnabled       bool            `json:"cache_enabled"`
}

LDAPConfig configuration for LDAP authentication

type LDAPGroup

type LDAPGroup struct {
	DN          string   `json:"dn"`
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Members     []string `json:"members"`
}

LDAPGroup group information from LDAP

type LDAPProvider

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

LDAPProvider LDAP authentication provider

func NewLDAPProvider

func NewLDAPProvider(config *LDAPConfig, logger Logger) (*LDAPProvider, error)

NewLDAPProvider creates new LDAP provider

func (*LDAPProvider) Authenticate

func (l *LDAPProvider) Authenticate(username, password string) (*AuthResult, error)

Authenticate authenticates user by username and password

func (*LDAPProvider) Close

func (l *LDAPProvider) Close() error

Close closes all connections

func (*LDAPProvider) GetGroup

func (l *LDAPProvider) GetGroup(groupName string) (*LDAPGroup, error)

GetGroup gets group information

func (*LDAPProvider) GetUser

func (l *LDAPProvider) GetUser(username string) (*LDAPUser, error)

GetUser gets user information

func (*LDAPProvider) SearchUsers

func (l *LDAPProvider) SearchUsers(filter string, limit int) ([]*LDAPUser, error)

SearchUsers searches users by filter

func (*LDAPProvider) ValidateConnection

func (l *LDAPProvider) ValidateConnection() error

ValidateConnection validates connection to LDAP server

type LDAPUser

type LDAPUser struct {
	DN          string            `json:"dn"`
	Username    string            `json:"username"`
	Email       string            `json:"email"`
	FirstName   string            `json:"first_name"`
	LastName    string            `json:"last_name"`
	DisplayName string            `json:"display_name"`
	Groups      []string          `json:"groups"`
	IsAdmin     bool              `json:"is_admin"`
	Attributes  map[string]string `json:"attributes"`
}

LDAPUser user information from LDAP

type Logger

type Logger interface {
	Printf(format string, v ...interface{})
	Errorf(format string, v ...interface{})
	Infof(format string, v ...interface{})
	Debugf(format string, v ...interface{})
}

Logger interface for logging

type MFACacheEntry

type MFACacheEntry struct {
	Username  string
	TokenHash string // Hash of used tokens to prevent replay
	CreatedAt time.Time
	ExpiresAt time.Time
}

MFACacheEntry represents cached MFA validation

type MFAConfig

type MFAConfig struct {
	Enabled          bool          `json:"enabled"`
	RequiredForAll   bool          `json:"required_for_all"`
	TOTPEnabled      bool          `json:"totp_enabled"`
	HOTPEnabled      bool          `json:"hotp_enabled"`
	BackupCodesCount int           `json:"backup_codes_count"`
	TOTPSettings     TOTPSettings  `json:"totp_settings"`
	HOTPSettings     HOTPSettings  `json:"hotp_settings"`
	Issuer           string        `json:"issuer"`
	AccountName      string        `json:"account_name"`
	GracePeriod      time.Duration `json:"grace_period"`
	MaxAttempts      int           `json:"max_attempts"`
	LockoutDuration  time.Duration `json:"lockout_duration"`
}

MFAConfig configuration for multi-factor authentication using standard libraries

type MFAProvider

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

MFAProvider multi-factor authentication provider using standard libraries

func NewMFAProvider

func NewMFAProvider(config *MFAConfig, logger Logger) (*MFAProvider, error)

NewMFAProvider creates new MFA provider using standard libraries

func (*MFAProvider) DisableMFA

func (m *MFAProvider) DisableMFA(userID string) error

DisableMFA disables MFA for user

func (*MFAProvider) GetUserMFAStatus

func (m *MFAProvider) GetUserMFAStatus(userID string) map[string]interface{}

GetUserMFAStatus returns MFA status for user

func (*MFAProvider) IsRequired

func (m *MFAProvider) IsRequired(userID string) bool

IsRequired checks if MFA is required for user

func (*MFAProvider) IsSetup

func (m *MFAProvider) IsSetup(userID string) bool

IsSetup checks if MFA is set up for user

func (*MFAProvider) RegenerateBackupCodes

func (m *MFAProvider) RegenerateBackupCodes(userID string) ([]string, error)

RegenerateBackupCodes regenerates backup codes for user

func (*MFAProvider) SetupHOTP

func (m *MFAProvider) SetupHOTP(userID, accountName string) (*TOTPData, error)

SetupHOTP sets up HOTP for user using standard library

func (*MFAProvider) SetupTOTP

func (m *MFAProvider) SetupTOTP(userID, accountName string) (*TOTPData, error)

SetupTOTP sets up TOTP for user using standard library

func (*MFAProvider) ValidateMFA

func (m *MFAProvider) ValidateMFA(userID, code string) (*MFAValidationResult, error)

ValidateMFA validates MFA code using standard libraries

func (*MFAProvider) VerifyTOTPSetup

func (m *MFAProvider) VerifyTOTPSetup(userID, code string) error

VerifyTOTPSetup verifies TOTP setup with user-provided code using standard library

type MFAValidationResult

type MFAValidationResult struct {
	Valid          bool   `json:"valid"`
	Method         string `json:"method"` // totp, hotp, backup
	RemainingCodes int    `json:"remaining_codes,omitempty"`
	Error          string `json:"error,omitempty"`
}

MFAValidationResult MFA validation result

type OIDCConfig

type OIDCConfig struct {
	Enabled               bool              `json:"enabled"`
	ProviderURL           string            `json:"provider_url"`
	ClientID              string            `json:"client_id"`
	ClientSecret          string            `json:"client_secret"`
	RedirectURL           string            `json:"redirect_url"`
	Scopes                []string          `json:"scopes"`
	UserInfoEndpoint      string            `json:"user_info_endpoint"`
	TokenEndpoint         string            `json:"token_endpoint"`
	AuthorizationEndpoint string            `json:"authorization_endpoint"`
	JWKSEndpoint          string            `json:"jwks_endpoint"`
	IssuerValidation      bool              `json:"issuer_validation"`
	RequiredClaims        map[string]string `json:"required_claims"`
	ClaimMappings         ClaimMappings     `json:"claim_mappings"`
	SessionTimeout        time.Duration     `json:"session_timeout"`
	RefreshTokenEnabled   bool              `json:"refresh_token_enabled"`
	DeviceFlowEnabled     bool              `json:"device_flow_enabled"`
	PkceEnabled           bool              `json:"pkce_enabled"`
}

OIDCConfig configuration for OIDC authentication

type OIDCProvider

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

OIDCProvider represents OIDC authentication provider using standard oauth2 library

func NewOIDCProvider

func NewOIDCProvider(config *OIDCConfig, logger Logger) (*OIDCProvider, error)

NewOIDCProvider creates new OIDC provider using standard oauth2 library

func (*OIDCProvider) GetAllSessions

func (p *OIDCProvider) GetAllSessions() map[string]*OIDCSession

GetAllSessions returns all active sessions

func (*OIDCProvider) GetAuthorizationURL

func (p *OIDCProvider) GetAuthorizationURL(userID string) (string, error)

GetAuthorizationURL creates URL for user authorization

func (*OIDCProvider) HandleCallback

func (p *OIDCProvider) HandleCallback(code, state string) (*OIDCSession, error)

HandleCallback handles callback from OIDC provider

func (*OIDCProvider) RefreshSession

func (p *OIDCProvider) RefreshSession(sessionID string) (*OIDCSession, error)

RefreshSession refreshes session using refresh token

func (*OIDCProvider) RevokeSession

func (p *OIDCProvider) RevokeSession(sessionID string) error

RevokeSession revokes user session

func (*OIDCProvider) StartDeviceFlow

func (p *OIDCProvider) StartDeviceFlow() (*DeviceAuthResponse, error)

StartDeviceFlow starts Device Authorization Flow

func (*OIDCProvider) ValidateSession

func (p *OIDCProvider) ValidateSession(sessionID string) (*OIDCSession, error)

ValidateSession validates session validity

type OIDCSession

type OIDCSession struct {
	UserID       string                 `json:"user_id"`
	Username     string                 `json:"username"`
	Email        string                 `json:"email"`
	Claims       map[string]interface{} `json:"claims"`
	AccessToken  string                 `json:"access_token"`
	RefreshToken string                 `json:"refresh_token"`
	IDToken      string                 `json:"id_token"`
	ExpiresAt    time.Time              `json:"expires_at"`
	CreatedAt    time.Time              `json:"created_at"`
	LastAccess   time.Time              `json:"last_access"`
	Groups       []string               `json:"groups"`
	Roles        []string               `json:"roles"`
	OAuth2Token  *oauth2.Token          `json:"-"` // The underlying oauth2 token
}

OIDCSession represents active OIDC user session

type OpenVPNPacket

type OpenVPNPacket struct {
	Opcode        byte
	KeyID         byte
	SessionID     []byte
	AckPacketID   uint32 // Used in ACK packets
	PacketID      uint32
	PayloadLength uint16
	Payload       []byte
	HMAC          []byte
}

OpenVPNPacket represents an OpenVPN protocol packet

func NewPacket

func NewPacket(opcode byte, payload []byte) *OpenVPNPacket

NewPacket creates a new OpenVPN packet

func (*OpenVPNPacket) AddHMAC

func (p *OpenVPNPacket) AddHMAC(key []byte) error

AddHMAC adds an HMAC to a packet

func (*OpenVPNPacket) Marshal

func (p *OpenVPNPacket) Marshal() ([]byte, error)

Marshal serializes an OpenVPN packet to bytes

func (*OpenVPNPacket) Unmarshal

func (p *OpenVPNPacket) Unmarshal(data []byte) error

Unmarshal deserializes an OpenVPN packet from bytes

func (*OpenVPNPacket) VerifyHMAC

func (p *OpenVPNPacket) VerifyHMAC(key []byte) bool

VerifyHMAC verifies the HMAC of a packet

type OpenVPNSession

type OpenVPNSession struct {
	SessionID       []byte
	RemoteSessionID []byte
	TLSConfig       *tls.Config
	TLSAuthKey      []byte
	PacketID        uint32
	CipherContext   *CipherContext
	LastPacketTime  time.Time
	IsHandshaking   bool
	HandshakeState  *tls.ConnectionState
	PushOptions     *PushOptions
}

OpenVPNSession represents a client session

func NewOpenVPNSession

func NewOpenVPNSession(tlsConfig *tls.Config, tlsAuthKey []byte) *OpenVPNSession

NewOpenVPNSession creates a new OpenVPN session

func (*OpenVPNSession) CreateDataPacket

func (s *OpenVPNSession) CreateDataPacket(data []byte) (*OpenVPNPacket, error)

CreateDataPacket creates a data packet for transmission

func (*OpenVPNSession) DecryptDataPacket

func (s *OpenVPNSession) DecryptDataPacket(packet *OpenVPNPacket) ([]byte, error)

DecryptDataPacket decrypts a DATA packet and returns the payload

func (*OpenVPNSession) ProcessClientHandshake

func (s *OpenVPNSession) ProcessClientHandshake(packet *OpenVPNPacket) (*OpenVPNPacket, error)

ProcessClientHandshake processes a client handshake packet

func (*OpenVPNSession) ProcessControlPacket

func (s *OpenVPNSession) ProcessControlPacket(packet *OpenVPNPacket) (*OpenVPNPacket, error)

ProcessControlPacket processes a control packet

func (*OpenVPNSession) UpdatePushOptions

func (s *OpenVPNSession) UpdatePushOptions(options PushOptions)

UpdatePushOptions updates push options for the session

type PasswordCacheEntry

type PasswordCacheEntry struct {
	PasswordHash string
	Salt         string
	CreatedAt    time.Time
	LastUsed     time.Time
	HitCount     int64
}

PasswordCacheEntry represents cached password verification

type PushOptions

type PushOptions struct {
	Routes          []string
	DNSServers      []string
	RedirectGateway bool
	OtherOptions    map[string]string
}

PushOptions represents the options to push to clients

type SessionCacheEntry

type SessionCacheEntry struct {
	UserID       string
	Username     string
	Roles        []string
	Source       string
	CreatedAt    time.Time
	ExpiresAt    time.Time
	LastAccessed time.Time
	Metadata     map[string]interface{}
}

SessionCacheEntry represents cached session data

type SimpleLogger

type SimpleLogger struct{}

SimpleLogger simple Logger implementation for compatibility

func (*SimpleLogger) Debugf

func (l *SimpleLogger) Debugf(format string, v ...interface{})

func (*SimpleLogger) Errorf

func (l *SimpleLogger) Errorf(format string, v ...interface{})

func (*SimpleLogger) Infof

func (l *SimpleLogger) Infof(format string, v ...interface{})

func (*SimpleLogger) Printf

func (l *SimpleLogger) Printf(format string, v ...interface{})

type TOTPData

type TOTPData struct {
	Secret      string   `json:"secret"`  // Base32 encoded secret
	QRCode      string   `json:"qr_code"` // Base64 encoded QR code image (PNG)
	URL         string   `json:"url"`     // Standard otpauth:// URL
	BackupCodes []string `json:"backup_codes"`
	Key         *otp.Key `json:"-"` // The actual key object (not serialized)
}

TOTPData data for TOTP setup using standard library

type TOTPSettings

type TOTPSettings struct {
	Period    uint          `json:"period"`    // Code validity period in seconds (standard library uses uint)
	Digits    otp.Digits    `json:"digits"`    // Number of digits in code (using standard library type)
	Algorithm otp.Algorithm `json:"algorithm"` // SHA1, SHA256, SHA512 (using standard library type)
	Skew      uint          `json:"skew"`      // Allowed time deviation
}

TOTPSettings settings for Time-based OTP using standard library

type TokenResponse

type TokenResponse struct {
	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int    `json:"expires_in"`
	RefreshToken string `json:"refresh_token,omitempty"`
	IDToken      string `json:"id_token,omitempty"`
	Scope        string `json:"scope,omitempty"`
}

TokenResponse represents token endpoint response

type User

type User struct {
	ID           string                 `json:"id"`
	Username     string                 `json:"username"`
	PasswordHash string                 `json:"password_hash"`
	Salt         string                 `json:"salt"`
	CreatedAt    time.Time              `json:"created_at"`
	LastLogin    time.Time              `json:"last_login"`
	IsActive     bool                   `json:"is_active"`
	Roles        []string               `json:"roles"`
	Metadata     map[string]interface{} `json:"metadata,omitempty"`
	Source       string                 `json:"source"` // local, ldap, oidc
}

User represents a user in the system

type UserAttributes

type UserAttributes struct {
	Username    string `json:"username"`     // sAMAccountName, uid
	Email       string `json:"email"`        // mail
	FirstName   string `json:"first_name"`   // givenName
	LastName    string `json:"last_name"`    // sn
	DisplayName string `json:"display_name"` // displayName, cn
	Groups      string `json:"groups"`       // memberOf
	DN          string `json:"dn"`           // distinguishedName
}

UserAttributes mapping of LDAP user attributes

type UserInfo

type UserInfo struct {
	Sub               string                 `json:"sub"`
	Name              string                 `json:"name,omitempty"`
	GivenName         string                 `json:"given_name,omitempty"`
	FamilyName        string                 `json:"family_name,omitempty"`
	PreferredUsername string                 `json:"preferred_username,omitempty"`
	Email             string                 `json:"email,omitempty"`
	EmailVerified     bool                   `json:"email_verified,omitempty"`
	Groups            []string               `json:"groups,omitempty"`
	Roles             []string               `json:"roles,omitempty"`
	CustomClaims      map[string]interface{} `json:"-"`
}

UserInfo represents user information from OIDC provider

type UserMFAData

type UserMFAData struct {
	UserID        string    `json:"user_id"`
	TOTPSecret    string    `json:"totp_secret,omitempty"` // Secret from standard library
	HOTPSecret    string    `json:"hotp_secret,omitempty"` // Secret from standard library
	HOTPCounter   uint64    `json:"hotp_counter"`
	BackupCodes   []string  `json:"backup_codes,omitempty"`
	IsEnabled     bool      `json:"is_enabled"`
	SetupComplete bool      `json:"setup_complete"`
	CreatedAt     time.Time `json:"created_at"`
	LastUsed      time.Time `json:"last_used"`
	DeviceName    string    `json:"device_name,omitempty"`
	TOTPKey       *otp.Key  `json:"-"` // The key object from standard library (not serialized)
	HOTPKey       *otp.Key  `json:"-"` // The HOTP key object (not serialized)
}

UserMFAData MFA data for user

Jump to

Keyboard shortcuts

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