Documentation
¶
Overview ¶
Package mlabuse provides a machine learning-based abuse detection plugin for Hockeypuck
Index ¶
- Constants
- func GetPlugin() plugin.Plugin
- type AnomalyDetector
- type AnomalyScore
- type BehaviorAnalyzer
- func (ba *BehaviorAnalyzer) AnalyzeRequest(clientIP string, r *http.Request) *BehaviorProfile
- func (ba *BehaviorAnalyzer) CleanupOldProfiles() int
- func (ba *BehaviorAnalyzer) GetProfile(clientIP string) *BehaviorProfile
- func (ba *BehaviorAnalyzer) GetRecentBehaviorData() []BehaviorDataPoint
- func (ba *BehaviorAnalyzer) RecordViolation(clientIP string, reason string)
- func (ba *BehaviorAnalyzer) UpdateProfile(clientIP string, r *http.Request, processingTime time.Duration)
- type BehaviorDataPoint
- type BehaviorProfile
- type CurrentMetrics
- type EntropyMetrics
- type HourlyMetrics
- type IsolationForest
- type IsolationNode
- type IsolationTree
- type LLMDetectionResult
- type LLMPredictor
- type MLAbusePlugin
- func (p *MLAbusePlugin) CreateMiddleware() (func(http.Handler) http.Handler, error)
- func (p *MLAbusePlugin) Dependencies() []plugin.PluginDependency
- func (p *MLAbusePlugin) Description() string
- func (p *MLAbusePlugin) Initialize(ctx context.Context, host plugin.PluginHost, config map[string]interface{}) error
- func (p *MLAbusePlugin) Name() string
- func (p *MLAbusePlugin) Priority() int
- func (p *MLAbusePlugin) RegisterHandlers(host plugin.PluginHost) error
- func (p *MLAbusePlugin) Shutdown(ctx context.Context) error
- func (p *MLAbusePlugin) Version() string
- type MLConfig
- type MetricsCollector
- type PerplexityAnalyzer
- type PromptInjectionScanner
- type SessionPattern
- type TokenPatternAnalyzer
- type ViolationRecord
Constants ¶
const ( PluginName = "ml-abuse-detector" PluginVersion = "1.0.0" Priority = 30 // Run after rate limiting (priority 20) )
Plugin constants
Variables ¶
This section is empty.
Functions ¶
Types ¶
type AnomalyDetector ¶
type AnomalyDetector struct {
// contains filtered or unexported fields
}
AnomalyDetector implements Isolation Forest algorithm for anomaly detection
func NewAnomalyDetector ¶
func NewAnomalyDetector(modelPath string, threshold float64) *AnomalyDetector
NewAnomalyDetector creates a new anomaly detector
func (*AnomalyDetector) DetectAnomaly ¶
func (ad *AnomalyDetector) DetectAnomaly(profile *BehaviorProfile) *AnomalyScore
DetectAnomaly analyzes a behavior profile and returns an anomaly score
func (*AnomalyDetector) LoadModel ¶
func (ad *AnomalyDetector) LoadModel() error
LoadModel loads the trained model from disk
func (*AnomalyDetector) SaveModel ¶
func (ad *AnomalyDetector) SaveModel() error
SaveModel saves the current model to disk
func (*AnomalyDetector) UpdateModel ¶
func (ad *AnomalyDetector) UpdateModel(newData []BehaviorDataPoint) error
UpdateModel performs online learning with new data
type AnomalyScore ¶
type AnomalyScore struct {
Score float64
Confidence float64
AnomalyType string
Reasons []string
Recommendation string
}
AnomalyScore represents the ML model output
type BehaviorAnalyzer ¶
type BehaviorAnalyzer struct {
// contains filtered or unexported fields
}
BehaviorAnalyzer analyzes request patterns and builds behavioral profiles
func NewBehaviorAnalyzer ¶
func NewBehaviorAnalyzer(windowSize int) *BehaviorAnalyzer
NewBehaviorAnalyzer creates a new behavior analyzer
func (*BehaviorAnalyzer) AnalyzeRequest ¶
func (ba *BehaviorAnalyzer) AnalyzeRequest(clientIP string, r *http.Request) *BehaviorProfile
AnalyzeRequest analyzes an incoming request and returns a behavior profile
func (*BehaviorAnalyzer) CleanupOldProfiles ¶
func (ba *BehaviorAnalyzer) CleanupOldProfiles() int
CleanupOldProfiles removes stale behavior profiles
func (*BehaviorAnalyzer) GetProfile ¶
func (ba *BehaviorAnalyzer) GetProfile(clientIP string) *BehaviorProfile
GetProfile returns the behavior profile for a client
func (*BehaviorAnalyzer) GetRecentBehaviorData ¶
func (ba *BehaviorAnalyzer) GetRecentBehaviorData() []BehaviorDataPoint
GetRecentBehaviorData returns recent behavior data for model updates
func (*BehaviorAnalyzer) RecordViolation ¶
func (ba *BehaviorAnalyzer) RecordViolation(clientIP string, reason string)
RecordViolation records a rate limit violation for the client
func (*BehaviorAnalyzer) UpdateProfile ¶
func (ba *BehaviorAnalyzer) UpdateProfile(clientIP string, r *http.Request, processingTime time.Duration)
UpdateProfile updates the behavior profile after request processing
type BehaviorDataPoint ¶
type BehaviorDataPoint struct {
Features []float64
Label bool // true if abusive
Weight float64 // importance weight
}
BehaviorDataPoint represents a training data point
type BehaviorProfile ¶
type BehaviorProfile struct {
ClientIP string
RequestIntervals []time.Duration
PathSequences []string
UserAgentRotation []string
PayloadSimilarity float64
TLSFingerprint string
SessionBehavior SessionPattern
EntropyMetrics EntropyMetrics
LastUpdated time.Time
}
BehaviorProfile represents a client's behavioral pattern
type CurrentMetrics ¶
type CurrentMetrics struct {
TotalRequests int64 `json:"total_requests"`
BlockedRequests int64 `json:"blocked_requests"`
BlockRate float64 `json:"block_rate"`
AnomalyDetections map[string]int64 `json:"anomaly_detections"`
LLMDetections int64 `json:"llm_detections"`
InjectionAttempts int64 `json:"injection_attempts"`
AvgAnomalyScore float64 `json:"avg_anomaly_score"`
AvgSyntheticScore float64 `json:"avg_synthetic_score"`
HourlyStats []HourlyMetrics `json:"hourly_stats"`
Uptime string `json:"uptime"`
}
CurrentMetrics represents the current state of metrics
type EntropyMetrics ¶
type EntropyMetrics struct {
TimingEntropy float64
PathEntropy float64
ParameterEntropy float64
OverallScore float64
}
EntropyMetrics measures randomness in behavior
type HourlyMetrics ¶
type HourlyMetrics struct {
Hour int
Requests int64
Blocked int64
AnomaliesDetected int64
LLMDetected int64
AvgAnomalyScore float64
}
HourlyMetrics represents metrics for a specific hour
type IsolationForest ¶
type IsolationForest struct {
Trees []*IsolationTree
NumTrees int
SampleSize int
MaxDepth int
FeatureNames []string
AnomalyScores map[string]float64 // Cache for recent scores
}
IsolationForest represents the ensemble of isolation trees
func (*IsolationForest) AnomalyScore ¶
func (f *IsolationForest) AnomalyScore(sample []float64) float64
AnomalyScore calculates the anomaly score for a sample
func (*IsolationForest) Train ¶
func (f *IsolationForest) Train(data [][]float64)
Train trains the Isolation Forest on the provided data
type IsolationNode ¶
type IsolationNode struct {
IsLeaf bool
SplitFeature int
SplitValue float64
Left *IsolationNode
Right *IsolationNode
Size int // Number of samples at this node
}
IsolationNode represents a node in the isolation tree
type IsolationTree ¶
type IsolationTree struct {
Root *IsolationNode
PathLength map[string]float64
}
IsolationTree represents a single tree in the forest
type LLMDetectionResult ¶
type LLMDetectionResult struct {
IsAIGenerated bool
Perplexity float64
TokenPatterns []string
SyntheticScore float64
PromptInjection bool
}
LLMDetectionResult represents LLM/AI-generated content detection
type LLMPredictor ¶
type LLMPredictor struct {
// contains filtered or unexported fields
}
LLMPredictor detects LLM/AI-generated content and prompt injection attempts
func NewLLMPredictor ¶
func NewLLMPredictor(threshold float64) *LLMPredictor
NewLLMPredictor creates a new LLM content predictor
func (*LLMPredictor) AnalyzeText ¶
func (p *LLMPredictor) AnalyzeText(text string) *LLMDetectionResult
AnalyzeText analyzes the provided text for LLM/AI-generated content
func (*LLMPredictor) DetectLLMContent ¶
func (p *LLMPredictor) DetectLLMContent(r *http.Request) *LLMDetectionResult
DetectLLMContent analyzes HTTP request for AI-generated content
type MLAbusePlugin ¶
type MLAbusePlugin struct {
// contains filtered or unexported fields
}
MLAbusePlugin implements machine learning-based abuse detection
func (*MLAbusePlugin) CreateMiddleware ¶
CreateMiddleware creates the ML abuse detection middleware
func (*MLAbusePlugin) Dependencies ¶
func (p *MLAbusePlugin) Dependencies() []plugin.PluginDependency
Dependencies returns required plugin dependencies
func (*MLAbusePlugin) Description ¶
func (p *MLAbusePlugin) Description() string
Description returns the plugin description
func (*MLAbusePlugin) Initialize ¶
func (p *MLAbusePlugin) Initialize(ctx context.Context, host plugin.PluginHost, config map[string]interface{}) error
Initialize implements the Plugin interface
func (*MLAbusePlugin) Priority ¶
func (p *MLAbusePlugin) Priority() int
Priority returns the plugin priority (higher numbers run later)
func (*MLAbusePlugin) RegisterHandlers ¶
func (p *MLAbusePlugin) RegisterHandlers(host plugin.PluginHost) error
RegisterHandlers registers the plugin's HTTP handlers
func (*MLAbusePlugin) Shutdown ¶
func (p *MLAbusePlugin) Shutdown(ctx context.Context) error
Shutdown gracefully stops the plugin
func (*MLAbusePlugin) Version ¶
func (p *MLAbusePlugin) Version() string
Version returns the plugin version
type MLConfig ¶
type MLConfig struct {
Enabled bool `json:"enabled"`
ModelPath string `json:"modelPath"`
AnomalyThreshold float64 `json:"anomalyThreshold"`
BehaviorWindowSize int `json:"behaviorWindowSize"`
UpdateInterval string `json:"updateInterval"`
LLMDetection bool `json:"llmDetection"`
SyntheticThreshold float64 `json:"syntheticThreshold"`
MaxMemoryMB int `json:"maxMemoryMB"`
EnableRealtimeUpdate bool `json:"enableRealtimeUpdate"`
}
MLConfig holds the plugin configuration
type MetricsCollector ¶
type MetricsCollector struct {
// contains filtered or unexported fields
}
MetricsCollector collects and aggregates ML detection metrics
func NewMetricsCollector ¶
func NewMetricsCollector() *MetricsCollector
NewMetricsCollector creates a new metrics collector
func (*MetricsCollector) GetCurrentMetrics ¶
func (mc *MetricsCollector) GetCurrentMetrics() CurrentMetrics
GetCurrentMetrics returns current metrics snapshot
func (*MetricsCollector) RecordRequest ¶
func (mc *MetricsCollector) RecordRequest(clientIP string, anomaly *AnomalyScore, llm *LLMDetectionResult, blocked bool)
RecordRequest records metrics for a request
func (*MetricsCollector) ReportStatistics ¶
func (mc *MetricsCollector) ReportStatistics()
ReportStatistics logs current statistics
type PerplexityAnalyzer ¶
type PerplexityAnalyzer struct {
// contains filtered or unexported fields
}
PerplexityAnalyzer calculates text perplexity for AI detection
type PromptInjectionScanner ¶
type PromptInjectionScanner struct {
// contains filtered or unexported fields
}
PromptInjectionScanner detects prompt injection attempts
type SessionPattern ¶
type SessionPattern struct {
SessionDuration time.Duration
RequestCount int
UniquePathsCount int
ErrorRate float64
BytesTransferred int64
KeyOperationRatio float64 // ratio of key operations to total requests
}
SessionPattern tracks session-level behavioral analysis
type TokenPatternAnalyzer ¶
type TokenPatternAnalyzer struct {
// contains filtered or unexported fields
}
TokenPatternAnalyzer detects AI-specific token patterns