ruleengine

package
v1.128.0 Latest Latest
Warning

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

Go to latest
Published: May 24, 2026 License: MPL-2.0 Imports: 9 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EventHTTPProbe   = "http_probe"
	EventHTTPAttack  = "http_attack"
	EventIDSAlert    = "ids_alert"
	EventAuthFail    = "auth_fail"
	EventRemoteIntel = "remote_intel"
)

Event type constants

View Source
const (
	CategorySQLi      = "sqli"
	CategoryTraversal = "traversal"
	CategoryProbe     = "probe"
	CategoryBrute     = "brute"
	CategoryC2        = "c2"
	CategoryExploit   = "exploit"
	CategoryMalware   = "malware"
	CategoryXSS       = "xss"
)

Category constants

View Source
const (
	SourceBotGuard   = "botguard"
	SourceSuricata   = "suricata"
	SourceLoginMon   = "loginmon"
	SourceRuleEngine = "rule_engine"
	SourceFeed       = "feed"
)

Source constants

View Source
const (
	ActionObserve      = "observe"
	ActionScore        = "score"
	ActionBanShort     = "ban_short"
	ActionBanLong      = "ban_long"
	ActionBanPermanent = "ban_permanent"
)

Action constants

Variables

This section is empty.

Functions

This section is empty.

Types

type Engine

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

Engine is the event rule engine. It matches normalized events against loaded rules and produces actions (observe, score, ban_*).

The engine operates at the semantic/behavioral layer ONLY. It MUST NOT trigger inline Suricata behavior (INV-S-012). It MUST NOT inspect raw packets or payloads. All enforcement goes through daemon IPC → nftables (INV-S-004).

func New

func New() *Engine

New creates a new rule engine.

func (*Engine) Cleanup

func (e *Engine) Cleanup(maxAge time.Duration)

Cleanup removes expired entries from scores and counters. Call periodically (e.g. every 5 minutes).

func (*Engine) Evaluate

func (e *Engine) Evaluate(ev *Event) *Result

Evaluate processes an event against all loaded rules. Returns the highest-priority matching result.

func (*Engine) LoadRules

func (e *Engine) LoadRules(rules []Rule)

LoadRules replaces the current rule set.

func (*Engine) RuleCount

func (e *Engine) RuleCount() int

RuleCount returns the number of loaded rules.

type Event

type Event struct {
	Timestamp  time.Time         `json:"timestamp"`
	EventType  string            `json:"event_type"` // http_probe, http_attack, ids_alert, auth_fail, remote_intel
	SourceIP   string            `json:"src_ip"`
	DestIP     string            `json:"dest_ip"`
	DestPort   int               `json:"dest_port"`
	Protocol   string            `json:"proto"`      // tcp, udp, icmp
	Service    string            `json:"service"`    // ssh, http, smtp, dns
	Category   string            `json:"category"`   // sqli, traversal, probe, brute, c2, exploit
	Confidence float64           `json:"confidence"` // 0.0-1.0
	Source     string            `json:"source"`     // botguard, suricata, loginmon, rule_engine
	Metadata   map[string]string `json:"metadata"`   // uri, method, status, user_agent, signature, sid
}

Event is the normalized event format consumed by the rule engine. All detection sources (BotGuard, Suricata, LoginMon, future adapters) produce events in this format. The rule engine never sees raw packets, payloads, or protocol-specific data (INV-S-012).

func NewBotGuardEvent added in v1.93.0

func NewBotGuardEvent(srcIP, destIP string, destPort int, uri, method, userAgent, category string, confidence float64) *Event

NewBotGuardEvent creates a normalized event from BotGuard detection data. Called by the BotGuard module when it detects suspicious HTTP behavior.

func NewFeedEvent added in v1.93.0

func NewFeedEvent(srcIP, feedName, indicator string, confidence float64) *Event

NewFeedEvent creates a normalized event from threat intel feed match.

func NewLoginMonEvent added in v1.93.0

func NewLoginMonEvent(srcIP, destIP string, destPort int, service, user string) *Event

NewLoginMonEvent creates a normalized event from LoginMon auth failure.

func NewSuricataEvent added in v1.93.0

func NewSuricataEvent(srcIP, destIP string, srcPort, destPort int, proto, signature, category string, severity int, sid int) *Event

NewSuricataEvent creates a normalized event from a Suricata EVE alert. Called by the Suricata adapter when it processes an alert.

type EventAdapter added in v1.93.0

type EventAdapter interface {
	// Name returns the adapter source name (e.g. "botguard", "suricata", "loginmon")
	Name() string
}

EventAdapter produces normalized events from a detection source. Each detection module (BotGuard, Suricata, LoginMon) implements this to feed events into the rule engine.

The adapter MUST NOT trigger inline behavior (INV-S-012). The adapter MUST NOT inspect raw packets or payloads.

type FieldMatch

type FieldMatch struct {
	Exact    string `yaml:"exact,omitempty" json:"exact,omitempty"`
	Contains string `yaml:"contains,omitempty" json:"contains,omitempty"`
	Prefix   string `yaml:"prefix,omitempty" json:"prefix,omitempty"`
}

FieldMatch defines how a single field is matched.

type Result

type Result struct {
	Matched    bool   `json:"matched"`
	RuleID     string `json:"rule_id,omitempty"`
	RuleName   string `json:"rule_name,omitempty"`
	Action     string `json:"action"`          // observe, score, ban_short, ban_long, ban_permanent
	Score      int    `json:"score,omitempty"` // points added
	TotalScore int    `json:"total_score"`     // accumulated per-IP score
}

Result is the engine's decision for an event.

type Rule

type Rule struct {
	ID        string         `yaml:"id" json:"id"`
	Name      string         `yaml:"name" json:"name"`
	Match     RuleMatch      `yaml:"match" json:"match"`
	Threshold *RuleThreshold `yaml:"threshold,omitempty" json:"threshold,omitempty"`
	Score     int            `yaml:"score" json:"score"`
	Action    string         `yaml:"action" json:"action"` // observe, score, ban_short, ban_long, ban_permanent
}

Rule defines a single matching rule.

func LoadRulesFromDir added in v1.93.0

func LoadRulesFromDir(dir string) ([]Rule, error)

LoadRulesFromDir loads all .yml rule packs from a directory. Returns the combined list of rules from all packs.

func (*Rule) Matches

func (r *Rule) Matches(e *Event) bool

Matches checks if an event matches this rule's criteria. This is pure field matching — no payload inspection (INV-S-012).

type RuleMatch

type RuleMatch struct {
	EventType string                `yaml:"event_type,omitempty" json:"event_type,omitempty"`
	Category  string                `yaml:"category,omitempty" json:"category,omitempty"`
	Service   string                `yaml:"service,omitempty" json:"service,omitempty"`
	Metadata  map[string]FieldMatch `yaml:"metadata,omitempty" json:"metadata,omitempty"`
}

RuleMatch defines the event matching criteria.

type RulePack

type RulePack struct {
	Name  string `yaml:"name" json:"name"`
	Rules []Rule `yaml:"rules" json:"rules"`
}

RulePack is a collection of rules loaded from a .rules file.

type RuleThreshold

type RuleThreshold struct {
	Count  int           `yaml:"count" json:"count"`
	Window time.Duration `yaml:"window" json:"window"`
	Per    string        `yaml:"per" json:"per"` // "src_ip" (always per source IP)
}

RuleThreshold defines count-over-time-window thresholds.

type Service added in v1.93.0

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

Service is the main integration point for the rule engine. It loads rules from disk, processes incoming events, and returns ban/observe decisions. The daemon wires this into the event pipeline.

All enforcement flows through daemon IPC → nftables (INV-S-004). The service MUST NOT trigger inline behavior (INV-S-012).

func NewService added in v1.93.0

func NewService(rulesDir string) *Service

NewService creates a rule engine service. rulesDir is typically /etc/nftban/rules.d/

func (*Service) ProcessEvent added in v1.93.0

func (s *Service) ProcessEvent(ev *Event) *Result

ProcessEvent evaluates an event against loaded rules. Returns a Result with the action to take. If the service is disabled or no rules match, returns ActionObserve.

func (*Service) Reload added in v1.93.0

func (s *Service) Reload() error

Reload reloads rules from disk without stopping.

func (*Service) Start added in v1.93.0

func (s *Service) Start() error

Start loads rules and enables the service.

func (*Service) Stats added in v1.93.0

func (s *Service) Stats() ServiceStats

Stats returns current service statistics.

func (*Service) Stop added in v1.93.0

func (s *Service) Stop()

Stop disables the service.

type ServiceStats added in v1.93.0

type ServiceStats struct {
	Enabled         bool  `json:"enabled"`
	RuleCount       int   `json:"rule_count"`
	EventsProcessed int64 `json:"events_processed"`
	RulesMatched    int64 `json:"rules_matched"`
	BansProduced    int64 `json:"bans_produced"`
}

ServiceStats holds runtime statistics for the rule engine.

Jump to

Keyboard shortcuts

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