pub struct ThreatDetector { /* private fields */ }Expand description
Threat detector
ImplementationsΒ§
SourceΒ§impl ThreatDetector
impl ThreatDetector
Sourcepub fn new() -> Self
pub fn new() -> Self
Create a new threat detector with default patterns
Examples found in repository?
examples/detect_threats.rs (line 13)
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}Sourcepub fn add_pattern(&mut self, pattern: ThreatPattern)
pub fn add_pattern(&mut self, pattern: ThreatPattern)
Add a custom threat pattern
Sourcepub fn analyze(&mut self, log: &LogEntry) -> Vec<ThreatAlert>
pub fn analyze(&mut self, log: &LogEntry) -> Vec<ThreatAlert>
Analyze a log entry for threats
Examples found in repository?
examples/detect_threats.rs (line 78)
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}Sourcepub fn analyze_batch(&mut self, logs: &[LogEntry]) -> Vec<ThreatAlert>
pub fn analyze_batch(&mut self, logs: &[LogEntry]) -> Vec<ThreatAlert>
Analyze multiple log entries in batch
Sourcepub fn get_alert_history(&self, since: DateTime<Utc>) -> Vec<&ThreatAlert>
pub fn get_alert_history(&self, since: DateTime<Utc>) -> Vec<&ThreatAlert>
Get alert history for a time window
Sourcepub fn deduplicate_alerts(&mut self, window_minutes: i64) -> usize
pub fn deduplicate_alerts(&mut self, window_minutes: i64) -> usize
Deduplicate alerts by removing similar alerts within time window
Sourcepub fn clear_old_alerts(&mut self, before: DateTime<Utc>)
pub fn clear_old_alerts(&mut self, before: DateTime<Utc>)
Clear old alerts from history (memory management)
Sourcepub fn get_stats(&self) -> HashMap<String, usize>
pub fn get_stats(&self) -> HashMap<String, usize>
Get statistics
Examples found in repository?
examples/detect_threats.rs (line 136)
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}Sourcepub fn filter_by_severity(
&self,
alerts: &[ThreatAlert],
min_severity: ThreatSeverity,
) -> Vec<ThreatAlert>
pub fn filter_by_severity( &self, alerts: &[ThreatAlert], min_severity: ThreatSeverity, ) -> Vec<ThreatAlert>
Get alerts by severity
Examples found in repository?
examples/detect_threats.rs (line 112)
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}Sourcepub fn filter_by_category(
&self,
alerts: &[ThreatAlert],
category: &ThreatCategory,
) -> Vec<ThreatAlert>
pub fn filter_by_category( &self, alerts: &[ThreatAlert], category: &ThreatCategory, ) -> Vec<ThreatAlert>
Get alerts by category
Trait ImplementationsΒ§
Auto Trait ImplementationsΒ§
impl Freeze for ThreatDetector
impl RefUnwindSafe for ThreatDetector
impl Send for ThreatDetector
impl Sync for ThreatDetector
impl Unpin for ThreatDetector
impl UnwindSafe for ThreatDetector
Blanket ImplementationsΒ§
SourceΒ§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
SourceΒ§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more