detect_threats/
detect_threats.rs

1//! Threat detection example
2//!
3//! This example demonstrates real-time threat detection for SIEM integration.
4
5use chrono::Utc;
6use rust_threat_detector::{LogEntry, ThreatDetector, ThreatSeverity};
7use std::collections::HashMap;
8
9fn main() {
10    println!("=== SIEM Threat Detection System ===\n");
11
12    // Create threat detector with default patterns
13    let mut detector = ThreatDetector::new();
14
15    // Simulate various security logs
16    #[allow(clippy::useless_vec)]
17    let logs = vec![
18        LogEntry {
19            timestamp: Utc::now(),
20            source_ip: Some("192.168.1.100".to_string()),
21            user: Some("admin".to_string()),
22            event_type: "authentication".to_string(),
23            message: "Failed login attempt for user admin from 192.168.1.100".to_string(),
24            metadata: HashMap::new(),
25        },
26        LogEntry {
27            timestamp: Utc::now(),
28            source_ip: Some("10.0.0.50".to_string()),
29            user: Some("user123".to_string()),
30            event_type: "file_access".to_string(),
31            message: "Malware detected in downloaded file: trojan.exe".to_string(),
32            metadata: HashMap::new(),
33        },
34        LogEntry {
35            timestamp: Utc::now(),
36            source_ip: Some("172.16.0.10".to_string()),
37            user: Some("dbuser".to_string()),
38            event_type: "database_query".to_string(),
39            message: "Query: SELECT * FROM users WHERE id='1' OR '1'='1'".to_string(),
40            metadata: HashMap::new(),
41        },
42        LogEntry {
43            timestamp: Utc::now(),
44            source_ip: Some("192.168.1.200".to_string()),
45            user: Some("operator".to_string()),
46            event_type: "system".to_string(),
47            message: "Privilege escalation attempt: unauthorized sudo command".to_string(),
48            metadata: HashMap::new(),
49        },
50        LogEntry {
51            timestamp: Utc::now(),
52            source_ip: Some("10.1.1.50".to_string()),
53            user: Some("ftpuser".to_string()),
54            event_type: "network".to_string(),
55            message: "Large data transfer detected: 500GB uploaded".to_string(),
56            metadata: HashMap::new(),
57        },
58        LogEntry {
59            timestamp: Utc::now(),
60            source_ip: Some("192.168.1.150".to_string()),
61            user: Some("john.doe".to_string()),
62            event_type: "application".to_string(),
63            message: "User successfully logged in to web portal".to_string(),
64            metadata: HashMap::new(),
65        },
66    ];
67
68    println!("Analyzing {} log entries for threats...\n", logs.len());
69
70    let mut all_alerts = Vec::new();
71    let mut critical_count = 0;
72    let mut high_count = 0;
73    let mut medium_count = 0;
74
75    for (i, log) in logs.iter().enumerate() {
76        println!("Log #{}: {}", i + 1, log.message);
77
78        let alerts = detector.analyze(log);
79
80        if alerts.is_empty() {
81            println!("   ✓ No threats detected\n");
82        } else {
83            for alert in &alerts {
84                println!("   🚨 ALERT: {}", alert.alert_id);
85                println!("      Severity: {:?}", alert.severity);
86                println!("      Category: {:?}", alert.category);
87                println!("      Description: {}", alert.description);
88                println!("      Action: {}", alert.recommended_action);
89                println!();
90
91                match alert.severity {
92                    ThreatSeverity::Critical => critical_count += 1,
93                    ThreatSeverity::High => high_count += 1,
94                    ThreatSeverity::Medium => medium_count += 1,
95                    _ => {}
96                }
97            }
98            all_alerts.extend(alerts);
99        }
100    }
101
102    // Summary statistics
103    println!("=== Detection Summary ===");
104    println!("Total logs analyzed: {}", logs.len());
105    println!("Total alerts generated: {}", all_alerts.len());
106    println!("  Critical: {}", critical_count);
107    println!("  High: {}", high_count);
108    println!("  Medium: {}", medium_count);
109
110    // Filter critical alerts
111    println!("\n=== Critical Alerts (Requires Immediate Action) ===");
112    let critical_alerts = detector.filter_by_severity(&all_alerts, ThreatSeverity::Critical);
113
114    for alert in &critical_alerts {
115        println!("\n{}", alert.alert_id);
116        println!("  Category: {:?}", alert.category);
117        println!("  Description: {}", alert.description);
118        println!("  Source: {}", alert.source_log);
119        println!("  Action Required: {}", alert.recommended_action);
120    }
121
122    // Export alerts as JSON for SIEM
123    println!("\n=== SIEM Integration Example ===");
124    if let Some(first_alert) = all_alerts.first() {
125        match first_alert.to_json() {
126            Ok(json) => {
127                println!("Alert JSON format:");
128                println!("{}", json);
129            }
130            Err(e) => eprintln!("JSON export error: {}", e),
131        }
132    }
133
134    // Detector statistics
135    println!("\n=== Detector Statistics ===");
136    let stats = detector.get_stats();
137    for (key, value) in stats {
138        println!("  {}: {}", key, value);
139    }
140
141    println!("\n=== Security Features ===");
142    println!("✓ Memory-safe threat detection (no buffer overflows)");
143    println!("✓ Real-time log analysis");
144    println!("✓ Pre-configured threat patterns");
145    println!("✓ Severity-based alerting");
146    println!("✓ SIEM integration ready (JSON export)");
147    println!("✓ Custom pattern support");
148
149    println!("\n=== Compliance Use Cases ===");
150    println!("✓ NIST SP 800-92 - Security log management");
151    println!("✓ PCI-DSS Requirement 10 - Log monitoring");
152    println!("✓ SOX compliance - IT control monitoring");
153    println!("✓ GDPR - Security incident detection");
154    println!("✓ MITRE ATT&CK - Threat pattern matching");
155}