Documentation
¶
Index ¶
- func ExportQuick(ctx context.Context, filter QueryFilter, format ExportFormat, writer io.Writer) error
- func Init(config Config) error
- func IsTorExitNode(ip string) bool
- func RecordQuick(event *Event) error
- func SetDefault(auditor *Auditor)
- type ActionInfo
- type ActorInfo
- type AnomalyDetector
- type Auditor
- func (a *Auditor) Close() error
- func (a *Auditor) Count(ctx context.Context, filter QueryFilter) (int64, error)
- func (a *Auditor) Export(ctx context.Context, filter QueryFilter, format ExportFormat, writer io.Writer) error
- func (a *Auditor) GetByID(ctx context.Context, id string) (*Event, error)
- func (a *Auditor) GetStats() Stats
- func (a *Auditor) Query(ctx context.Context, filter QueryFilter) ([]*Event, error)
- func (a *Auditor) Record(event *Event) error
- func (a *Auditor) RecordAsync(event *Event) error
- type BehaviorProfile
- type ClientInfo
- type Config
- type ContextInfo
- type DetectionRule
- type Event
- type EventQuerier
- type ExportFormat
- type GeoLocation
- type IAEngine
- type IAStats
- type IPReputation
- type IPReputationDB
- type MemoryStorage
- func (s *MemoryStorage) Close() error
- func (s *MemoryStorage) Count(ctx context.Context, filter QueryFilter) (int64, error)
- func (s *MemoryStorage) DeleteOlderThan(ctx context.Context, timestamp time.Time) (int64, error)
- func (s *MemoryStorage) Export(ctx context.Context, filter QueryFilter, format ExportFormat, writer io.Writer) error
- func (s *MemoryStorage) GetByID(ctx context.Context, id string) (*Event, error)
- func (s *MemoryStorage) Query(ctx context.Context, filter QueryFilter) ([]*Event, error)
- func (s *MemoryStorage) Save(ctx context.Context, event *Event) error
- func (s *MemoryStorage) SaveBatch(ctx context.Context, events []*Event) error
- type PostgresConfig
- type PostgresStorage
- func (s *PostgresStorage) Close() error
- func (s *PostgresStorage) Count(ctx context.Context, filter QueryFilter) (int64, error)
- func (s *PostgresStorage) DeleteOlderThan(ctx context.Context, timestamp time.Time) (int64, error)
- func (s *PostgresStorage) Export(ctx context.Context, filter QueryFilter, format ExportFormat, writer io.Writer) error
- func (s *PostgresStorage) GetByID(ctx context.Context, id string) (*Event, error)
- func (s *PostgresStorage) Query(ctx context.Context, filter QueryFilter) ([]*Event, error)
- func (s *PostgresStorage) Save(ctx context.Context, event *Event) error
- func (s *PostgresStorage) SaveBatch(ctx context.Context, events []*Event) error
- type QueryFilter
- type ResourceInfo
- type ResultInfo
- type RetentionPolicy
- type SQLiteConfig
- type SQLiteStorage
- func (s *SQLiteStorage) Close() error
- func (s *SQLiteStorage) Count(ctx context.Context, filter QueryFilter) (int64, error)
- func (s *SQLiteStorage) DeleteOlderThan(ctx context.Context, timestamp time.Time) (int64, error)
- func (s *SQLiteStorage) Export(ctx context.Context, filter QueryFilter, format ExportFormat, writer io.Writer) error
- func (s *SQLiteStorage) GetByID(ctx context.Context, id string) (*Event, error)
- func (s *SQLiteStorage) Query(ctx context.Context, filter QueryFilter) ([]*Event, error)
- func (s *SQLiteStorage) Save(ctx context.Context, event *Event) error
- func (s *SQLiteStorage) SaveBatch(ctx context.Context, events []*Event) error
- type Stats
- type Storage
- type ThreatDetection
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ExportQuick ¶
func ExportQuick(ctx context.Context, filter QueryFilter, format ExportFormat, writer io.Writer) error
ExportQuick exporta eventos usando el auditor global
func IsTorExitNode ¶
IsTorExitNode verifica si la IP es un exit node conocido de Tor
func RecordQuick ¶
RecordQuick registra un evento de auditoría rápidamente usando el auditor global
Types ¶
type ActionInfo ¶
type ActionInfo struct {
Type string `json:"type"` // Tipo de acción: CREATE, UPDATE, DELETE, LOGIN, LOGOUT, etc.
Category string `json:"category"` // Categoría: AUTH, DATA, SYSTEM, SECURITY, AUDIT
Description string `json:"description"` // Descripción legible
Method string `json:"method,omitempty"` // Método HTTP si aplica
Path string `json:"path,omitempty"` // Ruta/Path accedido
Endpoint string `json:"endpoint,omitempty"` // Endpoint completo
}
ActionInfo contiene información detallada de la acción
type ActorInfo ¶
type ActorInfo struct {
ID string `json:"id,omitempty"` // ID del usuario/actor
Email string `json:"email,omitempty"` // Email del usuario
Username string `json:"username,omitempty"` // Username
Role string `json:"role,omitempty"` // Rol del usuario
SessionID string `json:"session_id,omitempty"` // ID de sesión
Type string `json:"type"` // Tipo: user, system, api, anonymous
}
ActorInfo contiene información completa del actor
type AnomalyDetector ¶
type AnomalyDetector struct {
// contains filtered or unexported fields
}
AnomalyDetector detecta comportamientos anómalos usando análisis estadístico
type Auditor ¶
type Auditor struct {
// contains filtered or unexported fields
}
Auditor es la estructura principal del sistema de auditoría
func NewAuditor ¶
NewAuditor crea una nueva instancia de Auditor
func (*Auditor) Export ¶
func (a *Auditor) Export(ctx context.Context, filter QueryFilter, format ExportFormat, writer io.Writer) error
Export exporta eventos a un formato específico
func (*Auditor) RecordAsync ¶
RecordAsync registra un evento de auditoría de forma asíncrona
type BehaviorProfile ¶
type BehaviorProfile struct {
ActorID string `json:"actor_id"`
AverageRequestsPerMinute float64 `json:"avg_requests_per_minute"`
AverageSessionDuration time.Duration `json:"avg_session_duration"`
CommonIPs []string `json:"common_ips"`
CommonLocations []string `json:"common_locations"`
TypicalActions []string `json:"typical_actions"`
ActiveHours []int `json:"active_hours"` // Horas típicas de actividad (0-23)
Devices []string `json:"devices"`
LastUpdated time.Time `json:"last_updated"`
RiskBaseline float64 `json:"risk_baseline"`
}
BehaviorProfile contiene el perfil de comportamiento de un actor
type ClientInfo ¶
type ClientInfo struct {
Browser string `json:"browser,omitempty"`
BrowserVer string `json:"browser_version,omitempty"`
OS string `json:"os,omitempty"`
OSVer string `json:"os_version,omitempty"`
Device string `json:"device,omitempty"`
DeviceType string `json:"device_type,omitempty"` // desktop, mobile, tablet, bot
IsBot bool `json:"is_bot"`
IsMobile bool `json:"is_mobile"`
IsTablet bool `json:"is_tablet"`
}
ClientInfo contiene información del cliente parseada
type Config ¶
type Config struct {
StorageType string `json:"storage_type"` // memory, sqlite, postgres
StorageConfig interface{} `json:"storage_config"` // Configuración específica del storage
EnableIA bool `json:"enable_ia"` // Habilitar motor de IA
IAMinRiskThreshold float64 `json:"ia_min_risk_threshold"` // Threshold mínimo para alertas
EnableAsync bool `json:"enable_async"` // Procesamiento asíncrono
AsyncBufferSize int `json:"async_buffer_size"` // Buffer size para procesamiento asíncrono
Retention RetentionPolicy `json:"retention"` // Política de retención
EnableEncryption bool `json:"enable_encryption"` // Cifrar datos en reposo
EncryptionKey string `json:"encryption_key,omitempty"` // Clave de cifrado
LogLevel string `json:"log_level"` // Nivel de log para auditoría
IncludePayload bool `json:"include_payload"` // Incluir payload completo
MaxPayloadSize int64 `json:"max_payload_size"` // Tamaño máximo de payload a guardar
SanitizePII bool `json:"sanitize_pii"` // Sanitizar información personal
}
Config contiene la configuración completa del sistema de auditoría
type ContextInfo ¶
type ContextInfo struct {
IPAddress string `json:"ip_address"` // IP del cliente
IPGeoLocation GeoLocation `json:"ip_geo_location"` // Geolocalización de la IP
UserAgent string `json:"user_agent"` // User-Agent completo
ClientInfo ClientInfo `json:"client_info"` // Información del cliente parseada
Referer string `json:"referer,omitempty"` // Referer header
ForwardedFor string `json:"forwarded_for,omitempty"` // X-Forwarded-For
RequestID string `json:"request_id"` // Request ID único
TraceID string `json:"trace_id,omitempty"` // Trace ID para distributed tracing
SpanID string `json:"span_id,omitempty"` // Span ID para distributed tracing
Headers map[string]string `json:"headers,omitempty"` // Headers de la petición
PayloadSize int64 `json:"payload_size,omitempty"` // Tamaño del payload
PayloadHash string `json:"payload_hash,omitempty"` // Hash del payload para integridad
TLSVersion string `json:"tls_version,omitempty"` // Versión TLS si usa HTTPS
ServerPort int `json:"server_port,omitempty"` // Puerto del servidor
}
ContextInfo contiene contexto completo de la petición
type DetectionRule ¶
type DetectionRule struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Severity string `json:"severity"`
Pattern *regexp.Regexp `json:"pattern,omitempty"`
Condition func(event *Event) bool `json:"-"` // Función personalizada de condición
Action func(event *Event) *ThreatDetection `json:"-"` // Acción a tomar cuando se detecta
Enabled bool `json:"enabled"`
Hits int64 `json:"hits"`
LastHit time.Time `json:"last_hit,omitempty"`
}
DetectionRule define una regla de detección de amenazas
type Event ¶
type Event struct {
ID string `json:"id"` // UUID único del evento
Timestamp time.Time `json:"timestamp"` // Timestamp del evento
Actor ActorInfo `json:"actor"` // Información del actor
Action ActionInfo `json:"action"` // Información de la acción
Resource ResourceInfo `json:"resource"` // Información del recurso
Result ResultInfo `json:"result"` // Resultado de la acción
Context ContextInfo `json:"context"` // Contexto de la petición
Metadata map[string]interface{} `json:"metadata,omitempty"` // Metadata adicional flexible
RiskScore float64 `json:"risk_score"` // Score de riesgo calculado por IA
Threats []ThreatDetection `json:"threats,omitempty"` // Amenazas detectadas
DigitalFingerprint string `json:"digital_fingerprint"` // Huella digital inmutable
}
Event representa un evento de auditoría completo con todos los metadatos necesarios
func QueryQuick ¶
func QueryQuick(ctx context.Context, filter QueryFilter) ([]*Event, error)
QueryQuick consulta eventos usando el auditor global
type EventQuerier ¶
type EventQuerier func(ctx context.Context, filter QueryFilter) ([]*Event, error)
EventQuerier consulta eventos almacenados para la detección de amenazas. El auditor inyecta su storage.Query para que el motor no dependa de un storage concreto.
type ExportFormat ¶
type ExportFormat string
ExportFormat define formatos de exportación
const ( ExportFormatJSON ExportFormat = "json" ExportFormatCSV ExportFormat = "csv" ExportFormatNDJSON ExportFormat = "ndjson" )
type GeoLocation ¶
type GeoLocation struct {
Country string `json:"country,omitempty"`
CountryCode string `json:"country_code,omitempty"`
Region string `json:"region,omitempty"`
City string `json:"city,omitempty"`
Latitude float64 `json:"latitude,omitempty"`
Longitude float64 `json:"longitude,omitempty"`
Timezone string `json:"timezone,omitempty"`
ISP string `json:"isp,omitempty"`
Org string `json:"org,omitempty"`
AS string `json:"as,omitempty"`
}
GeoLocation contiene información geográfica
func LookupGeoIP ¶
func LookupGeoIP(ip string) GeoLocation
LookupGeoIP realiza una búsqueda GeoIP simplificada
type IAEngine ¶
type IAEngine struct {
// contains filtered or unexported fields
}
IAEngine es el motor de inteligencia artificial para detección de amenazas
func NewIAEngine ¶
func NewIAEngine(minRiskThreshold float64, history EventQuerier) *IAEngine
NewIAEngine crea un nuevo motor de IA para detección de amenazas
func (*IAEngine) AddRule ¶
func (e *IAEngine) AddRule(rule DetectionRule)
AddRule agrega una regla personalizada
func (*IAEngine) Analyze ¶
func (e *IAEngine) Analyze(event *Event) ([]ThreatDetection, float64)
Analyze analiza un evento y retorna amenazas detectadas y score de riesgo
func (*IAEngine) LoadDefaultRules ¶
func (e *IAEngine) LoadDefaultRules()
LoadDefaultRules carga las reglas de detección por defecto
func (*IAEngine) RemoveRule ¶
RemoveRule elimina una regla por ID
type IAStats ¶
type IAStats struct {
TotalEvaluations int64 `json:"total_evaluations"`
ThreatsDetected int64 `json:"threats_detected"`
FalsePositives int64 `json:"false_positives"`
TruePositives int64 `json:"true_positives"`
AverageConfidence float64 `json:"average_confidence"`
DetectionByType map[string]int64 `json:"detection_by_type"`
LastEvaluationTime time.Time `json:"last_evaluation_time"`
}
IAStats contiene estadísticas del motor de IA
type IPReputation ¶
type IPReputation struct {
IPAddress string `json:"ip_address"`
RiskScore float64 `json:"risk_score"`
IsTor bool `json:"is_tor"`
IsProxy bool `json:"is_proxy"`
IsVPN bool `json:"is_vpn"`
IsHosting bool `json:"is_hosting"`
IsMalicious bool `json:"is_malicious"`
AbuseReports int `json:"abuse_reports"`
Blacklisted bool `json:"blacklisted"`
Categories []string `json:"categories"`
LastSeen time.Time `json:"last_seen"`
FirstSeen time.Time `json:"first_seen"`
}
IPReputation contiene información de reputación de una IP
type IPReputationDB ¶
type IPReputationDB struct {
// contains filtered or unexported fields
}
IPReputationDB es una base de datos de reputación de IPs
func (*IPReputationDB) Get ¶
func (db *IPReputationDB) Get(ip string) *IPReputation
Get retorna la reputación de una IP
func (*IPReputationDB) MarkAsMalicious ¶
func (db *IPReputationDB) MarkAsMalicious(ip string, reason string)
MarkAsMalicious marca una IP como maliciosa
func (*IPReputationDB) Update ¶
func (db *IPReputationDB) Update(rep *IPReputation)
Update actualiza la reputación de una IP
type MemoryStorage ¶
type MemoryStorage struct {
// contains filtered or unexported fields
}
MemoryStorage implementa Storage usando memoria RAM (ideal para tests)
func NewMemoryStorage ¶
func NewMemoryStorage() *MemoryStorage
NewMemoryStorage crea un nuevo storage en memoria
func (*MemoryStorage) Close ¶
func (s *MemoryStorage) Close() error
Close cierra el storage (limpia memoria)
func (*MemoryStorage) Count ¶
func (s *MemoryStorage) Count(ctx context.Context, filter QueryFilter) (int64, error)
Count cuenta eventos que coinciden con los filtros
func (*MemoryStorage) DeleteOlderThan ¶
DeleteOlderThan elimina eventos anteriores a una fecha
func (*MemoryStorage) Export ¶
func (s *MemoryStorage) Export(ctx context.Context, filter QueryFilter, format ExportFormat, writer io.Writer) error
Export exporta eventos a un formato específico
func (*MemoryStorage) Query ¶
func (s *MemoryStorage) Query(ctx context.Context, filter QueryFilter) ([]*Event, error)
Query consulta eventos con filtros
type PostgresConfig ¶
type PostgresConfig struct {
DSN string `json:"dsn"` // Cadena de conexión completa (opcional)
Host string `json:"host"`
Port int `json:"port"`
Database string `json:"database"`
User string `json:"user"`
Password string `json:"password"`
SSLMode string `json:"ssl_mode"`
MaxOpenConns int `json:"max_open_conns"`
MaxIdleConns int `json:"max_idle_conns"`
MaxLifetime int `json:"max_lifetime"`
}
PostgresConfig configura la conexión a PostgreSQL
type PostgresStorage ¶
type PostgresStorage struct {
// contains filtered or unexported fields
}
PostgresStorage implementa Storage usando PostgreSQL
func NewPostgresStorage ¶
func NewPostgresStorage(config PostgresConfig) (*PostgresStorage, error)
NewPostgresStorage crea un nuevo storage PostgreSQL
func (*PostgresStorage) Close ¶
func (s *PostgresStorage) Close() error
Close cierra la conexión a la base de datos
func (*PostgresStorage) Count ¶
func (s *PostgresStorage) Count(ctx context.Context, filter QueryFilter) (int64, error)
Count cuenta eventos que coinciden con los filtros
func (*PostgresStorage) DeleteOlderThan ¶
DeleteOlderThan elimina eventos anteriores a una fecha
func (*PostgresStorage) Export ¶
func (s *PostgresStorage) Export(ctx context.Context, filter QueryFilter, format ExportFormat, writer io.Writer) error
Export exporta eventos a un formato específico
func (*PostgresStorage) Query ¶
func (s *PostgresStorage) Query(ctx context.Context, filter QueryFilter) ([]*Event, error)
Query consulta eventos con filtros
type QueryFilter ¶
type QueryFilter struct {
EventIDs []string `json:"event_ids,omitempty"`
ActorIDs []string `json:"actor_ids,omitempty"`
ActorTypes []string `json:"actor_types,omitempty"`
ActionTypes []string `json:"action_types,omitempty"`
ActionCategories []string `json:"action_categories,omitempty"`
ResourceTypes []string `json:"resource_types,omitempty"`
ResourceIDs []string `json:"resource_ids,omitempty"`
Statuses []string `json:"statuses,omitempty"`
IPAddresses []string `json:"ip_addresses,omitempty"`
SessionIDs []string `json:"session_ids,omitempty"`
ThreatTypes []string `json:"threat_types,omitempty"`
MinRiskScore float64 `json:"min_risk_score,omitempty"`
StartTime time.Time `json:"start_time,omitempty"`
EndTime time.Time `json:"end_time,omitempty"`
SearchQuery string `json:"search_query,omitempty"` // Búsqueda full-text
Limit int `json:"limit"`
Offset int `json:"offset"`
SortBy string `json:"sort_by"` // timestamp, risk_score, etc.
SortOrder string `json:"sort_order"` // asc, desc
}
QueryFilter define filtros para consultas de auditoría
type ResourceInfo ¶
type ResourceInfo struct {
Type string `json:"type"` // Tipo de recurso: user, post, file, config, etc.
ID string `json:"id,omitempty"` // ID del recurso
Name string `json:"name,omitempty"` // Nombre del recurso
Collection string `json:"collection,omitempty"` // Colección/tabla
Tenant string `json:"tenant,omitempty"` // Tenant/Multi-tenancy
}
ResourceInfo contiene información del recurso afectado
type ResultInfo ¶
type ResultInfo struct {
Status string `json:"status"` // Status: SUCCESS, FAILURE, PARTIAL
StatusCode int `json:"status_code"` // Código HTTP o status code
Message string `json:"message,omitempty"` // Mensaje descriptivo
Error string `json:"error,omitempty"` // Error si falló
Duration int64 `json:"duration_ms"` // Duración en milisegundos
ChangesCount int `json:"changes_count,omitempty"` // Cantidad de cambios realizados
}
ResultInfo contiene información del resultado
type RetentionPolicy ¶
type RetentionPolicy struct {
MaxAgeDays int `json:"max_age_days"` // Edad máxima en días
MaxEvents int64 `json:"max_events"` // Máximo número de eventos
CompressAfterDays int `json:"compress_after_days"` // Comprimir después de X días
ArchiveAfterDays int `json:"archive_after_days"` // Archivar después de X días
EnableAutoDelete bool `json:"enable_auto_delete"` // Habilitar eliminación automática
}
RetentionPolicy define políticas de retención de logs
type SQLiteConfig ¶
type SQLiteConfig struct {
DSN string `json:"dsn"` // Path al archivo SQLite (o ":memory:")
MaxOpenConns int `json:"max_open_conns"` // Máximas conexiones abiertas
MaxIdleConns int `json:"max_idle_conns"` // Máximas conexiones idle
MaxLifetime int `json:"max_lifetime"` // Máximo tiempo de vida de conexión (segundos)
}
SQLiteConfig configura la conexión a SQLite
type SQLiteStorage ¶
type SQLiteStorage struct {
// contains filtered or unexported fields
}
SQLiteStorage implementa Storage usando SQLite (driver modernc.org/sqlite, sin CGO)
func NewSQLiteStorage ¶
func NewSQLiteStorage(config SQLiteConfig) (*SQLiteStorage, error)
NewSQLiteStorage crea un nuevo storage SQLite
func (*SQLiteStorage) Close ¶
func (s *SQLiteStorage) Close() error
Close cierra la conexión a la base de datos
func (*SQLiteStorage) Count ¶
func (s *SQLiteStorage) Count(ctx context.Context, filter QueryFilter) (int64, error)
Count cuenta eventos que coinciden con los filtros
func (*SQLiteStorage) DeleteOlderThan ¶
DeleteOlderThan elimina eventos anteriores a una fecha
func (*SQLiteStorage) Export ¶
func (s *SQLiteStorage) Export(ctx context.Context, filter QueryFilter, format ExportFormat, writer io.Writer) error
Export exporta eventos a un formato específico
func (*SQLiteStorage) Query ¶
func (s *SQLiteStorage) Query(ctx context.Context, filter QueryFilter) ([]*Event, error)
Query consulta eventos con filtros
type Stats ¶
type Stats struct {
TotalEvents int64 `json:"total_events"`
EventsLastHour int64 `json:"events_last_hour"`
EventsLastDay int64 `json:"events_last_day"`
ThreatsDetected int64 `json:"threats_detected"`
AverageRiskScore float64 `json:"average_risk_score"`
LastEventTime time.Time `json:"last_event_time"`
Uptime time.Duration `json:"uptime"`
}
Stats contiene estadísticas del sistema de auditoría
type Storage ¶
type Storage interface {
Save(ctx context.Context, event *Event) error
SaveBatch(ctx context.Context, events []*Event) error
GetByID(ctx context.Context, id string) (*Event, error)
Query(ctx context.Context, filter QueryFilter) ([]*Event, error)
Count(ctx context.Context, filter QueryFilter) (int64, error)
DeleteOlderThan(ctx context.Context, timestamp time.Time) (int64, error)
Export(ctx context.Context, filter QueryFilter, format ExportFormat, writer io.Writer) error
Close() error
}
Storage define la interfaz para almacenamiento de eventos de auditoría
type ThreatDetection ¶
type ThreatDetection struct {
Type string `json:"type"` // Tipo de amenaza: BRUTE_FORCE, SQL_INJECTION, XSS, SCRAPING, etc.
Severity string `json:"severity"` // Severidad: LOW, MEDIUM, HIGH, CRITICAL
Confidence float64 `json:"confidence"` // Confianza de la detección (0-1)
Description string `json:"description"` // Descripción de la amenaza
Evidence []string `json:"evidence"` // Evidencias que soportan la detección
RuleID string `json:"rule_id"` // ID de la regla que detectó la amenaza
Pattern string `json:"pattern,omitempty"` // Patrón detectado
Recommendation string `json:"recommendation"` // Recomendación de mitigación
}
ThreatDetection contiene información de amenazas detectadas por IA