security

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package security provides security features for XxSql.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExtractIP

func ExtractIP(addr net.Addr) string

ExtractIP extracts IP address from a network address.

func GenerateRandomPassword

func GenerateRandomPassword(policy *PasswordPolicy) (string, error)

GenerateRandomPassword generates a random password meeting the policy.

func GenerateResetToken

func GenerateResetToken() (string, error)

GenerateResetToken generates a secure password reset token.

func GenerateSelfSignedCert

func GenerateSelfSignedCert(certFile, keyFile string, hosts []string) error

GenerateSelfSignedCert generates a self-signed certificate for development. Note: For production, use proper certificates from a CA.

Types

type AccessMode

type AccessMode int

AccessMode determines how IP access is controlled.

const (
	// AccessModeAllowAll allows all connections (default).
	AccessModeAllowAll AccessMode = iota
	// AccessModeWhitelist only allows IPs in the whitelist.
	AccessModeWhitelist
	// AccessModeBlacklist allows all IPs except those in the blacklist.
	AccessModeBlacklist
)

type AuditConfig

type AuditConfig struct {
	Enabled    bool
	FilePath   string
	MaxSizeMB  int
	MaxBackups int
	FlushIntMs int
}

AuditConfig contains configuration for audit logging.

func DefaultAuditConfig

func DefaultAuditConfig() *AuditConfig

DefaultAuditConfig returns default audit configuration.

type AuditFilter

type AuditFilter struct {
	EventType *EventType
	Severity  *Severity
	User      string
	SourceIP  string
	StartTime *time.Time
	EndTime   *time.Time
	Limit     int
}

AuditFilter provides filtering for audit queries.

func (*AuditFilter) Match

func (f *AuditFilter) Match(event *Event) bool

Match checks if an event matches the filter.

type AuditLogger

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

AuditLogger provides audit logging functionality.

func NewAuditLogger

func NewAuditLogger(cfg *AuditConfig) (*AuditLogger, error)

NewAuditLogger creates a new audit logger.

func (*AuditLogger) Close

func (al *AuditLogger) Close() error

Close closes the audit logger.

func (*AuditLogger) Flush

func (al *AuditLogger) Flush() error

Flush writes all buffered events to the file.

func (*AuditLogger) Log

func (al *AuditLogger) Log(event *Event)

Log records an audit event.

func (*AuditLogger) LogSimple

func (al *AuditLogger) LogSimple(eventType EventType, severity Severity, user, sourceIP, message string)

LogSimple records a simple audit event.

func (*AuditLogger) Query

func (al *AuditLogger) Query(filter *AuditFilter) ([]Event, error)

Query retrieves audit events matching the given criteria.

type Event

type Event struct {
	Timestamp    time.Time              `json:"timestamp"`
	EventType    EventType              `json:"event_type"`
	Severity     Severity               `json:"severity"`
	User         string                 `json:"user,omitempty"`
	SourceIP     string                 `json:"source_ip,omitempty"`
	ConnectionID uint64                 `json:"connection_id,omitempty"`
	Database     string                 `json:"database,omitempty"`
	Table        string                 `json:"table,omitempty"`
	Permission   string                 `json:"permission,omitempty"`
	Message      string                 `json:"message,omitempty"`
	Details      map[string]interface{} `json:"details,omitempty"`
}

Event represents an audit event.

type EventType

type EventType int

EventType represents an audit event type.

const (
	EventLoginSuccess EventType = iota
	EventLoginFailed
	EventLogout
	EventPasswordChange
	EventUserCreated
	EventUserDeleted
	EventPermissionGranted
	EventPermissionRevoked
	EventConnectionRejected
	EventRateLimitExceeded
	EventIPBlocked
	EventTLSHandshake
	EventTLSHandshakeFailed
)

func (EventType) String

func (e EventType) String() string

String returns the string representation of the event type.

type IPAccess

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

IPAccess provides IP-based access control.

func NewIPAccess

func NewIPAccess(cfg *IPAccessConfig, audit *AuditLogger) (*IPAccess, error)

NewIPAccess creates a new IP access controller.

func (*IPAccess) AddToBlacklist

func (ipa *IPAccess) AddToBlacklist(ipOrCIDR string) error

AddToBlacklist adds an IP or CIDR to the blacklist.

func (*IPAccess) AddToWhitelist

func (ipa *IPAccess) AddToWhitelist(ipOrCIDR string) error

AddToWhitelist adds an IP or CIDR to the whitelist.

func (*IPAccess) CheckAndLog

func (ipa *IPAccess) CheckAndLog(ipStr string) bool

CheckAndLog checks if IP is allowed and logs rejection.

func (*IPAccess) ClearBlacklist

func (ipa *IPAccess) ClearBlacklist()

ClearBlacklist clears all blacklist entries.

func (*IPAccess) ClearWhitelist

func (ipa *IPAccess) ClearWhitelist()

ClearWhitelist clears all whitelist entries.

func (*IPAccess) GetBlacklist

func (ipa *IPAccess) GetBlacklist() []string

GetBlacklist returns a copy of the blacklist.

func (*IPAccess) GetMode

func (ipa *IPAccess) GetMode() AccessMode

GetMode returns the current access mode.

func (*IPAccess) GetWhitelist

func (ipa *IPAccess) GetWhitelist() []string

GetWhitelist returns a copy of the whitelist.

func (*IPAccess) IsAllowed

func (ipa *IPAccess) IsAllowed(ipStr string) bool

IsAllowed checks if an IP address is allowed to connect.

func (*IPAccess) RemoveFromBlacklist

func (ipa *IPAccess) RemoveFromBlacklist(ipStr string)

RemoveFromBlacklist removes an IP or CIDR from the blacklist.

func (*IPAccess) RemoveFromWhitelist

func (ipa *IPAccess) RemoveFromWhitelist(ipStr string)

RemoveFromWhitelist removes an IP or CIDR from the whitelist.

func (*IPAccess) SetMode

func (ipa *IPAccess) SetMode(mode AccessMode)

SetMode sets the access mode.

func (*IPAccess) Stats

func (ipa *IPAccess) Stats() IPAccessStats

Stats returns IP access statistics.

type IPAccessConfig

type IPAccessConfig struct {
	Mode      AccessMode
	Whitelist []string
	Blacklist []string
}

IPAccessConfig contains configuration for IP access control.

func DefaultIPAccessConfig

func DefaultIPAccessConfig() *IPAccessConfig

DefaultIPAccessConfig returns default IP access configuration.

type IPAccessStats

type IPAccessStats struct {
	Mode           AccessMode
	WhitelistCount int
	BlacklistCount int
	NetworkCount   int
}

IPAccessStats contains IP access statistics.

type PasswordPolicy

type PasswordPolicy struct {
	MinLength        int
	MaxLength        int
	RequireUppercase bool
	RequireLowercase bool
	RequireDigit     bool
	RequireSpecial   bool
	MinSpecialChars  int
	ExpireDays       int // 0 = no expiration
	HistoryCount     int // Number of previous passwords to check
	LockoutAttempts  int // Failed attempts before lockout
	LockoutDuration  time.Duration
}

PasswordPolicy defines password requirements.

func DefaultPasswordPolicy

func DefaultPasswordPolicy() *PasswordPolicy

DefaultPasswordPolicy returns a default password policy.

type PasswordStrength

type PasswordStrength int

PasswordStrength represents password strength level.

const (
	StrengthVeryWeak PasswordStrength = iota
	StrengthWeak
	StrengthMedium
	StrengthStrong
	StrengthVeryStrong
)

func CheckStrength

func CheckStrength(password string) PasswordStrength

CheckStrength checks the strength of a password.

func (PasswordStrength) String

func (s PasswordStrength) String() string

String returns the string representation.

type PasswordValidator

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

PasswordValidator validates passwords against a policy.

func NewPasswordValidator

func NewPasswordValidator(policy *PasswordPolicy, audit *AuditLogger) *PasswordValidator

NewPasswordValidator creates a new password validator.

func (*PasswordValidator) ClearHistory

func (pv *PasswordValidator) ClearHistory(username string)

ClearHistory clears password history for a user.

func (*PasswordValidator) DaysUntilExpiry

func (pv *PasswordValidator) DaysUntilExpiry(username string) int

DaysUntilExpiry returns days until password expires.

func (*PasswordValidator) GetPasswordExpiry

func (pv *PasswordValidator) GetPasswordExpiry(username string) time.Time

GetPasswordExpiry returns when the password expires.

func (*PasswordValidator) GetPolicy

func (pv *PasswordValidator) GetPolicy() *PasswordPolicy

GetPolicy returns the current password policy.

func (*PasswordValidator) IsPasswordExpired

func (pv *PasswordValidator) IsPasswordExpired(username string) bool

IsPasswordExpired checks if a user's password has expired.

func (*PasswordValidator) RecordPasswordChange

func (pv *PasswordValidator) RecordPasswordChange(username, passwordHash string)

RecordPasswordChange records a password change for history tracking.

func (*PasswordValidator) SetPolicy

func (pv *PasswordValidator) SetPolicy(policy *PasswordPolicy)

SetPolicy sets a new password policy.

func (*PasswordValidator) Validate

func (pv *PasswordValidator) Validate(password string) error

Validate checks if a password meets the policy requirements. Returns nil if valid, or an error describing the violation.

func (*PasswordValidator) ValidateForUser

func (pv *PasswordValidator) ValidateForUser(username, password string) error

ValidateForUser validates a password for a specific user. This also checks against password history.

type RateLimitConfig

type RateLimitConfig struct {
	Enabled       bool
	MaxAttempts   int           // Max failed attempts before blocking
	WindowSize    time.Duration // Time window for counting attempts
	BlockDuration time.Duration // How long to block after max attempts
	CleanupInt    time.Duration // Interval for cleaning old records
}

RateLimitConfig contains configuration for rate limiting.

func DefaultRateLimitConfig

func DefaultRateLimitConfig() *RateLimitConfig

DefaultRateLimitConfig returns default rate limit configuration.

type RateLimitStats

type RateLimitStats struct {
	TotalTracked     int
	CurrentlyBlocked int
}

RateLimitStats contains rate limiter statistics.

type RateLimiter

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

RateLimiter provides rate limiting functionality.

func NewRateLimiter

func NewRateLimiter(cfg *RateLimitConfig, audit *AuditLogger) *RateLimiter

NewRateLimiter creates a new rate limiter.

func (*RateLimiter) CheckAllowed

func (rl *RateLimiter) CheckAllowed(key string) bool

CheckAllowed checks if a request from the given key is allowed. Returns true if allowed, false if rate limited.

func (*RateLimiter) Clear

func (rl *RateLimiter) Clear(key string)

Clear removes all records for a key.

func (*RateLimiter) GetBlockTimeRemaining

func (rl *RateLimiter) GetBlockTimeRemaining(key string) time.Duration

GetBlockTimeRemaining returns how long until a blocked key is unblocked. Returns 0 if not blocked.

func (*RateLimiter) GetRemainingAttempts

func (rl *RateLimiter) GetRemainingAttempts(key string) int

GetRemainingAttempts returns the number of remaining attempts for a key.

func (*RateLimiter) RecordAttempt

func (rl *RateLimiter) RecordAttempt(key string, user string) bool

RecordAttempt records a failed attempt for the given key. Returns true if this attempt caused blocking.

func (*RateLimiter) RecordSuccess

func (rl *RateLimiter) RecordSuccess(key string)

RecordSuccess clears the attempt record for the given key.

func (*RateLimiter) Stats

func (rl *RateLimiter) Stats() RateLimitStats

Stats returns current rate limiter statistics.

func (*RateLimiter) Stop

func (rl *RateLimiter) Stop()

Stop stops the rate limiter.

func (*RateLimiter) Unblock

func (rl *RateLimiter) Unblock(key string)

Unblock removes the block for a key.

type SecurityConfig

type SecurityConfig struct {
	Audit     *AuditConfig
	RateLimit *RateLimitConfig
	IPAccess  *IPAccessConfig
	Password  *PasswordPolicy
	TLS       *TLSConfig
}

SecurityConfig contains all security configuration.

func DefaultSecurityConfig

func DefaultSecurityConfig() *SecurityConfig

DefaultSecurityConfig returns default security configuration.

type SecurityManager

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

SecurityManager provides unified security management.

func NewSecurityManager

func NewSecurityManager(cfg *SecurityConfig) (*SecurityManager, error)

NewSecurityManager creates a new security manager.

func (*SecurityManager) AddIPToBlacklist

func (sm *SecurityManager) AddIPToBlacklist(ip string) error

AddIPToBlacklist adds an IP to the blacklist.

func (*SecurityManager) AddIPToWhitelist

func (sm *SecurityManager) AddIPToWhitelist(ip string) error

AddIPToWhitelist adds an IP to the whitelist.

func (*SecurityManager) CheckConnection

func (sm *SecurityManager) CheckConnection(ip string) error

CheckConnection checks if a connection should be allowed. This checks IP access control and rate limiting.

func (*SecurityManager) Close

func (sm *SecurityManager) Close() error

Close closes all security components.

func (*SecurityManager) DaysUntilPasswordExpiry

func (sm *SecurityManager) DaysUntilPasswordExpiry(username string) int

DaysUntilPasswordExpiry returns days until password expires.

func (*SecurityManager) GetAuditLogger

func (sm *SecurityManager) GetAuditLogger() *AuditLogger

GetAuditLogger returns the audit logger.

func (*SecurityManager) GetIPAccess

func (sm *SecurityManager) GetIPAccess() *IPAccess

GetIPAccess returns the IP access controller.

func (*SecurityManager) GetPasswordExpiry

func (sm *SecurityManager) GetPasswordExpiry(username string) time.Time

GetPasswordExpiry returns when a user's password expires.

func (*SecurityManager) GetPasswordValidator

func (sm *SecurityManager) GetPasswordValidator() *PasswordValidator

GetPasswordValidator returns the password validator.

func (*SecurityManager) GetRateLimiter

func (sm *SecurityManager) GetRateLimiter() *RateLimiter

GetRateLimiter returns the rate limiter.

func (*SecurityManager) GetTLSCert

func (sm *SecurityManager) GetTLSCert() interface {
	GetTLSConfig() *tls.Config
	IsEnabled() bool
	IsTLSRequired() bool
}

GetTLSCert returns the TLS certificate for listeners.

func (*SecurityManager) GetTLSConfig

func (sm *SecurityManager) GetTLSConfig() *TLSConfig

GetTLSConfig returns the TLS configuration.

func (*SecurityManager) IsPasswordExpired

func (sm *SecurityManager) IsPasswordExpired(username string) bool

IsPasswordExpired checks if a user's password is expired.

func (*SecurityManager) IsTLSEnabled

func (sm *SecurityManager) IsTLSEnabled() bool

IsTLSEnabled returns whether TLS is enabled.

func (*SecurityManager) IsTLSRequired

func (sm *SecurityManager) IsTLSRequired() bool

IsTLSRequired returns whether TLS is required.

func (*SecurityManager) LogPermissionGranted

func (sm *SecurityManager) LogPermissionGranted(actor, targetUser, permission string)

LogPermissionGranted logs a permission grant event.

func (*SecurityManager) LogPermissionRevoked

func (sm *SecurityManager) LogPermissionRevoked(actor, targetUser, permission string)

LogPermissionRevoked logs a permission revoke event.

func (*SecurityManager) LogUserCreated

func (sm *SecurityManager) LogUserCreated(actor, newUser string)

LogUserCreated logs a user creation event.

func (*SecurityManager) LogUserDeleted

func (sm *SecurityManager) LogUserDeleted(actor, deletedUser string)

LogUserDeleted logs a user deletion event.

func (*SecurityManager) RecordAuthFailure

func (sm *SecurityManager) RecordAuthFailure(ip, username string)

RecordAuthFailure records a failed authentication attempt.

func (*SecurityManager) RecordAuthSuccess

func (sm *SecurityManager) RecordAuthSuccess(ip, username string)

RecordAuthSuccess records a successful authentication.

func (*SecurityManager) RecordLogout

func (sm *SecurityManager) RecordLogout(ip, username string)

RecordLogout records a logout event.

func (*SecurityManager) RecordPasswordChange

func (sm *SecurityManager) RecordPasswordChange(username string, passwordHash string)

RecordPasswordChange records a password change.

func (*SecurityManager) RemoveIPFromBlacklist

func (sm *SecurityManager) RemoveIPFromBlacklist(ip string)

RemoveIPFromBlacklist removes an IP from the blacklist.

func (*SecurityManager) RemoveIPFromWhitelist

func (sm *SecurityManager) RemoveIPFromWhitelist(ip string)

RemoveIPFromWhitelist removes an IP from the whitelist.

func (*SecurityManager) ValidatePassword

func (sm *SecurityManager) ValidatePassword(password string) error

ValidatePassword validates a password against the policy.

func (*SecurityManager) ValidatePasswordForUser

func (sm *SecurityManager) ValidatePasswordForUser(username, password string) error

ValidatePasswordForUser validates a password for a specific user.

type Severity

type Severity int

Severity represents the severity level of an audit event.

const (
	SeverityInfo Severity = iota
	SeverityWarning
	SeverityCritical
)

func (Severity) String

func (s Severity) String() string

String returns the string representation of the severity.

type TLSConfig

type TLSConfig struct {
	Enabled      bool
	Mode         TLSMode
	CertFile     string
	KeyFile      string
	CAFile       string
	MinVersion   uint16
	CipherSuites []uint16
}

TLSConfig contains TLS configuration.

func DefaultTLSConfig

func DefaultTLSConfig() *TLSConfig

DefaultTLSConfig returns default TLS configuration.

type TLSManager

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

TLSManager manages TLS configuration and certificates.

func NewTLSManager

func NewTLSManager(cfg *TLSConfig, audit *AuditLogger) (*TLSManager, error)

NewTLSManager creates a new TLS manager.

func (*TLSManager) GetConfig

func (tm *TLSManager) GetConfig() *TLSConfig

GetConfig returns current TLS configuration.

func (*TLSManager) GetMode

func (tm *TLSManager) GetMode() TLSMode

GetMode returns the TLS mode.

func (*TLSManager) GetTLSConfig

func (tm *TLSManager) GetTLSConfig() *tls.Config

GetTLSConfig returns the TLS configuration.

func (*TLSManager) IsEnabled

func (tm *TLSManager) IsEnabled() bool

IsEnabled returns whether TLS is enabled.

func (*TLSManager) IsTLSRequired

func (tm *TLSManager) IsTLSRequired() bool

IsTLSRequired returns whether TLS is required.

func (*TLSManager) LogTLSHandshake

func (tm *TLSManager) LogTLSHandshake(sourceIP string, success bool, err error)

LogTLSHandshake logs a TLS handshake event.

func (*TLSManager) ReloadCertificates

func (tm *TLSManager) ReloadCertificates() error

ReloadCertificates reloads TLS certificates (for hot reload).

func (*TLSManager) SetConfig

func (tm *TLSManager) SetConfig(cfg *TLSConfig) error

SetConfig sets new TLS configuration.

func (*TLSManager) ShouldUpgrade

func (tm *TLSManager) ShouldUpgrade() bool

ShouldUpgrade checks if a connection should be upgraded to TLS.

func (*TLSManager) VerifyClient

func (tm *TLSManager) VerifyClient(cert *x509.Certificate) error

VerifyClient verifies a client certificate.

type TLSMode

type TLSMode int

TLSMode represents the TLS configuration mode.

const (
	// TLSModeDisabled means TLS is not enabled.
	TLSModeDisabled TLSMode = iota
	// TLSModeOptional means TLS is optional (both secure and insecure connections allowed).
	TLSModeOptional
	// TLSModeRequired means TLS is required for all connections.
	TLSModeRequired
	// TLSModeVerifyCA means TLS is required and client certificate must be verified.
	TLSModeVerifyCA
)

func (TLSMode) String

func (m TLSMode) String() string

String returns the string representation.

Jump to

Keyboard shortcuts

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