rsigma 0.18.0

CLI for parsing, validating, linting and evaluating Sigma detection rules
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//! E2E tests for the daemon's `--webhook` flag.
//!
//! Each test spawns `rsigma engine daemon` with a webhook config pointed at a
//! `wiremock` server, sends a detection-triggering event over `--input http`,
//! and asserts on the request the webhook made (rendered body and headers),
//! the retry / DLQ behavior, kind/scope filtering, env-header interpolation,
//! and that a stalled webhook never blocks a co-configured file sink.

#![cfg(feature = "daemon")]

mod common;

use std::time::Duration;

use common::{DaemonProcess, SIMPLE_RULE, http_post, poll_until, temp_file};
use wiremock::matchers::method;
use wiremock::{Mock, MockServer, ResponseTemplate};

const MATCHING_EVENT: &str = r#"{"CommandLine":"run malware.exe"}"#;

/// Detection webhook posting a rendered JSON body plus a static header.
const WEBHOOK_CFG: &str = r#"
webhooks:
  - id: slack
    kind: detection
    url: __URL__/hook
    headers:
      X-Source: rsigma
    body: '{"text":"${detection.rule.title}: ${detection.fields.CommandLine}"}'
"#;

/// Webhook whose Authorization header is an env-var template.
const WEBHOOK_AUTH_CFG: &str = r#"
webhooks:
  - id: slack
    kind: detection
    url: __URL__/hook
    headers:
      Authorization: "Bearer ${RSIGMA_TEST_WEBHOOK_TOKEN}"
    body: '{"text":"${detection.rule.title}"}'
"#;

/// Webhook that HMAC-signs deliveries using a secret from the environment.
const WEBHOOK_SIGNED_CFG: &str = r#"
webhooks:
  - id: slack
    kind: detection
    url: __URL__/hook
    body: '{"text":"${detection.rule.title}"}'
    signing:
      secret_env: RSIGMA_TEST_WEBHOOK_SECRET
"#;

/// Webhook scoped to a level the test rule (high) does not carry.
const WEBHOOK_SCOPED_CFG: &str = r#"
webhooks:
  - id: slack
    kind: detection
    url: __URL__/hook
    body: '{"text":"${detection.rule.title}"}'
    scope:
      levels: [critical]
"#;

/// HTTPS webhook trusting a private CA, retrying once so the unreachable
/// delivery reaches the DLQ quickly.
const TLS_CFG: &str = r#"
webhooks:
  - id: internal
    kind: detection
    url: https://127.0.0.1:1/hook
    body: '{"text":"${detection.rule.title}"}'
    retry:
      attempts: 1
    tls:
      ca: __CA__
"#;

/// Webhook with fast retry tuning so the retry loop runs within the test.
const WEBHOOK_RETRY_CFG: &str = r#"
webhooks:
  - id: slack
    kind: detection
    url: __URL__/hook
    body: '{"text":"${detection.rule.title}"}'
    retry:
      attempts: 3
      backoff: 100ms
      max_backoff: 300ms
"#;

fn rt() -> tokio::runtime::Runtime {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap()
}

/// Start a wiremock server that answers every POST with `status`.
fn mock_server(rt: &tokio::runtime::Runtime, status: u16) -> MockServer {
    rt.block_on(async {
        let s = MockServer::start().await;
        Mock::given(method("POST"))
            .respond_with(ResponseTemplate::new(status))
            .mount(&s)
            .await;
        s
    })
}

fn request_count(rt: &tokio::runtime::Runtime, server: &MockServer) -> usize {
    rt.block_on(server.received_requests())
        .map(|r| r.len())
        .unwrap_or(0)
}

#[test]
fn webhook_delivers_rendered_body_and_headers() {
    let rt = rt();
    let server = mock_server(&rt, 200);
    let webhook = temp_file(".yml", &WEBHOOK_CFG.replace("__URL__", &server.uri()));
    let rule = temp_file(".yml", SIMPLE_RULE);
    let daemon = DaemonProcess::spawn_http_with_args(
        rule.path().to_str().unwrap(),
        &["--webhook", webhook.path().to_str().unwrap()],
    );

    let (status, _) = http_post(&daemon.url("/api/v1/events"), MATCHING_EVENT);
    assert_eq!(status, 200);

    let req = poll_until(Duration::from_secs(5), || {
        rt.block_on(server.received_requests())
            .unwrap_or_default()
            .into_iter()
            .next()
    })
    .expect("webhook never made a request");

    assert_eq!(
        req.headers.get("x-source").and_then(|v| v.to_str().ok()),
        Some("rsigma"),
        "the static header should be sent",
    );
    let body: serde_json::Value =
        serde_json::from_slice(&req.body).expect("rendered body must be valid JSON");
    assert_eq!(
        body["text"], "Test Rule: run malware.exe",
        "the body should interpolate the rule title and matched field",
    );
}

#[test]
fn webhook_permanent_4xx_routes_to_dlq() {
    let rt = rt();
    let server = mock_server(&rt, 400);
    let webhook = temp_file(".yml", &WEBHOOK_CFG.replace("__URL__", &server.uri()));
    let rule = temp_file(".yml", SIMPLE_RULE);
    let dlq = temp_file(".ndjson", "");
    let dlq_spec = format!("file://{}", dlq.path().display());
    let daemon = DaemonProcess::spawn_http_with_args(
        rule.path().to_str().unwrap(),
        &[
            "--webhook",
            webhook.path().to_str().unwrap(),
            "--dlq",
            &dlq_spec,
        ],
    );

    let (status, _) = http_post(&daemon.url("/api/v1/events"), MATCHING_EVENT);
    assert_eq!(status, 200);

    let dlqd = poll_until(Duration::from_secs(10), || {
        let s = std::fs::read_to_string(dlq.path()).unwrap_or_default();
        (s.contains("webhook slack") && s.contains("HTTP 400")).then_some(())
    });
    assert!(
        dlqd.is_some(),
        "a permanent 4xx should route to the DLQ with the webhook id and status",
    );
    // A permanent failure must not be retried: exactly one request.
    assert_eq!(
        request_count(&rt, &server),
        1,
        "permanent 4xx must not retry"
    );
}

#[test]
fn webhook_retries_then_exhausts_to_dlq() {
    let rt = rt();
    let server = mock_server(&rt, 500);
    let webhook = temp_file(".yml", &WEBHOOK_RETRY_CFG.replace("__URL__", &server.uri()));
    let rule = temp_file(".yml", SIMPLE_RULE);
    let dlq = temp_file(".ndjson", "");
    let dlq_spec = format!("file://{}", dlq.path().display());
    let daemon = DaemonProcess::spawn_http_with_args(
        rule.path().to_str().unwrap(),
        &[
            "--webhook",
            webhook.path().to_str().unwrap(),
            "--dlq",
            &dlq_spec,
        ],
    );

    let (status, _) = http_post(&daemon.url("/api/v1/events"), MATCHING_EVENT);
    assert_eq!(status, 200);

    // attempts: 3 => one initial try plus two retries.
    let dlqd = poll_until(Duration::from_secs(10), || {
        let s = std::fs::read_to_string(dlq.path()).unwrap_or_default();
        (s.contains("webhook slack") && s.contains("HTTP 500")).then_some(())
    });
    assert!(
        dlqd.is_some(),
        "a retryable 5xx should exhaust retries into the DLQ"
    );
    assert!(
        request_count(&rt, &server) >= 2,
        "the webhook should have retried at least once before the DLQ",
    );
}

#[test]
fn webhook_scope_filter_skips_out_of_scope() {
    let rt = rt();
    let server = mock_server(&rt, 200);
    let webhook = temp_file(
        ".yml",
        &WEBHOOK_SCOPED_CFG.replace("__URL__", &server.uri()),
    );
    let rule = temp_file(".yml", SIMPLE_RULE);
    let out = temp_file(".ndjson", "");
    let out_spec = format!("file://{}", out.path().display());
    let daemon = DaemonProcess::spawn_http_with_args(
        rule.path().to_str().unwrap(),
        &[
            "--webhook",
            webhook.path().to_str().unwrap(),
            "--output",
            &out_spec,
        ],
    );

    let (status, _) = http_post(&daemon.url("/api/v1/events"), MATCHING_EVENT);
    assert_eq!(status, 200);

    // The detection reaches the file sink (so we know the event matched)...
    let landed = poll_until(Duration::from_secs(5), || {
        std::fs::read_to_string(out.path())
            .unwrap_or_default()
            .contains("Test Rule")
            .then_some(())
    });
    assert!(landed.is_some(), "detection should reach the file sink");

    // ...but the level-scoped-out webhook made no request. Give the webhook
    // worker (dispatched alongside the file sink) a moment to have skipped.
    std::thread::sleep(Duration::from_millis(300));
    assert_eq!(
        request_count(&rt, &server),
        0,
        "a webhook scoped to critical must not fire for a high-severity detection",
    );
}

#[test]
fn webhook_env_header_is_interpolated() {
    let rt = rt();
    let server = mock_server(&rt, 200);
    let webhook = temp_file(".yml", &WEBHOOK_AUTH_CFG.replace("__URL__", &server.uri()));
    let rule = temp_file(".yml", SIMPLE_RULE);
    let daemon = DaemonProcess::spawn_http_with_args_env(
        rule.path().to_str().unwrap(),
        &["--webhook", webhook.path().to_str().unwrap()],
        &[("RSIGMA_TEST_WEBHOOK_TOKEN", "secret-xyz")],
    );

    let (status, _) = http_post(&daemon.url("/api/v1/events"), MATCHING_EVENT);
    assert_eq!(status, 200);

    let req = poll_until(Duration::from_secs(5), || {
        rt.block_on(server.received_requests())
            .unwrap_or_default()
            .into_iter()
            .next()
    })
    .expect("webhook never made a request");
    assert_eq!(
        req.headers
            .get("authorization")
            .and_then(|v| v.to_str().ok()),
        Some("Bearer secret-xyz"),
        "the env-var header secret should be interpolated at render time",
    );
}

#[test]
fn webhook_signs_requests_when_configured() {
    let rt = rt();
    let server = mock_server(&rt, 200);
    let webhook = temp_file(
        ".yml",
        &WEBHOOK_SIGNED_CFG.replace("__URL__", &server.uri()),
    );
    let rule = temp_file(".yml", SIMPLE_RULE);
    let daemon = DaemonProcess::spawn_http_with_args_env(
        rule.path().to_str().unwrap(),
        &["--webhook", webhook.path().to_str().unwrap()],
        &[("RSIGMA_TEST_WEBHOOK_SECRET", "test-secret")],
    );

    let (status, _) = http_post(&daemon.url("/api/v1/events"), MATCHING_EVENT);
    assert_eq!(status, 200);

    let req = poll_until(Duration::from_secs(5), || {
        rt.block_on(server.received_requests())
            .unwrap_or_default()
            .into_iter()
            .next()
    })
    .expect("webhook never made a request");

    // The default scheme is Standard Webhooks: a signed id, timestamp, and a
    // versioned signature are present.
    assert!(
        req.headers.get("webhook-id").is_some(),
        "missing webhook-id header",
    );
    assert!(
        req.headers.get("webhook-timestamp").is_some(),
        "missing webhook-timestamp header",
    );
    let sig = req
        .headers
        .get("webhook-signature")
        .and_then(|v| v.to_str().ok())
        .unwrap_or_default();
    assert!(
        sig.starts_with("v1,"),
        "expected a v1 signature, got {sig:?}",
    );
}

#[test]
fn webhook_tls_with_ca_routes_unreachable_to_dlq() {
    use rcgen::{BasicConstraints, CertificateParams, IsCa, KeyPair};

    // A private CA the webhook is told to trust. The endpoint is unreachable,
    // so the handshake never happens; this exercises tls.ca file reading, the
    // TLS client build, and the delivery path into the DLQ end to end.
    let mut ca_params = CertificateParams::new(Vec::<String>::new()).unwrap();
    ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
    let ca_key = KeyPair::generate().unwrap();
    let ca_pem = ca_params.self_signed(&ca_key).unwrap().pem();
    let ca = temp_file(".pem", &ca_pem);

    let cfg = TLS_CFG.replace("__CA__", &ca.path().display().to_string());
    let webhook = temp_file(".yml", &cfg);
    let rule = temp_file(".yml", SIMPLE_RULE);
    let dlq = temp_file(".ndjson", "");
    let dlq_spec = format!("file://{}", dlq.path().display());
    let daemon = DaemonProcess::spawn_http_with_args(
        rule.path().to_str().unwrap(),
        &[
            "--webhook",
            webhook.path().to_str().unwrap(),
            "--dlq",
            &dlq_spec,
        ],
    );

    let (status, _) = http_post(&daemon.url("/api/v1/events"), MATCHING_EVENT);
    assert_eq!(status, 200);

    let dlqd = poll_until(Duration::from_secs(10), || {
        std::fs::read_to_string(dlq.path())
            .unwrap_or_default()
            .contains("webhook internal")
            .then_some(())
    });
    assert!(
        dlqd.is_some(),
        "an https webhook with a custom CA should build TLS and route the unreachable delivery to the DLQ",
    );
}

#[test]
fn webhook_does_not_block_file_sink_under_fanout() {
    // The webhook targets a closed port; the co-configured file sink must
    // still receive the detection, proving per-sink worker isolation.
    let webhook = temp_file(
        ".yml",
        &WEBHOOK_CFG.replace("__URL__", "http://127.0.0.1:1"),
    );
    let rule = temp_file(".yml", SIMPLE_RULE);
    let out = temp_file(".ndjson", "");
    let out_spec = format!("file://{}", out.path().display());
    let daemon = DaemonProcess::spawn_http_with_args(
        rule.path().to_str().unwrap(),
        &[
            "--webhook",
            webhook.path().to_str().unwrap(),
            "--output",
            &out_spec,
        ],
    );

    let (status, _) = http_post(&daemon.url("/api/v1/events"), MATCHING_EVENT);
    assert_eq!(status, 200);

    let landed = poll_until(Duration::from_secs(5), || {
        std::fs::read_to_string(out.path())
            .unwrap_or_default()
            .contains("Test Rule")
            .then_some(())
    });
    assert!(
        landed.is_some(),
        "an unreachable webhook must not block the file sink behind it",
    );
}