Documentation
¶
Index ¶
- Constants
- Variables
- func CompileRules(config *Config) error
- func EvaluateRule(rule *Rule, record types.AuditRecord) (*types.Alert, error)
- func GetEmbeddedRuleSetInfo() (map[string]EmbeddedRuleSetInfo, error)
- func GetEmbeddedRuleSetNames() ([]string, error)
- func SharedAlertAuditWriter(output string, header *types.Header) (netio.AuditRecordWriter, bool)
- func ValidateOfflinePack(pack *OfflinePack) error
- func ValidateSeverity(severity string) bool
- type ActionStats
- type AlertEvent
- type AlertTail
- type AlertWriter
- type CaptureTimeConfig
- type Config
- type EmbeddedRuleSetInfo
- type Engine
- func (e *Engine) AppliesTo(record types.AuditRecord) bool
- func (e *Engine) CaptureTimeEnabled() bool
- func (e *Engine) Close() error
- func (e *Engine) Evaluate(record types.AuditRecord) (int, error)
- func (e *Engine) EvaluateObserved(scope string, record types.AuditRecord) (int, error)
- func (e *Engine) EvaluateScoped(scope string, record types.AuditRecord) (int, error)
- func (e *Engine) Finalize() (int, error)
- func (e *Engine) GetActionStats() map[string]uint64
- func (e *Engine) GetFirewallManager() *firewall.Manager
- func (e *Engine) GetStats() map[string]any
- func (e *Engine) SetDeduplicationWindow(d time.Duration)
- func (e *Engine) SetFirewallManager(manager *firewall.Manager)
- func (e *Engine) SetPerformanceTracker(tracker *performance.Tracker)
- func (e *Engine) SetRateLimit(limit int)
- func (e *Engine) UpdateConfig(config *Config) error
- type FileAlertWriter
- type OfflineAlertMetadata
- type OfflineContributor
- type OfflineFile
- type OfflineLease
- type OfflineLimits
- type OfflinePack
- type OfflineReadyMarker
- type OfflineReport
- type OfflineRequest
- type OfflineRule
- type OfflineRuleStats
- type OfflineThreshold
- type OfflineTypeStats
- type OrderedStream
- type ResponseAction
- type Rule
- type Sequence
Constants ¶
const OfflineFormat = "netcap-offline-rules/v1"
const OfflineLeaseFile = ".offline-rule-evaluation.lock"
const OfflineReadyFile = "audit-output-ready.json"
Variables ¶
var ErrAlertCursor = errors.New("alert cursor no longer matches capture history")
var ErrAlertNotReady = errors.New("no complete alert member available")
var ErrStateCapacity = errors.New("scoped rule state capacity reached")
var ErrUnsupportedResponseAction = errors.New("unsupported response action")
ErrUnsupportedResponseAction identifies an action that installs no firewall rule.
Functions ¶
func CompileRules ¶
CompileRules compiles all rule expressions in the configuration.
func EvaluateRule ¶
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 ¶
GetEmbeddedRuleSetNames returns a list of embedded rule set names (without .yml extension).
func SharedAlertAuditWriter ¶
SharedAlertAuditWriter joins an already-enabled incremental alert store. Ordinary captures retain their configured output writer.
func ValidateOfflinePack ¶
func ValidateOfflinePack(pack *OfflinePack) error
func ValidateSeverity ¶
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 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 (*AlertTail) Next ¶
func (t *AlertTail) Next() (AlertEvent, error)
type AlertWriter ¶
AlertWriter is an interface for writing alerts.
type CaptureTimeConfig ¶ added in v0.16.0
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 ¶
LoadEmbeddedRules loads all embedded default detection rules. These are bundled into the binary at compile time.
func LoadRulesFromDirectory ¶
LoadRulesFromDirectory loads all rule files from a directory and returns a merged configuration.
func LoadRulesFromFile ¶
LoadRulesFromFile loads rules from a YAML file.
func LoadRulesWithEmbeddedDefaults ¶
LoadRulesWithEmbeddedDefaults loads rules from a directory path, but first loads embedded defaults. File rules override embedded rules with the same name.
func MergeConfigs ¶
MergeConfigs merges two configs, with override rules taking precedence. Rules with matching names in override replace rules in base.
type EmbeddedRuleSetInfo ¶
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
CaptureTimeEnabled reports whether this engine owns a single scoped timeline.
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
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
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
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 ¶
GetActionStats returns response action statistics.
func (*Engine) GetFirewallManager ¶
GetFirewallManager returns the current firewall manager.
func (*Engine) SetDeduplicationWindow ¶
SetDeduplicationWindow configures the time window for alert deduplication.
func (*Engine) SetFirewallManager ¶
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 ¶
SetRateLimit configures the maximum number of alerts per minute per rule.
func (*Engine) UpdateConfig ¶
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 OfflineFile ¶
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 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 OfflineThreshold ¶
type OfflineTypeStats ¶
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.