security

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2025 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConstantTimeCompare

func ConstantTimeCompare(a, b []byte) int

ConstantTimeCompare is a convenience function for constant-time comparison

func ConstantTimeEq

func ConstantTimeEq(a, b []byte) bool

ConstantTimeEq is a convenience function for constant-time equality check

func FillSecureRandom

func FillSecureRandom(data []byte) error

FillSecureRandom fills a byte slice with cryptographically secure random data

func GenerateSecureKey

func GenerateSecureKey(keySize int) ([]byte, error)

GenerateSecureKey generates a cryptographic key

func GenerateSecureNonce

func GenerateSecureNonce(size int) ([]byte, error)

GenerateSecureNonce generates a cryptographically secure nonce

func GenerateSecurePassword

func GenerateSecurePassword(length int, includeSpecial bool) (string, error)

GenerateSecurePassword generates a secure random password

func GenerateSecureRandom

func GenerateSecureRandom(size int) ([]byte, error)

GenerateSecureRandom generates cryptographically secure random bytes

func GenerateSecureSalt

func GenerateSecureSalt(size int) ([]byte, error)

GenerateSecureSalt generates a cryptographically secure salt

func LogSecurityEvent

func LogSecurityEvent(eventType, message string, level SecurityLevel)

LogSecurityEvent logs a security event using the global auditor

func MaskSensitiveOperation

func MaskSensitiveOperation(data []byte, operation func([]byte) []byte) []byte

MaskSensitiveOperation performs an operation with side-channel masking

func ProtectAgainstTiming

func ProtectAgainstTiming(operation func() error) error

ProtectAgainstTiming performs an operation with timing attack protection

func SecureAllocate

func SecureAllocate(size int) []byte

SecureAllocate is a convenience function for secure memory allocation

func SecureCompareBytes

func SecureCompareBytes(a, b []byte) bool

SecureCompareBytes compares byte slices in constant time

func SecureCompareStrings

func SecureCompareStrings(a, b string) bool

SecureCompareStrings compares strings in constant time

func SecureCopy

func SecureCopy(src []byte) []byte

SecureCopy is a convenience function for secure copying

func SetGlobalEventHandler

func SetGlobalEventHandler(handler func(SecurityEvent))

SetGlobalEventHandler sets a global event handler for security events

func TrackSecureOperation

func TrackSecureOperation(ctx context.Context, operation string, fn func() error) error

TrackSecureOperation tracks a secure operation using the global tracker

func ValidateKeySize

func ValidateKeySize(keySize int, algorithm string) error

ValidateKeySize validates a key size using the global validator

func ValidatePasswordStrength

func ValidatePasswordStrength(password string) error

ValidatePasswordStrength validates password strength using the global validator

func ZeroBytes

func ZeroBytes(data []byte)

ZeroBytes is a convenience function for securely zeroing bytes

Types

type CacheTimingProtection

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

CacheTimingProtection protects against cache timing attacks

func NewCacheTimingProtection

func NewCacheTimingProtection(tableSize int) *CacheTimingProtection

NewCacheTimingProtection creates protection against cache timing attacks

func (*CacheTimingProtection) SecureLookup

func (ctp *CacheTimingProtection) SecureLookup(index int) []byte

SecureLookup performs a lookup that accesses all table entries to prevent cache timing

type EntropyPool

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

EntropyPool provides additional entropy source for critical operations

func NewEntropyPool

func NewEntropyPool(size int) *EntropyPool

NewEntropyPool creates a new entropy pool

func (*EntropyPool) Extract

func (ep *EntropyPool) Extract(size int) ([]byte, error)

Extract extracts random bytes from the entropy pool

func (*EntropyPool) Fill

func (ep *EntropyPool) Fill() error

Fill fills the entropy pool with random data

type OperationMetrics

type OperationMetrics struct {
	Count           int64         `json:"count"`
	SuccessCount    int64         `json:"success_count"`
	FailureCount    int64         `json:"failure_count"`
	TotalDuration   time.Duration `json:"total_duration"`
	AverageDuration time.Duration `json:"average_duration"`
	LastExecution   time.Time     `json:"last_execution"`
}

OperationMetrics tracks metrics for secure operations

type PowerAnalysisProtection

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

PowerAnalysisProtection protects against power analysis attacks

func NewPowerAnalysisProtection

func NewPowerAnalysisProtection(dummyOps int) *PowerAnalysisProtection

NewPowerAnalysisProtection creates protection against power analysis attacks

func (*PowerAnalysisProtection) ProtectedComputation

func (pap *PowerAnalysisProtection) ProtectedComputation(data []byte, computation func([]byte) []byte) []byte

ProtectedComputation performs computation with power analysis protection

type RandomnessTest

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

RandomnessTest performs basic randomness quality tests

func NewRandomnessTest

func NewRandomnessTest(data []byte) *RandomnessTest

NewRandomnessTest creates a new randomness test with sample data

func (*RandomnessTest) FrequencyTest

func (rt *RandomnessTest) FrequencyTest() float64

FrequencyTest performs a basic frequency test for randomness

func (*RandomnessTest) SerialTest

func (rt *RandomnessTest) SerialTest() float64

SerialTest performs a basic serial correlation test

type SecureBuffer

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

SecureBuffer represents a buffer that automatically zeros itself when finalized

func NewSecureBuffer

func NewSecureBuffer(size int) *SecureBuffer

NewSecureBuffer creates a new secure buffer of the specified size

func (*SecureBuffer) Bytes

func (sb *SecureBuffer) Bytes() []byte

Bytes returns the underlying byte slice WARNING: The returned slice should not be stored or used after Finalize() is called

func (*SecureBuffer) ClearFinalizer

func (sb *SecureBuffer) ClearFinalizer()

ClearFinalizer removes the automatic cleanup finalizer

func (*SecureBuffer) Copy

func (sb *SecureBuffer) Copy() []byte

Copy returns a copy of the buffer's contents

func (*SecureBuffer) Finalize

func (sb *SecureBuffer) Finalize()

Finalize securely clears the buffer and marks it as finalized

func (*SecureBuffer) Len

func (sb *SecureBuffer) Len() int

Len returns the length of the buffer

func (*SecureBuffer) SetFinalizer

func (sb *SecureBuffer) SetFinalizer()

SetFinalizer sets up automatic cleanup when the buffer is garbage collected

type SecureComparison

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

SecureComparison provides various secure comparison utilities

func NewSecureComparison

func NewSecureComparison() *SecureComparison

NewSecureComparison creates a new secure comparison instance

func (*SecureComparison) CompareAPIKeys

func (sc *SecureComparison) CompareAPIKeys(expected, actual string) bool

CompareAPIKeys compares API keys securely

func (*SecureComparison) ComparePasswords

func (sc *SecureComparison) ComparePasswords(expected, actual string) bool

ComparePasswords compares passwords securely

func (*SecureComparison) CompareSessionTokens

func (sc *SecureComparison) CompareSessionTokens(expected, actual string) bool

CompareSessionTokens compares session tokens securely

type SecureMemory

type SecureMemory struct{}

SecureMemory provides utilities for secure memory handling in cryptographic operations.

IMPORTANT: Sensitive data (passwords, keys, secrets) MUST be stored as []byte, never string. Go strings are immutable and cannot be securely erased from memory. Always use []byte for sensitive data and call ZeroBytes when done.

Example:

password := []byte("secret123")
defer security.ZeroBytes(password)
// Use password...

func NewSecureMemory

func NewSecureMemory() *SecureMemory

NewSecureMemory creates a new SecureMemory instance

func (*SecureMemory) ConstantTimeCompare

func (s *SecureMemory) ConstantTimeCompare(a, b []byte) int

ConstantTimeCompare compares two byte slices in constant time to prevent timing attacks. Returns 1 if slices are equal, 0 otherwise.

func (*SecureMemory) ConstantTimeCopy

func (s *SecureMemory) ConstantTimeCopy(dst, src []byte) error

ConstantTimeCopy copies data in constant time to prevent timing-based information leakage Returns an error if dst and src have different lengths

func (*SecureMemory) ConstantTimeEq

func (s *SecureMemory) ConstantTimeEq(a, b []byte) bool

ConstantTimeEq compares two byte slices and returns true if they are equal. This is a wrapper around ConstantTimeCompare for convenience.

func (*SecureMemory) ConstantTimeSelect

func (s *SecureMemory) ConstantTimeSelect(condition int, a, b []byte) []byte

ConstantTimeSelect selects between two values based on a condition in constant time. If condition is 1, returns a; if condition is 0, returns b.

func (*SecureMemory) SecureAllocate

func (s *SecureMemory) SecureAllocate(size int) []byte

SecureAllocate allocates memory that will be securely zeroed when freed. Returns a byte slice that should be used for sensitive data.

func (*SecureMemory) SecureCopy

func (s *SecureMemory) SecureCopy(src []byte) []byte

SecureCopy performs a secure copy of sensitive data with automatic cleanup

func (*SecureMemory) SecureRandom

func (s *SecureMemory) SecureRandom(size int) ([]byte, error)

SecureRandom generates cryptographically secure random bytes This is a convenience wrapper that ensures proper random number generation

func (*SecureMemory) ZeroBytes

func (s *SecureMemory) ZeroBytes(data []byte)

ZeroBytes securely zeros a byte slice to prevent sensitive data from lingering in memory. This function overwrites the memory multiple times to ensure data destruction even against advanced forensic techniques.

type SecureOperationTracker

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

SecureOperationTracker tracks sensitive operations for audit purposes

func NewSecureOperationTracker

func NewSecureOperationTracker(auditor *SecurityAuditor) *SecureOperationTracker

NewSecureOperationTracker creates a new operation tracker

func (*SecureOperationTracker) GetAllMetrics

func (sot *SecureOperationTracker) GetAllMetrics() map[string]*OperationMetrics

GetAllMetrics returns metrics for all operations

func (*SecureOperationTracker) GetOperationMetrics

func (sot *SecureOperationTracker) GetOperationMetrics(operation string) *OperationMetrics

GetOperationMetrics returns metrics for a specific operation

func (*SecureOperationTracker) TrackOperation

func (sot *SecureOperationTracker) TrackOperation(ctx context.Context, operation string, fn func() error) error

TrackOperation tracks a secure operation

type SecureRandomGenerator

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

SecureRandomGenerator provides cryptographically secure random number generation

func NewSecureRandomGenerator

func NewSecureRandomGenerator() *SecureRandomGenerator

NewSecureRandomGenerator creates a new secure random generator

func (*SecureRandomGenerator) Generate

func (srg *SecureRandomGenerator) Generate(size int) ([]byte, error)

Generate generates a slice of secure random bytes

func (*SecureRandomGenerator) GenerateKey

func (srg *SecureRandomGenerator) GenerateKey(keySize int) ([]byte, error)

GenerateKey generates a cryptographic key of specified size

func (*SecureRandomGenerator) GenerateNonce

func (srg *SecureRandomGenerator) GenerateNonce(size int) ([]byte, error)

GenerateNonce generates a cryptographically secure nonce

func (*SecureRandomGenerator) GeneratePassword

func (srg *SecureRandomGenerator) GeneratePassword(length int, includeSpecial bool) (string, error)

GeneratePassword generates a secure random password with specified character sets

func (*SecureRandomGenerator) GenerateSalt

func (srg *SecureRandomGenerator) GenerateSalt(size int) ([]byte, error)

GenerateSalt generates a cryptographically secure salt

func (*SecureRandomGenerator) Read

func (srg *SecureRandomGenerator) Read(b []byte) (int, error)

Read generates secure random bytes

type SecureRandomSource

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

SecureRandomSource provides a time-seeded random source for additional entropy

func NewSecureRandomSource

func NewSecureRandomSource() *SecureRandomSource

NewSecureRandomSource creates a new secure random source

func (*SecureRandomSource) Seed

func (srs *SecureRandomSource) Seed() []byte

Seed provides additional entropy based on timing and counter

type SecureSlice

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

SecureSlice is a wrapper around byte slice that provides automatic cleanup

func NewSecureSlice

func NewSecureSlice(size int) *SecureSlice

NewSecureSlice creates a new secure slice of the specified size

func NewSecureSliceFromBytes

func NewSecureSliceFromBytes(data []byte) *SecureSlice

NewSecureSliceFromBytes creates a secure slice from existing bytes

func (*SecureSlice) Bytes

func (ss *SecureSlice) Bytes() []byte

Bytes returns the underlying bytes (use with caution)

func (*SecureSlice) Close

func (ss *SecureSlice) Close() error

Close securely clears the slice and releases resources

func (*SecureSlice) Copy

func (ss *SecureSlice) Copy() []byte

Copy returns a copy of the slice contents

func (*SecureSlice) Len

func (ss *SecureSlice) Len() int

Len returns the length of the slice

type SecureStringComparison

type SecureStringComparison struct{}

SecureStringComparison provides constant-time string comparison utilities

func NewSecureStringComparison

func NewSecureStringComparison() *SecureStringComparison

NewSecureStringComparison creates a new secure string comparison instance

func (*SecureStringComparison) CompareHashes

func (ssc *SecureStringComparison) CompareHashes(expected, actual string) bool

CompareHashes compares two hash values in constant time

func (*SecureStringComparison) CompareStrings

func (ssc *SecureStringComparison) CompareStrings(a, b string) bool

CompareStrings compares two strings in constant time

func (*SecureStringComparison) CompareTokens

func (ssc *SecureStringComparison) CompareTokens(expected, actual string) bool

CompareTokens compares authentication tokens in constant time

type SecurityAuditor

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

SecurityAuditor provides security auditing and monitoring capabilities

func NewSecurityAuditor

func NewSecurityAuditor(maxEvents int) *SecurityAuditor

NewSecurityAuditor creates a new security auditor

func (*SecurityAuditor) GetEvents

func (sa *SecurityAuditor) GetEvents() []SecurityEvent

GetEvents returns all logged events

func (*SecurityAuditor) GetEventsByLevel

func (sa *SecurityAuditor) GetEventsByLevel(level SecurityLevel) []SecurityEvent

GetEventsByLevel returns events filtered by security level

func (*SecurityAuditor) GetEventsByType

func (sa *SecurityAuditor) GetEventsByType(eventType string) []SecurityEvent

GetEventsByType returns events filtered by type

func (*SecurityAuditor) LogAuthenticationEvent

func (sa *SecurityAuditor) LogAuthenticationEvent(userID, operation, outcome string, level SecurityLevel)

LogAuthenticationEvent logs an authentication-related event

func (*SecurityAuditor) LogAuthorizationEvent

func (sa *SecurityAuditor) LogAuthorizationEvent(userID, resource, operation, outcome string, level SecurityLevel)

LogAuthorizationEvent logs an authorization-related event

func (*SecurityAuditor) LogCryptoEvent

func (sa *SecurityAuditor) LogCryptoEvent(operation, outcome string, duration time.Duration, level SecurityLevel)

LogCryptoEvent logs a cryptographic operation event

func (*SecurityAuditor) LogDataAccessEvent

func (sa *SecurityAuditor) LogDataAccessEvent(userID, resource, operation, outcome string, level SecurityLevel)

LogDataAccessEvent logs a data access event

func (*SecurityAuditor) LogEvent

func (sa *SecurityAuditor) LogEvent(event SecurityEvent)

LogEvent logs a security event

func (*SecurityAuditor) LogSecurityViolation

func (sa *SecurityAuditor) LogSecurityViolation(violationType, description string, context map[string]interface{})

LogSecurityViolation logs a security violation

func (*SecurityAuditor) SetEventHandler

func (sa *SecurityAuditor) SetEventHandler(handler func(SecurityEvent))

SetEventHandler sets a custom event handler for security events

type SecurityContext

type SecurityContext struct {
	UserID        string            `json:"user_id"`
	SessionID     string            `json:"session_id"`
	IPAddress     string            `json:"ip_address"`
	UserAgent     string            `json:"user_agent"`
	Permissions   []string          `json:"permissions"`
	SecurityLevel SecurityLevel     `json:"security_level"`
	Metadata      map[string]string `json:"metadata,omitempty"`
	ExpiresAt     time.Time         `json:"expires_at"`
}

SecurityContext provides security context for operations

func (*SecurityContext) HasPermission

func (sc *SecurityContext) HasPermission(permission string) bool

HasPermission checks if the context has a specific permission

func (*SecurityContext) IsExpired

func (sc *SecurityContext) IsExpired() bool

IsExpired checks if the security context has expired

func (*SecurityContext) Validate

func (sc *SecurityContext) Validate() error

Validate validates the security context

type SecurityEvent

type SecurityEvent struct {
	Type       string                 `json:"type"`
	Level      SecurityLevel          `json:"level"`
	Message    string                 `json:"message"`
	Timestamp  time.Time              `json:"timestamp"`
	Context    map[string]interface{} `json:"context,omitempty"`
	StackTrace string                 `json:"stack_trace,omitempty"`
	Source     string                 `json:"source,omitempty"`
	UserID     string                 `json:"user_id,omitempty"`
	SessionID  string                 `json:"session_id,omitempty"`
	IPAddress  string                 `json:"ip_address,omitempty"`
	UserAgent  string                 `json:"user_agent,omitempty"`
	Operation  string                 `json:"operation,omitempty"`
	Resource   string                 `json:"resource,omitempty"`
	Outcome    string                 `json:"outcome,omitempty"`
	Duration   time.Duration          `json:"duration,omitempty"`
}

SecurityEvent represents a security-related event

type SecurityLevel

type SecurityLevel int

SecurityLevel represents the security level for operations

const (
	SecurityLevelLow SecurityLevel = iota
	SecurityLevelMedium
	SecurityLevelHigh
	SecurityLevelCritical
)

func (SecurityLevel) String

func (sl SecurityLevel) String() string

String returns the string representation of the security level

type SecurityValidator

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

SecurityValidator provides various security validation utilities

func NewSecurityValidator

func NewSecurityValidator(auditor *SecurityAuditor) *SecurityValidator

NewSecurityValidator creates a new security validator

func (*SecurityValidator) ValidateKeySize

func (sv *SecurityValidator) ValidateKeySize(keySize int, algorithm string) error

ValidateKeySize validates cryptographic key sizes

func (*SecurityValidator) ValidatePasswordStrength

func (sv *SecurityValidator) ValidatePasswordStrength(password string) error

ValidatePasswordStrength validates password strength

func (*SecurityValidator) ValidateTokenFormat

func (sv *SecurityValidator) ValidateTokenFormat(token string, minLength int) error

ValidateTokenFormat validates token format and entropy

type SideChannelProtection

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

SideChannelProtection provides protection against side-channel attacks

func NewSideChannelProtection

func NewSideChannelProtection() *SideChannelProtection

NewSideChannelProtection creates a new side-channel protection instance

func (*SideChannelProtection) BlindOperation

func (scp *SideChannelProtection) BlindOperation(data []byte, operation func([]byte) ([]byte, error)) ([]byte, error)

BlindOperation performs blinded computation to prevent side-channel attacks

func (*SideChannelProtection) MaskOperation

func (scp *SideChannelProtection) MaskOperation(data []byte, operation func([]byte) []byte) []byte

MaskOperation performs an operation with side-channel masking

type TimingProtection

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

TimingProtection provides utilities to protect against timing attacks

func NewTimingProtection

func NewTimingProtection(baseDelay time.Duration) *TimingProtection

NewTimingProtection creates a new timing protection instance

func (*TimingProtection) ConstantTimeOperation

func (tp *TimingProtection) ConstantTimeOperation(operation func() error) error

ConstantTimeOperation executes an operation in constant time by adding delays

func (*TimingProtection) ConstantTimeSelect

func (tp *TimingProtection) ConstantTimeSelect(condition bool, trueOp, falseOp func() error) error

ConstantTimeSelect selects between two operations based on condition

Jump to

Keyboard shortcuts

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