security

package
v1.9.6 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2025 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// Encryption errors
	ErrInvalidKeyLength    = errors.New("invalid key length")
	ErrEncryptionFailed    = errors.New("encryption failed")
	ErrDecryptionFailed    = errors.New("decryption failed")
	ErrKeyDerivationFailed = errors.New("key derivation failed")
	ErrInvalidCiphertext   = errors.New("invalid ciphertext")

	// Storage errors
	ErrCredentialNotFound = errors.New("credential not found")
	ErrCredentialExists   = errors.New("credential already exists")
	ErrStorageOperation   = errors.New("storage operation failed")
	ErrInvalidCredential  = errors.New("invalid credential")

	// Pattern errors
	ErrInvalidPatternName  = errors.New("invalid pattern name")
	ErrInvalidPatternRegex = errors.New("invalid pattern regex")
	ErrPatternNotFound     = errors.New("pattern not found")

	// Input errors
	ErrEmptyInput   = errors.New("empty input")
	ErrInvalidInput = errors.New("invalid input")
	ErrInputTooLong = errors.New("input too long")

	// Audit errors
	ErrAuditLogFailed    = errors.New("audit log failed")
	ErrInvalidAuditEvent = errors.New("invalid audit event")

	// Authentication errors
	ErrAuthenticationFailed = errors.New("authentication failed")
	ErrPermissionDenied     = errors.New("permission denied")
	ErrSessionExpired       = errors.New("session expired")
)

Security package errors

Functions

func GetTerminalSize

func GetTerminalSize() (width, height int, err error)

GetTerminalSize returns the terminal size if available

func ValidatePattern

func ValidatePattern(pattern SensitivePattern) error

ValidatePattern validates a sensitive pattern

Types

type AESGCMCipher

type AESGCMCipher struct{}

AESGCMCipher implements AES-GCM encryption

func NewAESGCMCipher

func NewAESGCMCipher() *AESGCMCipher

NewAESGCMCipher creates a new AES-GCM cipher

func (*AESGCMCipher) Decrypt

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

Decrypt decrypts ciphertext using AES-GCM

func (*AESGCMCipher) Encrypt

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

Encrypt encrypts plaintext using AES-GCM

type AlertFilter

type AlertFilter struct {
	Types      []string
	Severities []string
	Resources  []string
	TimeRange  *TimeRange
	MaxAge     time.Duration
}

AlertFilter provides filtering for security alerts

func (*AlertFilter) Matches

func (filter *AlertFilter) Matches(alert SecurityAlert) bool

Matches checks if an alert matches the filter criteria

type AuditConfig

type AuditConfig struct {
	LogFile       string
	BufferSize    int
	FlushInterval time.Duration
	MaxFileSize   int64
	RotateFiles   bool
	MaxFiles      int
}

AuditConfig provides configuration for audit logging

func DefaultAuditConfig

func DefaultAuditConfig() *AuditConfig

DefaultAuditConfig returns default audit configuration

type AuditEvent

type AuditEvent struct {
	Timestamp time.Time              `json:"timestamp"`
	EventType string                 `json:"event_type"`
	UserID    string                 `json:"user_id,omitempty"`
	Action    string                 `json:"action"`
	Resource  string                 `json:"resource"`
	Status    string                 `json:"status"`
	Details   map[string]interface{} `json:"details,omitempty"`
	ClientIP  string                 `json:"client_ip,omitempty"`
	SessionID string                 `json:"session_id,omitempty"`
	RequestID string                 `json:"request_id,omitempty"`
}

AuditEvent represents a security audit event

type AuditEventFilter

type AuditEventFilter struct {
	EventTypes []string
	Actions    []string
	Resources  []string
	TimeRange  TimeRange
}

AuditEventFilter provides filtering for audit events

func (*AuditEventFilter) Matches

func (filter *AuditEventFilter) Matches(event AuditEvent) bool

Matches checks if an event matches the filter criteria

type AuditLogger

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

AuditLogger handles security audit logging

func NewAuditLogger

func NewAuditLogger(config *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()

Flush manually flushes the buffer

func (*AuditLogger) GetLogFile

func (al *AuditLogger) GetLogFile() string

GetLogFile returns the current log file path

func (*AuditLogger) LogAuthenticationEvent

func (al *AuditLogger) LogAuthenticationEvent(userID, action, status string, details map[string]interface{})

LogAuthenticationEvent logs authentication events

func (*AuditLogger) LogConfigurationChange

func (al *AuditLogger) LogConfigurationChange(resource, action string, details map[string]interface{})

LogConfigurationChange logs configuration change events

func (*AuditLogger) LogCredentialAccess

func (al *AuditLogger) LogCredentialAccess(credentialKey, action string)

LogCredentialAccess logs credential access events

func (*AuditLogger) LogCredentialRotation

func (al *AuditLogger) LogCredentialRotation(credentialKey string, oldVersion, newVersion int)

LogCredentialRotation logs credential rotation events

func (*AuditLogger) LogSecurityViolation

func (al *AuditLogger) LogSecurityViolation(violation string, details map[string]interface{})

LogSecurityViolation logs security violation events

func (*AuditLogger) LogSystemEvent

func (al *AuditLogger) LogSystemEvent(eventType, action, resource, status string, details map[string]interface{})

LogSystemEvent logs general system events

func (*AuditLogger) RotateLog

func (al *AuditLogger) RotateLog() error

RotateLog rotates the log file if rotation is enabled

func (*AuditLogger) SetUserContext

func (al *AuditLogger) SetUserContext(userID, sessionID, clientIP string) *ContextualAuditLogger

SetUserContext sets user context for subsequent log entries

type Cipher

type Cipher interface {
	Encrypt(plaintext []byte, key []byte) ([]byte, error)
	Decrypt(ciphertext []byte, key []byte) ([]byte, error)
}

Cipher defines the interface for encryption/decryption operations

type ContextualAuditLogger

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

ContextualAuditLogger provides audit logging with pre-set context

func (*ContextualAuditLogger) LogEvent

func (cal *ContextualAuditLogger) LogEvent(eventType, action, resource, status string, details map[string]interface{})

LogEvent logs an event with context

type CredentialMonitor

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

CredentialMonitor monitors credential security and generates alerts

func NewCredentialMonitor

func NewCredentialMonitor(storage *SecureStorage, auditLogger *AuditLogger, config *MonitorConfig) *CredentialMonitor

NewCredentialMonitor creates a new credential monitor

func (*CredentialMonitor) CheckCredentialAge

func (cm *CredentialMonitor) CheckCredentialAge() []SecurityAlert

CheckCredentialAge checks for aging credentials and generates alerts

func (*CredentialMonitor) CheckCredentialVersions

func (cm *CredentialMonitor) CheckCredentialVersions() []SecurityAlert

CheckCredentialVersions checks for version-related issues

func (*CredentialMonitor) CheckExpiredCredentials

func (cm *CredentialMonitor) CheckExpiredCredentials() []SecurityAlert

CheckExpiredCredentials checks for credentials that should be rotated

func (*CredentialMonitor) CheckUnusedCredentials

func (cm *CredentialMonitor) CheckUnusedCredentials() []SecurityAlert

CheckUnusedCredentials checks for unused credentials and generates alerts

func (*CredentialMonitor) ClearAlerts

func (cm *CredentialMonitor) ClearAlerts(filter *AlertFilter) int

ClearAlerts clears alerts based on filter criteria

func (*CredentialMonitor) GetAlerts

func (cm *CredentialMonitor) GetAlerts(filter *AlertFilter) []SecurityAlert

GetAlerts returns current alerts with optional filtering

func (*CredentialMonitor) GetStatistics

func (cm *CredentialMonitor) GetStatistics() *MonitorStatistics

GetStatistics returns monitoring statistics

func (*CredentialMonitor) GetThreshold

func (cm *CredentialMonitor) GetThreshold(credentialKey string) time.Duration

GetThreshold gets age threshold for a specific credential

func (*CredentialMonitor) RunAllChecks

func (cm *CredentialMonitor) RunAllChecks() []SecurityAlert

RunAllChecks runs all credential checks and returns combined alerts

func (*CredentialMonitor) SetThreshold

func (cm *CredentialMonitor) SetThreshold(credentialKey string, threshold time.Duration)

SetThreshold sets age threshold for a specific credential

type FileStorage

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

FileStorage implements Storage interface using files

func NewFileStorage

func NewFileStorage(basePath string) *FileStorage

NewFileStorage creates a new file-based storage

func (*FileStorage) Delete

func (fs *FileStorage) Delete(key string) error

Delete removes a credential file

func (*FileStorage) List

func (fs *FileStorage) List() ([]string, error)

List returns all credential keys

func (*FileStorage) Load

func (fs *FileStorage) Load(key string) (*SecureCredential, error)

Load loads a credential from file

func (*FileStorage) Save

func (fs *FileStorage) Save(key string, credential SecureCredential) error

Save stores a credential to file

type KeyManager

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

KeyManager handles encryption key management

func NewKeyManager

func NewKeyManager() (*KeyManager, error)

NewKeyManager creates a new key manager

func NewKeyManagerWithMasterKey

func NewKeyManagerWithMasterKey(masterKey []byte) (*KeyManager, error)

NewKeyManagerWithMasterKey creates a key manager with existing master key

func (*KeyManager) DeriveKey

func (km *KeyManager) DeriveKey(info string, length int) ([]byte, error)

DeriveKey derives a key for specific purpose using HKDF

func (*KeyManager) GetEncryptionKey

func (km *KeyManager) GetEncryptionKey() ([]byte, error)

GetEncryptionKey derives an encryption key using HKDF

type MonitorConfig

type MonitorConfig struct {
	DefaultAgeThreshold  time.Duration
	UnusedThreshold      time.Duration
	MaxAlerts            int
	CheckInterval        time.Duration
	AlertRetentionPeriod time.Duration
	EnableNotifications  bool
	NotificationChannels []string
}

MonitorConfig provides configuration for credential monitoring

func DefaultMonitorConfig

func DefaultMonitorConfig() *MonitorConfig

DefaultMonitorConfig returns default monitor configuration

type MonitorStatistics

type MonitorStatistics struct {
	TotalAlerts      int            `json:"total_alerts"`
	AlertsByType     map[string]int `json:"alerts_by_type"`
	AlertsBySeverity map[string]int `json:"alerts_by_severity"`
}

MonitorStatistics provides monitoring statistics

type SecureCredential

type SecureCredential struct {
	Key        string    `json:"key"`
	Encrypted  []byte    `json:"encrypted"`
	Algorithm  string    `json:"algorithm"`
	CreatedAt  time.Time `json:"created_at"`
	LastUsedAt time.Time `json:"last_used_at"`
	Version    int       `json:"version"`
}

SecureCredential represents an encrypted credential

type SecureInput

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

SecureInput provides secure input methods for sensitive data

func NewSecureInput

func NewSecureInput() *SecureInput

NewSecureInput creates a new secure input instance

func NewSecureInputWithStreams

func NewSecureInputWithStreams(stdin io.Reader, stdout, stderr io.Writer) *SecureInput

NewSecureInputWithStreams creates a secure input with custom streams

func (*SecureInput) ConfirmOverwrite

func (si *SecureInput) ConfirmOverwrite(resource string) (bool, error)

ConfirmOverwrite asks for confirmation before overwriting

func (*SecureInput) IsTerminal

func (si *SecureInput) IsTerminal() bool

IsTerminal checks if the input is from a terminal

func (*SecureInput) ReadAPIKey

func (si *SecureInput) ReadAPIKey(prompt string) (string, error)

ReadAPIKey reads an API key with validation

func (*SecureInput) ReadChoice

func (si *SecureInput) ReadChoice(prompt string, choices []string) (string, error)

ReadChoice reads a choice from multiple options

func (*SecureInput) ReadConfirmation

func (si *SecureInput) ReadConfirmation(message string) (bool, error)

ReadConfirmation reads a yes/no confirmation

func (*SecureInput) ReadPassword

func (si *SecureInput) ReadPassword(prompt string) (string, error)

ReadPassword reads a password with no echo

func (*SecureInput) ReadSecret

func (si *SecureInput) ReadSecret(prompt string) (string, error)

ReadSecret reads a secret token with validation

func (*SecureInput) ReadSensitiveValue

func (si *SecureInput) ReadSensitiveValue(prompt, fieldName string) (string, error)

ReadSensitiveValue reads a sensitive value with validation

func (*SecureInput) ReadText

func (si *SecureInput) ReadText(prompt string) (string, error)

ReadText reads regular text input (non-sensitive)

type SecureInputConfig

type SecureInputConfig struct {
	MinPasswordLength int
	MaxInputLength    int
	AllowEmptyInput   bool
	ConfirmSensitive  bool
}

SecureInputConfig provides configuration for secure input

func DefaultSecureInputConfig

func DefaultSecureInputConfig() *SecureInputConfig

DefaultSecureInputConfig returns default secure input configuration

func (*SecureInputConfig) ValidateInput

func (config *SecureInputConfig) ValidateInput(input, fieldName string) error

ValidateInput validates input according to configuration

func (*SecureInputConfig) ValidatePassword

func (config *SecureInputConfig) ValidatePassword(password string) error

ValidatePassword validates password according to configuration

type SecureLogWriter

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

SecureLogWriter wraps an io.Writer to filter sensitive data from logs

func NewSecureLogWriter

func NewSecureLogWriter(writer io.Writer, filter *SensitiveDataFilter) *SecureLogWriter

NewSecureLogWriter creates a new secure log writer

func (*SecureLogWriter) Write

func (slw *SecureLogWriter) Write(p []byte) (n int, err error)

Write implements io.Writer interface with sensitive data filtering

type SecureStorage

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

SecureStorage provides secure credential storage

func NewSecureStorage

func NewSecureStorage(storage Storage) (*SecureStorage, error)

NewSecureStorage creates a new secure storage instance

func NewSecureStorageWithMasterKey

func NewSecureStorageWithMasterKey(storage Storage, masterKey []byte) (*SecureStorage, error)

NewSecureStorageWithMasterKey creates secure storage with existing master key

func (*SecureStorage) DeleteCredential

func (ss *SecureStorage) DeleteCredential(key string) error

DeleteCredential removes a credential

func (*SecureStorage) GetMasterKey

func (ss *SecureStorage) GetMasterKey() []byte

GetMasterKey returns the master key (for backup/restore purposes)

func (*SecureStorage) ListCredentials

func (ss *SecureStorage) ListCredentials() ([]*SecureCredential, error)

ListCredentials returns all stored credential metadata

func (*SecureStorage) RetrieveCredential

func (ss *SecureStorage) RetrieveCredential(key string) (string, error)

RetrieveCredential decrypts and returns a credential

func (*SecureStorage) RotateCredential

func (ss *SecureStorage) RotateCredential(key, newValue string) error

RotateCredential updates an existing credential with a new value

func (*SecureStorage) StoreCredential

func (ss *SecureStorage) StoreCredential(key, value string) error

StoreCredential encrypts and stores a credential

type SecurityAlert

type SecurityAlert struct {
	Type        string                 `json:"type"`
	Severity    string                 `json:"severity"`
	Message     string                 `json:"message"`
	Resource    string                 `json:"resource"`
	CreatedAt   time.Time              `json:"created_at"`
	Remediation string                 `json:"remediation"`
	Details     map[string]interface{} `json:"details,omitempty"`
}

SecurityAlert represents a security alert

type SensitiveDataFilter

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

SensitiveDataFilter handles filtering of sensitive information from logs and output

func NewSensitiveDataFilter

func NewSensitiveDataFilter() *SensitiveDataFilter

NewSensitiveDataFilter creates a new sensitive data filter with default patterns

func NewSensitiveDataFilterWithCustomPatterns

func NewSensitiveDataFilterWithCustomPatterns(patterns []SensitivePattern) *SensitiveDataFilter

NewSensitiveDataFilterWithCustomPatterns creates a filter with custom patterns

func (*SensitiveDataFilter) AddPattern

func (sdf *SensitiveDataFilter) AddPattern(pattern SensitivePattern)

AddPattern adds a new sensitive pattern to the filter

func (*SensitiveDataFilter) FilterBytes

func (sdf *SensitiveDataFilter) FilterBytes(data []byte) []byte

FilterBytes filters sensitive data from byte slice

func (*SensitiveDataFilter) FilterLogEntry

func (sdf *SensitiveDataFilter) FilterLogEntry(entry string) string

FilterLogEntry filters sensitive information from a log entry

func (*SensitiveDataFilter) FilterString

func (sdf *SensitiveDataFilter) FilterString(input string) string

FilterString filters sensitive information from a string

func (*SensitiveDataFilter) GetPatterns

func (sdf *SensitiveDataFilter) GetPatterns() []SensitivePattern

GetPatterns returns all registered patterns

func (*SensitiveDataFilter) RemovePattern

func (sdf *SensitiveDataFilter) RemovePattern(name string)

RemovePattern removes a pattern by name

func (*SensitiveDataFilter) SetMaskChar

func (sdf *SensitiveDataFilter) SetMaskChar(char rune)

SetMaskChar sets the character used for masking

func (*SensitiveDataFilter) SetMaskLength

func (sdf *SensitiveDataFilter) SetMaskLength(length int)

SetMaskLength sets the length of the mask

type SensitivePattern

type SensitivePattern struct {
	Name        string
	Pattern     *regexp.Regexp
	Replacement string
	Description string
}

SensitivePattern defines a pattern for sensitive data detection

type Storage

type Storage interface {
	Save(key string, credential SecureCredential) error
	Load(key string) (*SecureCredential, error)
	Delete(key string) error
	List() ([]string, error)
}

Storage defines the interface for credential storage

type TimeRange

type TimeRange struct {
	Start time.Time
	End   time.Time
}

TimeRange represents a time range for filtering

Jump to

Keyboard shortcuts

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