security

package
v0.4.0-beta.3 Latest Latest
Warning

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

Go to latest
Published: Aug 5, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EventTypeUnauthorizedAccess = "unauthorized_access"
	EventTypeForbiddenAccess    = "forbidden_access"
	EventTypeNotFoundProbe      = "not_found_probe"
	EventTypeServerError        = "server_error"
	EventTypeRateLimitExceeded  = "rate_limit_exceeded"
	EventTypeSuspiciousPath     = "suspicious_path"
	EventTypeHighRequestRate    = "high_request_rate"
	EventTypeScannerDetected    = "scanner_detected"
)

Event types

View Source
const (
	SeverityLow      = "low"
	SeverityMedium   = "medium"
	SeverityHigh     = "high"
	SeverityCritical = "critical"
)

Severity levels

View Source
const LuaSecurityScript = `` /* 2870-byte string literal not displayed */

LuaSecurityScript is the Lua script template for real-time security event capture

Variables

View Source
var ScannerUserAgents = []string{
	"nikto",
	"nmap",
	"sqlmap",
	"dirbuster",
	"dirb",
	"gobuster",
	"nuclei",
	"masscan",
	"wpscan",
	"burp",
	"acunetix",
	"nessus",
	"openvas",
	"w3af",
	"arachni",
	"skipfish",
	"whatweb",
	"joomscan",
	"droopescan",
	"zgrab",
}

ScannerUserAgents match on sight and block immediately, so this list holds only attack tools that name themselves. General-purpose HTTP clients (curl, wget, python-requests, go-http-client) are deliberately absent: real scripts and health checks use them, so matching them here blocked legitimate callers on their first request. They are still caught by the volumetric thresholds.

View Source
var SuspiciousPaths = []string{

	"/wp-admin",
	"/wp-login.php",
	"/wp-config.php",
	"/wp-content/uploads",
	"/wp-includes",
	"/xmlrpc.php",
	"/wp-json/wp/v2/users",

	"/.env",
	"/.env.local",
	"/.env.production",
	"/.env.backup",
	"/config.php",
	"/configuration.php",
	"/settings.php",
	"/local.xml",
	"/app/etc/local.xml",

	"/.git",
	"/.git/config",
	"/.git/HEAD",
	"/.gitignore",
	"/.svn",
	"/.hg",

	"/composer.json",
	"/composer.lock",
	"/package.json",
	"/yarn.lock",
	"/Gemfile",
	"/requirements.txt",

	"/phpMyAdmin",
	"/phpmyadmin",
	"/pma",
	"/myadmin",
	"/mysql",
	"/adminer.php",
	"/adminer",

	"/admin",
	"/administrator",
	"/admin.php",
	"/manager",
	"/cpanel",
	"/webadmin",
	"/controlpanel",

	"/shell",
	"/cmd",
	"/c99",
	"/r57",
	"/shell.php",
	"/cmd.php",
	"/backdoor",
	"/webshell",

	"/.aws",
	"/.aws/credentials",
	"/.ssh",
	"/.ssh/id_rsa",
	"/.docker",
	"/docker-compose.yml",
	"/.kube/config",

	"/actuator",
	"/actuator/env",
	"/actuator/health",
	"/api/swagger",
	"/swagger.json",
	"/swagger-ui",
	"/api-docs",
	"/.well-known/security.txt",
	"/debug",
	"/trace",
	"/server-status",
	"/server-info",

	"/.bak",
	"/.backup",
	"/.old",
	"/backup.sql",
	"/database.sql",
	"/dump.sql",
	"/db.sql",

	"/storage/logs",
	"/.env.example",
	"/artisan",

	"/sites/default/settings.php",
	"/typo3conf",
	"/fileadmin",
	"/magento",

	"/.htaccess",
	"/.htpasswd",
	"/web.config",
	"/crossdomain.xml",
	"/clientaccesspolicy.xml",
}

Suspicious paths that are commonly probed by attackers

Functions

func GenerateLuaScript

func GenerateLuaScript(agentIP string, agentPort int) (string, error)

GenerateLuaScript generates the security.lua file with injected agent IP and port

func GetSuspiciousPathDescription

func GetSuspiciousPathDescription(path string) string

GetSuspiciousPathDescription returns a description for why a path is suspicious

func IsScanner

func IsScanner(userAgent string) bool

IsScanner checks if user agent indicates a scanner

func IsSuspiciousPath

func IsSuspiciousPath(path string) bool

IsSuspiciousPath checks if a path is suspicious

Types

type BlockedIP

type BlockedIP struct {
	ID          int64      `json:"id"`
	IP          string     `json:"ip"`
	Reason      string     `json:"reason,omitempty"`
	BlockedAt   time.Time  `json:"blocked_at"`
	ExpiresAt   *time.Time `json:"expires_at,omitempty"`
	AutoBlocked bool       `json:"auto_blocked"`
}

type DB

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

func NewDB

func NewDB(deploymentsPath string) (*DB, error)

func (*DB) AddProtectedRoute

func (db *DB) AddProtectedRoute(route *ProtectedRoute) (int64, error)

AddProtectedRoute adds a new protected route

func (*DB) AddWhitelistEntry

func (db *DB) AddWhitelistEntry(value, entryType, reason string, isInternal bool) (int64, error)

AddWhitelistEntry adds a new entry to the whitelist

func (*DB) BlockIP

func (db *DB) BlockIP(ip, reason string, expiresAt *time.Time, autoBlocked bool) (int64, error)

BlockIP adds an IP to the blocked list

func (*DB) CleanupExpiredBlocks

func (db *DB) CleanupExpiredBlocks() (int64, error)

CleanupExpiredBlocks removes expired IP blocks

func (*DB) CleanupOldEvents

func (db *DB) CleanupOldEvents(olderThan time.Duration) (int64, error)

CleanupOldEvents deletes events older than the specified duration

func (*DB) Close

func (db *DB) Close() error

func (*DB) DeleteProtectedRoute

func (db *DB) DeleteProtectedRoute(id int64) error

DeleteProtectedRoute deletes a protected route

func (*DB) GetActiveBlockedIPs

func (db *DB) GetActiveBlockedIPs() ([]BlockedIP, error)

GetActiveBlockedIPs retrieves IPs that are currently blocked (not expired)

func (*DB) GetBlockedIPs

func (db *DB) GetBlockedIPs() ([]BlockedIP, error)

GetBlockedIPs retrieves all blocked IPs

func (*DB) GetEnabledProtectedRoutes

func (db *DB) GetEnabledProtectedRoutes() ([]ProtectedRoute, error)

GetEnabledProtectedRoutes retrieves only enabled protected routes

func (*DB) GetEventByID

func (db *DB) GetEventByID(id int64) (*SecurityEvent, error)

GetEventByID retrieves a single event by ID

func (*DB) GetEvents

func (db *DB) GetEvents(filter *EventFilter) ([]SecurityEvent, int, error)

GetEvents retrieves events with optional filtering

func (*DB) GetProtectedRoutes

func (db *DB) GetProtectedRoutes() ([]ProtectedRoute, error)

GetProtectedRoutes retrieves all protected routes

func (*DB) GetStats

func (db *DB) GetStats() (*SecurityStats, error)

GetStats retrieves security statistics

func (*DB) GetWhitelist

func (db *DB) GetWhitelist() ([]WhitelistEntry, error)

GetWhitelist retrieves all whitelist entries

func (*DB) InsertEvent

func (db *DB) InsertEvent(event *SecurityEvent) (int64, error)

InsertEvent inserts a new security event

func (*DB) IsIPBlocked

func (db *DB) IsIPBlocked(ip string) (bool, error)

IsIPBlocked checks if an IP is currently blocked

func (*DB) IsWhitelisted

func (db *DB) IsWhitelisted(value string) (bool, error)

IsWhitelisted checks if an IP or path is in the whitelist

func (*DB) RemoveWhitelistEntry

func (db *DB) RemoveWhitelistEntry(id int64) error

RemoveWhitelistEntry removes an entry from the whitelist

func (*DB) SeedDefaultWhitelist

func (db *DB) SeedDefaultWhitelist() error

SeedDefaultWhitelist adds default internal whitelist entries if not present

func (*DB) UnblockIP

func (db *DB) UnblockIP(ip string) error

UnblockIP removes an IP from the blocked list

func (*DB) UpdateProtectedRoute

func (db *DB) UpdateProtectedRoute(route *ProtectedRoute) error

UpdateProtectedRoute updates an existing protected route

type DeploymentStats

type DeploymentStats struct {
	Name       string `json:"name"`
	EventCount int    `json:"event_count"`
	Critical   int    `json:"critical"`
	High       int    `json:"high"`
}

type Detector

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

func NewDetector

func NewDetector() *Detector

func (*Detector) Classify

func (d *Detector) Classify(event *IngestEvent) *SecurityEvent

Classify analyzes an incoming event and creates a SecurityEvent if it's security-relevant

func (*Detector) CleanupOldWindows

func (d *Detector) CleanupOldWindows()

CleanupOldWindows removes expired rate tracking windows

func (*Detector) GetIPRequestCount

func (d *Detector) GetIPRequestCount(ip string) int

GetIPRequestCount returns the current request count for an IP

func (*Detector) SetThresholds

func (d *Detector) SetThresholds(rateThreshold, notFoundThreshold, authFailureThreshold, uniquePathsThreshold, repeatedHitsThreshold int, windowDuration time.Duration)

SetThresholds configures detection thresholds

func (*Detector) ShouldAutoBlock

func (d *Detector) ShouldAutoBlock(ip string, event *SecurityEvent) (bool, string)

ShouldAutoBlock reports whether an IP should be auto-blocked, and when it should, a human-readable reason naming the rule and the counts or paths that tripped it, so a blocked IP carries a trace of what led to the block.

type EventFilter

type EventFilter struct {
	EventType      string
	Severity       string
	SourceIP       string
	DeploymentName string
	StartTime      time.Time
	EndTime        time.Time
	Limit          int
	Offset         int
}

type IPStats

type IPStats struct {
	IP         string    `json:"ip"`
	EventCount int       `json:"event_count"`
	LastSeen   time.Time `json:"last_seen"`
}

type IngestEvent

type IngestEvent struct {
	SourceIP       string `json:"source_ip"`
	RequestPath    string `json:"request_path"`
	RequestMethod  string `json:"request_method"`
	StatusCode     int    `json:"status_code"`
	UserAgent      string `json:"user_agent"`
	DeploymentName string `json:"deployment_name,omitempty"`
	Timestamp      int64  `json:"timestamp"`
}

IngestEvent is the payload sent from nginx Lua

type IngestResult

type IngestResult struct {
	Event       *SecurityEvent
	AutoBlocked bool
	BlockedIP   string
	BlockTTL    int // TTL in seconds for the block
}

IngestResult contains the result of event ingestion

type Manager

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

func NewManager

func NewManager(deploymentsPath string) (*Manager, error)

func (*Manager) AddDockerGatewayToWhitelist

func (m *Manager) AddDockerGatewayToWhitelist(gatewayIP string) error

func (*Manager) AddProtectedRoute

func (m *Manager) AddProtectedRoute(route *ProtectedRoute) (int64, error)

AddProtectedRoute adds a new protected route

func (*Manager) AddWhitelistEntry

func (m *Manager) AddWhitelistEntry(value, entryType, reason string) (int64, error)

func (*Manager) BlockIP

func (m *Manager) BlockIP(ip, reason string, durationSeconds int) (int64, error)

BlockIP blocks an IP address

func (*Manager) Cleanup

func (m *Manager) Cleanup(retentionDays int) (int64, int64, error)

Cleanup removes old events and expired blocks

func (*Manager) Close

func (m *Manager) Close() error

func (*Manager) DeleteProtectedRoute

func (m *Manager) DeleteProtectedRoute(id int64) error

DeleteProtectedRoute deletes a protected route

func (*Manager) GetActiveBlockedIPs

func (m *Manager) GetActiveBlockedIPs() ([]BlockedIP, error)

GetActiveBlockedIPs retrieves currently active blocked IPs

func (*Manager) GetBlockedIPs

func (m *Manager) GetBlockedIPs() ([]BlockedIP, error)

GetBlockedIPs retrieves all blocked IPs

func (*Manager) GetEnabledProtectedRoutes

func (m *Manager) GetEnabledProtectedRoutes() ([]ProtectedRoute, error)

GetEnabledProtectedRoutes retrieves only enabled routes

func (*Manager) GetEventByID

func (m *Manager) GetEventByID(id int64) (*SecurityEvent, error)

GetEventByID retrieves a single event

func (*Manager) GetEvents

func (m *Manager) GetEvents(filter *EventFilter) ([]SecurityEvent, int, error)

GetEvents retrieves events with optional filtering

func (*Manager) GetEventsByDeployment

func (m *Manager) GetEventsByDeployment(name string, limit int) ([]SecurityEvent, int, error)

GetEventsByDeployment retrieves events for a specific deployment

func (*Manager) GetEventsByIP

func (m *Manager) GetEventsByIP(ip string) ([]SecurityEvent, error)

GetEventsByIP retrieves all events for a specific IP

func (*Manager) GetProtectedRoutes

func (m *Manager) GetProtectedRoutes() ([]ProtectedRoute, error)

GetProtectedRoutes retrieves all protected routes

func (*Manager) GetStats

func (m *Manager) GetStats() (*SecurityStats, error)

GetStats retrieves security statistics

func (*Manager) GetWhitelist

func (m *Manager) GetWhitelist() ([]WhitelistEntry, error)

func (*Manager) IngestEvent

func (m *Manager) IngestEvent(event *IngestEvent, autoBlockDuration time.Duration) (*IngestResult, error)

IngestEvent processes an incoming event from nginx and stores it

func (*Manager) InitNginxConfigs

func (m *Manager) InitNginxConfigs(nginxConfigPath string) error

InitNginxConfigs ensures the nginx security config files exist. This should be called after manager initialization with the nginx config path.

func (*Manager) IsIPBlocked

func (m *Manager) IsIPBlocked(ip string) (bool, error)

IsIPBlocked checks if an IP is blocked

func (*Manager) IsRequestWhitelisted added in v0.3.0

func (m *Manager) IsRequestWhitelisted(ip, path string) (bool, error)

IsRequestWhitelisted reports whether a request's source IP or path matches any whitelist entry. IP entries match exactly, CIDR entries match contained addresses, and path entries match by prefix.

func (*Manager) IsWhitelisted

func (m *Manager) IsWhitelisted(value string) (bool, error)

func (*Manager) RemoveWhitelistEntry

func (m *Manager) RemoveWhitelistEntry(id int64) error

func (*Manager) SetDetectorThresholds

func (m *Manager) SetDetectorThresholds(rateThreshold, notFoundThreshold, authFailureThreshold, uniquePathsThreshold, repeatedHitsThreshold int, windowDuration time.Duration)

SetDetectorThresholds updates the detector's behavior thresholds

func (*Manager) UnblockIP

func (m *Manager) UnblockIP(ip string) error

UnblockIP unblocks an IP address

func (*Manager) UpdateProtectedRoute

func (m *Manager) UpdateProtectedRoute(route *ProtectedRoute) error

UpdateProtectedRoute updates an existing protected route

type NginxConfigGenerator

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

NginxConfigGenerator generates nginx security configuration files

func NewNginxConfigGenerator

func NewNginxConfigGenerator(manager *Manager, configPath string) *NginxConfigGenerator

func (*NginxConfigGenerator) EnsureSecurityConfigFiles

func (g *NginxConfigGenerator) EnsureSecurityConfigFiles() error

EnsureSecurityConfigFiles creates the rate_limits.conf file if it doesn't exist. This is called during initialization to ensure nginx can start.

func (*NginxConfigGenerator) GenerateProtectedLocations

func (g *NginxConfigGenerator) GenerateProtectedLocations() (string, error)

GenerateProtectedLocations generates location blocks for protected routes

func (*NginxConfigGenerator) GenerateProtectedPathsConfig

func (g *NginxConfigGenerator) GenerateProtectedPathsConfig(paths []string) string

GenerateProtectedPathsConfig generates location blocks for blocked paths

func (*NginxConfigGenerator) GenerateRateLimitsConfig

func (g *NginxConfigGenerator) GenerateRateLimitsConfig() (string, error)

GenerateRateLimitsConfig generates the rate_limits.conf file

func (*NginxConfigGenerator) WriteRateLimitsConfig

func (g *NginxConfigGenerator) WriteRateLimitsConfig() error

WriteRateLimitsConfig writes the rate_limits.conf file

type ProtectedRoute

type ProtectedRoute struct {
	ID            int64     `json:"id"`
	PathPattern   string    `json:"path_pattern"`
	RateLimit     int       `json:"rate_limit"`
	BlockDuration int       `json:"block_duration"`
	Enabled       bool      `json:"enabled"`
	CreatedAt     time.Time `json:"created_at"`
}

type SecurityEvent

type SecurityEvent struct {
	ID             int64     `json:"id"`
	EventType      string    `json:"event_type"`
	Severity       string    `json:"severity"`
	SourceIP       string    `json:"source_ip"`
	RequestPath    string    `json:"request_path,omitempty"`
	RequestMethod  string    `json:"request_method,omitempty"`
	StatusCode     int       `json:"status_code,omitempty"`
	UserAgent      string    `json:"user_agent,omitempty"`
	Message        string    `json:"message"`
	RawLog         string    `json:"raw_log,omitempty"`
	DeploymentName string    `json:"deployment_name,omitempty"`
	CreatedAt      time.Time `json:"created_at"`
}

type SecurityStats

type SecurityStats struct {
	TotalEvents          int               `json:"total_events"`
	Last24Hours          int               `json:"last_24_hours"`
	Last7Days            int               `json:"last_7_days"`
	BlockedIPsCount      int               `json:"blocked_ips_count"`
	ProtectedRoutesCount int               `json:"protected_routes_count"`
	BySeverity           map[string]int    `json:"by_severity"`
	ByType               map[string]int    `json:"by_type"`
	TopOffendingIPs      []IPStats         `json:"top_offending_ips"`
	TopDeployments       []DeploymentStats `json:"top_deployments"`
	RecentCritical       []SecurityEvent   `json:"recent_critical"`
	EventsTrend          []TrendPoint      `json:"events_trend"`
}

type TrendPoint

type TrendPoint struct {
	Date  string `json:"date"`
	Count int    `json:"count"`
}

type WhitelistEntry

type WhitelistEntry struct {
	ID         int64     `json:"id"`
	Value      string    `json:"value"`
	Type       string    `json:"type"` // "ip", "cidr", or "path"
	Reason     string    `json:"reason,omitempty"`
	IsInternal bool      `json:"is_internal"`
	CreatedAt  time.Time `json:"created_at"`
}

Jump to

Keyboard shortcuts

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