detect_threats/
detect_threats.rs

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