Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions .github/workflows/fuzz.yml
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,7 @@ jobs:
max_len: 65536
- target: fuzz_enrichers_config
max_len: 65536
- target: fuzz_command_argv
max_len: 4096
- target: fuzz_command_argv_clusters
- target: fuzz_command_strict
max_len: 1024
- target: fuzz_extract_jq
max_len: 4096
Expand Down
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,20 @@ All notable changes to RSigma are documented in this file. Each entry correspond

## [Unreleased]

- Fired deadman correlations no longer leave their suppression entries in memory forever: an entry is dropped when its group fires without suppression, and otherwise once its suppression window passes on that tenant's own clock (#863)
- A shed batch still runs its `template`, `lookup`, `stix`, and `mmdb` enrichers, and a detection whose dedup, `group_by`, or risk-object selector reads the field of a skipped or shed enricher is no longer folded into a different detection or credited to an entity; it counts in `rsigma_alert_identity_incomplete_total` (#862)
- A `dns` enricher's circuit breaker now opens only when its resolver cannot be reached, since an event picks the zone whose owner decides SERVFAIL, REFUSED, timeouts, and slow answers, and when its cooldown ends it asks the resolver for the root zone's `NS` records instead of using a detection's query as the probe (#861)
- An `http` enricher no longer sends a request whose rendered URL or header value is over 8 KiB or whose rendered body is over 1 MiB, and such a request, or one the client cannot build, applies `on_error` without counting against the circuit breaker (#861)
- A `command` enricher no longer starts a command whose rendered arguments or environment values contain a NUL byte or add up to more than 128 KiB, and its timeouts, slow runs, and argv the system refuses as invalid or too long no longer count against the circuit breaker (#861)
- An enricher skipped by its open circuit breaker or shed for want of capacity now leaves its `inject_field` absent and records `skipped` or `shed` under its id in the result's top-level `enrichment_status`, so no selector, matcher, or entity graph reads the status as an enriched value, and an `entity_graph` selector that resolves to an object or array no longer forms a join edge (#860)
- PostgreSQL substring field references no longer hide matches in rows with more than 1024 values; such rows are returned as matches (#859)

### Command enrichers take event values only through `env` (#864)

**Breaking changes:** command enrichers can no longer place event values in argv; use env instead.

Migration: move each event value from argv into env and read it as `"$NAME"` (sh) or `$env:NAME` (pwsh). Put `--` before it where the tool supports it. See docs: [Passing event values safely](https://rsigma.io/guide/enrichers/#passing-event-values-safely).

### A new state database is created with one commit (#858)

`engine daemon --state-db` created each table of a new state database, and added each migrated column, in a statement of its own, so a new database took nine commits before the daemon started listening. Every commit flushes to disk, which is slow on Windows and slower still on a busy disk: on a loaded Windows CI runner, a daemon with a new state database did not finish startup within 10 seconds. The schema is now created or migrated, and then checked, in one transaction, so a new or earlier database takes one commit and a current one takes none. On the Windows runner, opening a new state database now takes about 40 ms instead of about 100 ms, and at most 50 ms under load instead of 500 ms.
Expand Down
2 changes: 1 addition & 1 deletion crates/rsigma-cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1608,8 +1608,8 @@ Per-result `tokio::process::Command` invocation with template-expanded argv and
inject_field: ip_reputation
command:
- "/usr/local/bin/check-ip-rep"
- "${detection.fields.SourceIp}"
env:
SOURCE_IP: "${detection.fields.SourceIp}"
REP_LOCAL_DB: "/var/lib/iprep.db"
output: json # json (default) | raw
timeout: 3s
Expand Down
37 changes: 32 additions & 5 deletions crates/rsigma-eval/src/correlation_engine/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,9 @@ pub struct CorrelationEngine<L = LogSourceExtractor> {
/// Each pending group's `fire_at` in `deadlines`, so its entry is found
/// without a scan.
deadline_of: HashMap<StateKey, i64>,
/// Newest tenant clock at the last `last_alert` reclaim from the deadline
/// path, which scans every entry and so runs at most once per second.
last_alert_reclaimed_at: Option<i64>,
}

impl CorrelationEngine {
Expand Down Expand Up @@ -303,6 +306,7 @@ impl<L> CorrelationEngine<L> {
wall_clock_tenants: std::collections::HashSet::new(),
deadlines: HashMap::new(),
deadline_of: HashMap::new(),
last_alert_reclaimed_at: None,
}
}

Expand Down Expand Up @@ -2115,14 +2119,23 @@ impl<L> CorrelationEngine<L> {
}
}

/// Drop an absence group after its deadman fired. Its `last_alert` entry
/// stays so suppression survives until the next heartbeat re-arms it.
/// Drop an absence group after its deadman fired. When the correlation
/// suppresses, its `last_alert` entry stays so suppression survives until
/// the next heartbeat re-arms it.
fn drop_absence_group(&mut self, key: &StateKey) {
self.state.remove(key);
self.note_tenant_removal(key);
self.event_buffers.remove(key);
self.event_ref_buffers.remove(key);
self.index_clear(key);
let suppress = self
.correlations
.get(key.corr_idx)
.and_then(|correlation| correlation.suppress_secs)
.or(self.config.suppress);
if suppress.is_none() {
self.last_alert.remove(key);
}
}

/// Fire one due obligation and chain its result into parent correlations.
Expand Down Expand Up @@ -2310,6 +2323,10 @@ impl<L> CorrelationEngine<L> {
}
self.refresh_absence_index(&key);
}
if self.last_alert_reclaimed_at.is_none_or(|at| before > at) {
self.last_alert_reclaimed_at = Some(before);
self.reclaim_last_alert(self.high_water);
}
out
}

Expand Down Expand Up @@ -3169,8 +3186,17 @@ impl<L> CorrelationEngine<L> {
}

// Phase 3: Evict last_alert entries whose suppress window has passed.
// An alert after `now_secs` counts as expired, as in the suppression
// check, so it cannot outlive its window.
self.reclaim_last_alert(now_secs);
}

/// Drop `last_alert` entries whose suppress window has passed.
///
/// Each entry is measured against its own tenant's clock, so a tenant
/// running ahead neither ends another tenant's suppression early nor makes
/// its alerts look like they lie in the future. `now_secs` stands in for a
/// tenant without a clock. An alert after the reference counts as expired,
/// as in the suppression check, so it cannot outlive its window.
fn reclaim_last_alert(&mut self, now_secs: i64) {
self.last_alert.retain(|key, &mut alert_ts| {
let suppress = if key.corr_idx < self.correlations.len() {
self.correlations[key.corr_idx]
Expand All @@ -3180,7 +3206,8 @@ impl<L> CorrelationEngine<L> {
} else {
0
};
suppression_active(alert_ts, now_secs, suppress)
let reference = self.clocks.get(&key.tenant).copied().unwrap_or(now_secs);
suppression_active(alert_ts, reference, suppress)
});
}

Expand Down
115 changes: 115 additions & 0 deletions crates/rsigma-eval/src/correlation_engine/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6603,6 +6603,121 @@ correlation:
assert_eq!(armed.deadline, 260);
}

#[test]
fn fired_deadman_groups_do_not_accumulate_last_alert() {
let yaml = r#"---
title: Silent
correlation:
type: temporal
group-by: [User]
timespan: 60s
condition: not a
"#;
let groups = 10_000;
for suppress in [None, Some(300)] {
let config = CorrelationConfig {
suppress,
..CorrelationConfig::default()
};
let mut engine = absence_engine(yaml, config);
assert!(groups < engine.config.max_state_entries);
for i in 0..groups {
hit(&mut engine, "a", &format!("user{i}"), 100);
}
assert_eq!(engine.advance_clock(None, 161).len(), groups);
assert_eq!(engine.state_count(), 0);
// A group keeps its alert only for its suppress window.
let kept = if suppress.is_some() { groups } else { 0 };
assert_eq!(engine.last_alert.len(), kept, "suppress {suppress:?}");

assert!(engine.advance_clock(None, 460).is_empty());
assert_eq!(engine.last_alert.len(), 0, "suppress {suppress:?}");
}
}

#[test]
fn suppression_still_honored_before_expiry() {
let yaml = r#"---
title: Silent
correlation:
type: temporal
group-by: [User]
timespan: 60s
condition: not a
rsigma.suppress: 300s
---
title: Many B
correlation:
type: event_count
rules: [b]
group-by: [User]
timespan: 1h
condition:
gte: 1000
"#;
let tenant_a = TenantId::new("a").unwrap();
let tenant_b = TenantId::new("b").unwrap();
let send = |engine: &mut CorrelationEngine, tenant: &TenantId, action: &str, user: &str, ts| {
let event = json!({"Action": action, "User": user});
engine
.process_event_at_for_tenant(&JsonEvent::borrow(&event), ts, Some(tenant))
.into_iter()
.filter(|r| r.header.rule_title == "Silent")
.count()
};
let tick = |engine: &mut CorrelationEngine, tenant: &TenantId, ts| {
engine
.advance_clock(Some(tenant), ts)
.into_iter()
.filter(|r| r.header.rule_title == "Silent")
.count()
};

// Tenant B running far ahead does not end tenant A's suppression early.
let mut engine = absence_engine(yaml, CorrelationConfig::default());
send(&mut engine, &tenant_a, "a", "host", 100);
assert_eq!(tick(&mut engine, &tenant_a, 161), 1);
send(&mut engine, &tenant_b, "a", "host", 900);
assert_eq!(tick(&mut engine, &tenant_b, 1000), 1);
assert_eq!(send(&mut engine, &tenant_a, "a", "host", 200), 0);
assert_eq!(
tick(&mut engine, &tenant_a, 261),
0,
"A's 160 alert still suppresses 260"
);
assert_eq!(send(&mut engine, &tenant_a, "a", "host", 500), 0);
assert_eq!(
tick(&mut engine, &tenant_a, 561),
1,
"suppression ends at 460"
);

// An alert fired by an idle tick lies ahead of every event so far. A
// lagging tenant's events and ticks, which also reclaim through the
// state cap, must not treat it as expired.
let mut engine = absence_engine(
yaml,
CorrelationConfig {
max_state_entries: 2,
max_absence_entries: 2,
..CorrelationConfig::default()
},
);
send(&mut engine, &tenant_a, "a", "host", 300);
send(&mut engine, &tenant_b, "a", "host", 500);
assert_eq!(tick(&mut engine, &tenant_b, 561), 1);
for (user, ts) in [("u1", 301), ("u2", 302), ("u3", 303)] {
send(&mut engine, &tenant_a, "b", user, ts);
}
assert_eq!(tick(&mut engine, &tenant_a, 304), 0);
assert_eq!(send(&mut engine, &tenant_b, "a", "host", 600), 0);
assert_eq!(
tick(&mut engine, &tenant_b, 661),
0,
"B's 560 alert still suppresses 660"
);
}

#[test]
fn fallback_timestamps_do_not_advance_the_clock() {
let mut engine = absence_engine(TEMPORAL, CorrelationConfig::default());
Expand Down
25 changes: 10 additions & 15 deletions crates/rsigma-runtime/src/enrichment/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,10 @@
//! so operators can see what went wrong without grepping the daemon's
//! tracing output.
//!
//! The argv runs without a shell, so each rendered element is one argument.
//! An argv that would hand an event value to a program as code (a shell
//! script, an interpreter's inline code, the program path itself, an
//! option of a wrapper) fails every call, and the config loader rejects
//! it. An argument whose template starts with an event value is refused
//! when the value starts with `-`, unless a `--` of the program that
//! receives it comes earlier, so a value cannot pose as an option.
//! The argv runs without a shell, and no argv entry may take an event
//! value: event values reach the command only through `env`. A command
//! that breaks the rules in [`super::command_rules`] fails every call, and
//! the config loader rejects it.

use std::collections::HashMap;
use std::time::Duration;
Expand All @@ -37,7 +34,7 @@ use rsigma_eval::EvaluationResult;
use tokio::io::{AsyncRead, AsyncReadExt};
use tokio::process::Command;

use super::command_argv::{ArgvAnalysis, analyze, argv_problem, leading_dash_problem};
use super::command_rules::{command_problem, has_result_ref};
use super::{
EnrichError, EnrichErrorKind, Enricher, EnricherKind, OnError, Scope, inject_enrichment,
render_enricher_template,
Expand Down Expand Up @@ -77,7 +74,6 @@ pub struct CommandEnricher {
on_error: OnError,
scope: Scope,
output: OutputFormat,
analysis: ArgvAnalysis,
argv_problem: Option<String>,
}

Expand All @@ -94,8 +90,7 @@ impl CommandEnricher {
scope: Scope,
output: OutputFormat,
) -> Self {
let analysis = analyze(&argv);
let argv_problem = argv_problem(&argv, &env, &analysis);
let argv_problem = command_problem(&argv, &env).map(|(_, message)| message);
Self {
id,
kind,
Expand All @@ -106,7 +101,6 @@ impl CommandEnricher {
on_error,
scope,
output,
analysis,
argv_problem,
}
}
Expand Down Expand Up @@ -217,6 +211,10 @@ impl Enricher for CommandEnricher {
return Err(self.rejected("empty argv".to_string()));
}
if let Some(problem) = &self.argv_problem {
debug_assert!(
!self.argv.iter().any(|arg| has_result_ref(arg)),
"the config loader refuses this argv: {problem}"
);
return Err(self.rejected(problem.clone()));
}

Expand All @@ -225,9 +223,6 @@ impl Enricher for CommandEnricher {
.iter()
.map(|a| render_enricher_template(a, result))
.collect();
if let Some(problem) = leading_dash_problem(&self.argv, &rendered, &self.analysis) {
return Err(self.rejected(problem));
}

let env: Vec<(&String, String)> = self
.env
Expand Down
Loading
Loading