rules

package
v0.16.4 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: BSD-3-Clause, GPL-3.0 Imports: 43 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const OfflineFormat = "netcap-offline-rules/v1"
View Source
const OfflineLeaseFile = ".offline-rule-evaluation.lock"
View Source
const OfflineReadyFile = "audit-output-ready.json"

Variables

View Source
var ErrAlertCursor = errors.New("alert cursor no longer matches capture history")
View Source
var ErrAlertNotReady = errors.New("no complete alert member available")
View Source
var ErrStateCapacity = errors.New("scoped rule state capacity reached")
View Source
var ErrUnsupportedResponseAction = errors.New("unsupported response action")

ErrUnsupportedResponseAction identifies an action that installs no firewall rule.

Functions

func CompileRules

func CompileRules(config *Config) error

CompileRules compiles all rule expressions in the configuration.

func EvaluateRule

func EvaluateRule(rule *Rule, record types.AuditRecord) (*types.Alert, error)

EvaluateRule evaluates a rule against an audit record and returns an alert if it matches.

func GetEmbeddedRuleSetInfo

func GetEmbeddedRuleSetInfo() (map[string]EmbeddedRuleSetInfo, error)

GetEmbeddedRuleSetInfo returns information about all embedded rule sets including descriptions.

func GetEmbeddedRuleSetNames

func GetEmbeddedRuleSetNames() ([]string, error)

GetEmbeddedRuleSetNames returns a list of embedded rule set names (without .yml extension).

func SharedAlertAuditWriter

func SharedAlertAuditWriter(output string, header *types.Header) (netio.AuditRecordWriter, bool)

SharedAlertAuditWriter joins an already-enabled incremental alert store. Ordinary captures retain their configured output writer.

func ValidateOfflinePack

func ValidateOfflinePack(pack *OfflinePack) error

func ValidateSeverity

func ValidateSeverity(severity string) bool

ValidateSeverity checks if a severity string is valid.

Types

type ActionStats

type ActionStats struct {
	ActionsExecuted uint64
	ActionsSuccess  uint64
	ActionsFailed   uint64
	IPsBlocked      uint64
	// contains filtered or unexported fields
}

ActionStats tracks response action statistics.

type AlertEvent

type AlertEvent struct {
	Cursor string
	Alert  *types.Alert
}

type AlertTail

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

AlertTail follows complete gzip members without rescanning history on each poll. Legacy first-member records are validated once and streamed with bounded memory.

func OpenAlertTail

func OpenAlertTail(path, cursor string) (*AlertTail, error)

func (*AlertTail) Close

func (t *AlertTail) Close() error

func (*AlertTail) Next

func (t *AlertTail) Next() (AlertEvent, error)

type AlertWriter

type AlertWriter interface {
	WriteAlert(alert *types.Alert) error
	Close() error
}

AlertWriter is an interface for writing alerts.

type CaptureTimeConfig added in v0.16.0

type CaptureTimeConfig struct {
	Scope           string `yaml:"scope"`
	LatenessSeconds int    `yaml:"lateness_seconds"`
}

type Config

type Config struct {
	// CaptureTime opts capture-time evaluation into one caller-qualified scope.
	CaptureTime *CaptureTimeConfig `yaml:"capture_time,omitempty"`
	Description string             `yaml:"description"`
	Rules       []*Rule            `yaml:"rules"`
}

Config holds a collection of rules loaded from a YAML file.

func LoadEmbeddedRules

func LoadEmbeddedRules() (*Config, error)

LoadEmbeddedRules loads all embedded default detection rules. These are bundled into the binary at compile time.

func LoadRulesFromDirectory

func LoadRulesFromDirectory(dirPath string) (*Config, error)

LoadRulesFromDirectory loads all rule files from a directory and returns a merged configuration.

func LoadRulesFromFile

func LoadRulesFromFile(path string) (*Config, error)

LoadRulesFromFile loads rules from a YAML file.

func LoadRulesWithEmbeddedDefaults

func LoadRulesWithEmbeddedDefaults(dirPath string) (*Config, error)

LoadRulesWithEmbeddedDefaults loads rules from a directory path, but first loads embedded defaults. File rules override embedded rules with the same name.

func MergeConfigs

func MergeConfigs(base, override *Config) *Config

MergeConfigs merges two configs, with override rules taking precedence. Rules with matching names in override replace rules in base.

type EmbeddedRuleSetInfo

type EmbeddedRuleSetInfo struct {
	Name        string
	Description string
	RuleCount   int
}

EmbeddedRuleSetInfo contains information about an embedded rule set.

type Engine

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

Engine manages rules and evaluates them against audit records.

func NewEngine

func NewEngine(rulesPath string, alertWriter AlertWriter) (*Engine, error)

NewEngine creates a new rules engine with the given configuration and alert writer. rulesPath can be a path to a single YAML file or a directory containing multiple YAML files.

func NewEngineFromConfig

func NewEngineFromConfig(config *Config, alertWriter AlertWriter) (*Engine, error)

NewEngineFromConfig creates a new rules engine from an existing configuration. This allows creating an engine without reading from a file.

func (*Engine) AppliesTo added in v0.16.0

func (e *Engine) AppliesTo(record types.AuditRecord) bool

func (*Engine) CaptureTimeEnabled added in v0.16.0

func (e *Engine) CaptureTimeEnabled() bool

CaptureTimeEnabled reports whether this engine owns a single scoped timeline.

func (*Engine) Close

func (e *Engine) Close() error

Close closes the alert writer.

func (*Engine) Evaluate

func (e *Engine) Evaluate(record types.AuditRecord) (int, error)

Evaluate evaluates all applicable rules against an audit record. It returns the number of alerts generated.

func (*Engine) EvaluateObserved added in v0.16.0

func (e *Engine) EvaluateObserved(scope string, record types.AuditRecord) (int, error)

EvaluateObserved retains the observed interface/encapsulation scope inside the declared source timeline. The declaration alone cannot isolate mixed inputs.

func (*Engine) EvaluateScoped added in v0.16.0

func (e *Engine) EvaluateScoped(scope string, record types.AuditRecord) (int, error)

EvaluateScoped evaluates ordered records in an explicit capture/source scope. Use OrderedStream for bounded reordering; unscoped legacy rules retain their API.

func (*Engine) Finalize added in v0.16.0

func (e *Engine) Finalize() (int, error)

Finalize drains capture-time records before the owner publishes readiness. It is idempotent and leaves the alert writer open for coordinated teardown.

func (*Engine) GetActionStats

func (e *Engine) GetActionStats() map[string]uint64

GetActionStats returns response action statistics.

func (*Engine) GetFirewallManager

func (e *Engine) GetFirewallManager() *firewall.Manager

GetFirewallManager returns the current firewall manager.

func (*Engine) GetStats

func (e *Engine) GetStats() map[string]any

GetStats returns statistics about the engine.

func (*Engine) SetDeduplicationWindow

func (e *Engine) SetDeduplicationWindow(d time.Duration)

SetDeduplicationWindow configures the time window for alert deduplication.

func (*Engine) SetFirewallManager

func (e *Engine) SetFirewallManager(manager *firewall.Manager)

SetFirewallManager sets the firewall manager for response actions. If not set, iptables-based response actions will be skipped.

func (*Engine) SetPerformanceTracker

func (e *Engine) SetPerformanceTracker(tracker *performance.Tracker)

SetPerformanceTracker sets the performance tracker for collecting metrics.

func (*Engine) SetRateLimit

func (e *Engine) SetRateLimit(limit int)

SetRateLimit configures the maximum number of alerts per minute per rule.

func (*Engine) UpdateConfig

func (e *Engine) UpdateConfig(config *Config) error

UpdateConfig updates the rules configuration in memory. A successful reload resets thresholds, sequences, distinct counts, dedup and rate limits.

type FileAlertWriter

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

FileAlertWriter appends complete gzip members, readable before Close.

func NewFileAlertWriter

func NewFileAlertWriter(outputDir string) (*FileAlertWriter, error)

NewFileAlertWriter validates existing history without retaining it in memory. A new file is created only on the first alert.

func (*FileAlertWriter) Close

func (w *FileAlertWriter) Close() error

Close releases this writer; it is idempotent and reports persistence failures.

func (*FileAlertWriter) Error

func (w *FileAlertWriter) Error() error

Error includes failures raised by other writers sharing this file.

func (*FileAlertWriter) WriteAlert

func (w *FileAlertWriter) WriteAlert(alert *types.Alert) error

WriteAlert returns only after the complete alert member is synced to disk.

type OfflineAlertMetadata

type OfflineAlertMetadata struct {
	Version                 int                  `json:"version"`
	EventID                 string               `json:"eventId"`
	RunID                   string               `json:"runId"`
	RuleID                  string               `json:"ruleId"`
	RuleDigest              string               `json:"ruleDigest"`
	InputCanonicalDigest    string               `json:"inputCanonicalDigest"`
	ObservationPolicyDigest string               `json:"observationPolicyDigest,omitempty"`
	Group                   map[string]any       `json:"group"`
	Count                   int                  `json:"count"`
	First                   int64                `json:"first,string"`
	Last                    int64                `json:"last,string"`
	WindowNs                int64                `json:"windowNs,string"`
	Contributors            []OfflineContributor `json:"contributors"`
	ContributorsTruncated   bool                 `json:"contributorsTruncated"`
}

type OfflineContributor

type OfflineContributor struct {
	File       string `json:"file"`
	Ordinal    uint64 `json:"ordinal,string"`
	SHA256     string `json:"sha256"`
	Timestamp  int64  `json:"timestamp,string"`
	FileSHA256 string `json:"fileSHA256,omitempty"`
}

type OfflineFile

type OfflineFile struct {
	Name   string `json:"name"`
	SHA256 string `json:"sha256"`
	Bytes  int64  `json:"bytes,string"`
}

type OfflineLease

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

OfflineLease coordinates evaluators and parent reanalysis. Stale locks require explicit operator removal; deleting a live owner's lock is never automatic.

func AcquireOfflineLease

func AcquireOfflineLease(directory string) (*OfflineLease, error)

func (*OfflineLease) Close

func (l *OfflineLease) Close() error

type OfflineLimits

type OfflineLimits struct {
	FrameBytes     int64         `json:"frameBytes"`
	Records        int64         `json:"records"`
	DecodedBytes   int64         `json:"decodedBytes"`
	SortBytes      int64         `json:"sortBytes"`
	StateBytes     int64         `json:"stateBytes"`
	GroupsPerRule  int64         `json:"groupsPerRule"`
	Groups         int64         `json:"groups"`
	PendingPerRule int64         `json:"pendingPerRule"`
	Pending        int64         `json:"pending"`
	Rules          int64         `json:"rules"`
	Alerts         int64         `json:"alerts"`
	AlertBytes     int64         `json:"alertBytes"`
	Duration       time.Duration `json:"duration"`
}

Zero selects the default. Positive overrides may only reduce the hard ceiling. Limits are bounded below JavaScript's exact-integer ceiling, including duration in nanoseconds.

func DefaultOfflineLimits

func DefaultOfflineLimits() OfflineLimits

type OfflinePack

type OfflinePack struct {
	Format string        `yaml:"format" json:"format"`
	Rules  []OfflineRule `yaml:"rules" json:"rules"`
}

OfflinePack is deliberately incompatible with the live engine's integer threshold.

func LoadOfflinePack

func LoadOfflinePack(path string) (*OfflinePack, error)

func ParseOfflinePack

func ParseOfflinePack(data []byte) (*OfflinePack, error)

type OfflineReadyMarker

type OfflineReadyMarker struct {
	Version int    `json:"version"`
	RunID   string `json:"runId"`
}

type OfflineReport

type OfflineReport struct {
	Version                 int                `json:"version"`
	ID                      string             `json:"id"`
	RunID                   string             `json:"runId"`
	Status                  string             `json:"status"`
	Error                   string             `json:"error,omitempty"`
	StartedAt               string             `json:"startedAt"`
	Elapsed                 time.Duration      `json:"elapsed,string"`
	PackDigest              string             `json:"packDigest"`
	ConfigDigest            string             `json:"configDigest"`
	ObservationPolicyDigest string             `json:"observationPolicyDigest,omitempty"`
	InputCanonicalDigest    string             `json:"inputCanonicalDigest"`
	Files                   []OfflineFile      `json:"files"`
	Types                   []OfflineTypeStats `json:"types"`
	Rules                   []OfflineRuleStats `json:"rules"`
	Limits                  OfflineLimits      `json:"limits"`
	Limitations             []string           `json:"limitations"`
	PlannedAlerts           int64              `json:"plannedAlerts,string"`
	CommittedAlerts         int64              `json:"committedAlerts,string"`
}

func EvaluateOffline

func EvaluateOffline(ctx context.Context, request OfflineRequest) (*OfflineReport, error)

EvaluateOffline validates and evaluates all input before appending any alert. Errors before committing publish nothing. A publish-failed report records the durable prefix; callers must never automatically retry a failed publication.

func ListOfflineEvaluations

func ListOfflineEvaluations(directory string) ([]OfflineReport, error)

ListOfflineEvaluations returns at most 100 reports in lexical evaluation-ID order. Malformed visible reports and an oversized history fail explicitly.

type OfflineRequest

type OfflineRequest struct {
	Directory string        `json:"directory"`
	Pack      *OfflinePack  `json:"pack"`
	Limits    OfflineLimits `json:"limits"`
}

type OfflineRule

type OfflineRule struct {
	ID          string           `yaml:"id" json:"id"`
	Name        string           `yaml:"name" json:"name"`
	Description string           `yaml:"description" json:"description"`
	Type        string           `yaml:"type" json:"type"`
	Expression  string           `yaml:"expression" json:"expression"`
	Severity    string           `yaml:"severity" json:"severity"`
	Enabled     bool             `yaml:"enabled" json:"enabled"`
	Threshold   OfflineThreshold `yaml:"threshold" json:"threshold"`
}

type OfflineRuleStats

type OfflineRuleStats struct {
	ID            string `json:"id"`
	Type          string `json:"type"`
	Digest        string `json:"digest"`
	Enabled       bool   `json:"enabled"`
	Matches       int64  `json:"matches,string"`
	MissingGroups int64  `json:"missingGroups,string"`
	Alerts        int64  `json:"alerts,string"`
}

type OfflineThreshold

type OfflineThreshold struct {
	Count   int      `yaml:"count" json:"count"`
	Window  string   `yaml:"window" json:"window"`
	GroupBy []string `yaml:"group_by" json:"groupBy"`
}

type OfflineTypeStats

type OfflineTypeStats struct {
	Type           string `json:"type"`
	Records        int64  `json:"records,string"`
	CanonicalBytes int64  `json:"canonicalBytes,string"`
	Missing        bool   `json:"missing"`
	UnknownScopes  int64  `json:"unknownScopes,string"`
}

type OrderedStream added in v0.16.0

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

OrderedStream owns one capture/source scope and a bounded reorder buffer. The caller advances capture-time watermarks only when earlier records can no longer arrive (or after its configured lateness allowance). Records at/below a committed watermark fail explicitly. Finish drains EOF in canonical order.

func NewOrderedStream added in v0.16.0

func NewOrderedStream(config *Config, writer AlertWriter, scope string) (*OrderedStream, error)

func (*OrderedStream) Advance added in v0.16.0

func (s *OrderedStream) Advance(watermark int64) (int, error)

Advance evaluates all admitted records at/below watermark. A write/evaluation error makes this stream terminal; retained evidence must be replayed in a new run rather than silently losing a threshold crossing on retry.

func (*OrderedStream) Close added in v0.16.0

func (s *OrderedStream) Close() error

func (*OrderedStream) Finish added in v0.16.0

func (s *OrderedStream) Finish() (int, error)

func (*OrderedStream) Push added in v0.16.0

func (s *OrderedStream) Push(record types.AuditRecord) error

func (*OrderedStream) Reload added in v0.16.0

func (s *OrderedStream) Reload(config *Config) error

Reload refuses queued old-generation records. Flush an explicit watermark first; compilation failure preserves both active rules and correlation state.

type ResponseAction

type ResponseAction struct {
	// Type is the action type (iptables_block, iptables_reject, iptables_rate_limit, iptables_log)
	Type string `yaml:"type"`

	// Config contains action-specific configuration
	Config map[string]any `yaml:"config,omitempty"`

	// Enabled allows disabling specific actions (default: true if omitted)
	Enabled *bool `yaml:"enabled,omitempty"`
}

ResponseAction defines an automated response to a rule match.

func (*ResponseAction) IsEnabled

func (a *ResponseAction) IsEnabled() bool

IsEnabled returns true if the action is enabled (default is true).

func (*ResponseAction) Validate

func (a *ResponseAction) Validate() error

Validate checks if the response action has a valid type.

type Rule

type Rule struct {
	// Name is a unique identifier for the rule
	Name string `yaml:"name"`

	// Description provides human-readable information about the rule
	Description string `yaml:"description"`

	// Type specifies which audit record type this rule applies to (e.g., "TCP", "HTTP")
	Type string `yaml:"type"`

	// Expression is the expr-lang expression to evaluate
	Expression string `yaml:"expression"`

	// Severity indicates the importance of alerts generated by this rule
	// Valid values: low, medium, high, critical
	Severity string `yaml:"severity"`

	// MITRE contains MITRE ATT&CK technique IDs associated with this rule
	MITRE []string `yaml:"mitre"`

	// Tags are custom labels for categorizing rules
	Tags []string `yaml:"tags"`

	// Enabled determines whether this rule is active
	Enabled bool `yaml:"enabled"`

	// Threshold is the number of times this rule must match before triggering an alert
	// If 0 or 1, alert is triggered immediately on first match (default behavior)
	Threshold int `yaml:"threshold,omitempty"`

	// ThresholdWindow is the time window (in seconds) within which the threshold must be reached
	// Only applicable when Threshold > 1. Default is 60 seconds (1 minute)
	ThresholdWindow int `yaml:"threshold_window,omitempty"`

	// GroupBy opts repeated-count rules into explicit scoped capture-time state.
	GroupBy []string `yaml:"group_by,omitempty"`

	// DistinctField enables cardinality-based detection: instead of counting raw
	// matches, the engine counts the number of DISTINCT values of this field
	// observed per source IP within ThresholdWindow. When the distinct count
	// reaches DistinctThreshold, an alert fires.
	//
	// This expresses the AA26-231A "internal enumeration" hunt shape: one source
	// touching many distinct controllers on port 102, once each. For example,
	// DistinctField: "DstIP" with DistinctThreshold: 5 fires when a single
	// source contacts 5+ distinct destinations within the window.
	//
	// The field name must be a top-level field of the record type (e.g. "DstIP").
	DistinctField string `yaml:"distinct_field,omitempty"`

	// DistinctThreshold is the number of distinct DistinctField values (per source)
	// required within ThresholdWindow before an alert fires. Only applicable when
	// DistinctField is set. Defaults to 2 if DistinctField is set but this is <= 1.
	DistinctThreshold int `yaml:"distinct_threshold,omitempty"`

	// Actions are response actions to execute when this rule matches and generates an alert.
	// These are automated responses like blocking IPs via iptables.
	Actions []*ResponseAction `yaml:"actions,omitempty"`

	// Sequence requires an earlier record to have been observed before this
	// rule's own expression can raise an alert. It expresses "B after A within
	// a window, for the same group", such as a write to a register that the
	// same source read minutes earlier.
	//
	// When set, the sequence gate is applied first; Threshold and DistinctField
	// then behave exactly as they do for an ungated rule.
	Sequence *Sequence `yaml:"sequence,omitempty"`
	// contains filtered or unexported fields
}

Rule represents a detection rule that can be evaluated against audit records.

type Sequence

type Sequence struct {
	// AfterType permits a qualified cross-record join. It requires explicit scope.
	AfterType string `yaml:"after_type,omitempty"`
	// AfterGroupBy maps antecedent fields positionally to GroupBy.
	AfterGroupBy []string `yaml:"after_group_by,omitempty"`
	// After is the expression identifying the earlier record. It is evaluated
	// against the same record type as the rule.
	After string `yaml:"after"`

	// GroupBy lists top-level record fields whose values must be equal for the
	// earlier and triggering records to be considered related. Grouping is
	// exact equality: it cannot express range overlap.
	GroupBy []string `yaml:"group_by"`

	// Within is how many seconds the earlier record stays eligible. Default 60.
	Within int `yaml:"within,omitempty"`
	// contains filtered or unexported fields
}

Sequence configures ordered, grouped correlation for a rule.

func (*Sequence) Validate

func (s *Sequence) Validate() error

Validate checks that a sequence is usable before rules are compiled.

Jump to

Keyboard shortcuts

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