fukurow_domain_cyber/
patterns.rs

1//! Attack pattern definitions and matching
2
3use fukurow_core::model::{SecurityAction, CyberEvent};
4use std::collections::HashMap;
5
6/// Common attack patterns
7#[derive(Debug, Clone)]
8pub struct AttackPattern {
9    pub name: String,
10    pub description: String,
11    pub indicators: Vec<String>,
12    pub severity: String,
13    pub actions: Vec<SecurityAction>,
14}
15
16/// Pattern-based detector
17pub struct PatternDetector {
18    patterns: Vec<AttackPattern>,
19}
20
21impl PatternDetector {
22    pub fn new() -> Self {
23        let mut detector = Self {
24            patterns: Vec::new(),
25        };
26
27        detector.initialize_patterns();
28        detector
29    }
30
31    fn initialize_patterns(&mut self) {
32        // Ransomware pattern
33        self.patterns.push(AttackPattern {
34            name: "ransomware_execution".to_string(),
35            description: "Detect ransomware execution patterns".to_string(),
36            indicators: vec![
37                "encrypt".to_string(),
38                "bitcoin".to_string(),
39                "ransom".to_string(),
40                ".encrypted".to_string(),
41            ],
42            severity: "critical".to_string(),
43            actions: vec![
44                SecurityAction::IsolateHost {
45                    host_ip: "?host_ip".to_string(),
46                    reason: "Ransomware execution detected".to_string(),
47                },
48                SecurityAction::TerminateProcess {
49                    process_id: 0, // Will be filled by detection logic
50                    reason: "Ransomware process termination".to_string(),
51                },
52                SecurityAction::Alert {
53                    severity: "critical".to_string(),
54                    message: "Ransomware attack detected".to_string(),
55                    details: serde_json::json!({
56                        "pattern": "ransomware_execution",
57                        "indicators": ["encrypt", "bitcoin", "ransom"]
58                    }),
59                },
60            ],
61        });
62
63        // Data exfiltration pattern
64        self.patterns.push(AttackPattern {
65            name: "data_exfiltration".to_string(),
66            description: "Detect large data transfers to external IPs".to_string(),
67            indicators: vec![
68                "large_file_transfer".to_string(),
69                "external_ip".to_string(),
70                "unusual_traffic".to_string(),
71            ],
72            severity: "high".to_string(),
73            actions: vec![
74                SecurityAction::BlockConnection {
75                    source_ip: "?source_ip".to_string(),
76                    dest_ip: "?dest_ip".to_string(),
77                    reason: "Potential data exfiltration detected".to_string(),
78                },
79                SecurityAction::Alert {
80                    severity: "high".to_string(),
81                    message: "Data exfiltration attempt".to_string(),
82                    details: serde_json::json!({
83                        "pattern": "data_exfiltration",
84                        "traffic_type": "large_transfer"
85                    }),
86                },
87            ],
88        });
89
90        // Brute force attack pattern
91        self.patterns.push(AttackPattern {
92            name: "brute_force_login".to_string(),
93            description: "Detect brute force login attempts".to_string(),
94            indicators: vec![
95                "multiple_failed_logins".to_string(),
96                "same_user".to_string(),
97                "rapid_attempts".to_string(),
98            ],
99            severity: "medium".to_string(),
100            actions: vec![
101                SecurityAction::BlockConnection {
102                    source_ip: "?source_ip".to_string(),
103                    dest_ip: "?dest_ip".to_string(),
104                    reason: "Brute force login attempts detected".to_string(),
105                },
106                SecurityAction::Alert {
107                    severity: "medium".to_string(),
108                    message: "Brute force attack detected".to_string(),
109                    details: serde_json::json!({
110                        "pattern": "brute_force_login",
111                        "attempt_count": "?count"
112                    }),
113                },
114            ],
115        });
116    }
117
118    /// Match events against attack patterns
119    pub fn match_patterns(&self, events: &[CyberEvent]) -> Vec<SecurityAction> {
120        let mut actions = Vec::new();
121
122        for pattern in &self.patterns {
123            if self.pattern_matches_events(pattern, events) {
124                actions.extend(pattern.actions.clone());
125            }
126        }
127
128        actions
129    }
130
131    fn pattern_matches_events(&self, pattern: &AttackPattern, events: &[CyberEvent]) -> bool {
132        // Simple pattern matching - in real implementation, this would be more sophisticated
133        for event in events {
134            match event {
135                CyberEvent::ProcessExecution { command_line, .. } => {
136                    if pattern.indicators.iter().any(|indicator| command_line.contains(indicator)) {
137                        return true;
138                    }
139                }
140                CyberEvent::NetworkConnection { .. } => {
141                    // Network pattern matching would go here
142                }
143                CyberEvent::FileAccess { .. } => {
144                    // File access pattern matching would go here
145                }
146                CyberEvent::UserLogin { .. } => {
147                    // Login pattern matching would go here
148                }
149            }
150        }
151        false
152    }
153
154    /// Get all available patterns
155    pub fn get_patterns(&self) -> &[AttackPattern] {
156        &self.patterns
157    }
158}
159
160/// Behavioral anomaly detector
161pub struct AnomalyDetector {
162    baseline_metrics: HashMap<String, f64>,
163}
164
165impl AnomalyDetector {
166    pub fn new() -> Self {
167        Self {
168            baseline_metrics: HashMap::new(),
169        }
170    }
171
172    /// Update baseline metrics
173    pub fn update_baseline(&mut self, metric_name: String, value: f64) {
174        self.baseline_metrics.insert(metric_name, value);
175    }
176
177    /// Detect anomalies in metrics
178    pub fn detect_anomaly(&self, metric_name: &str, current_value: f64, threshold: f64) -> Option<SecurityAction> {
179        if let Some(baseline) = self.baseline_metrics.get(metric_name) {
180            let deviation = (current_value - baseline).abs() / baseline;
181
182            if deviation > threshold {
183                return Some(SecurityAction::Alert {
184                    severity: "medium".to_string(),
185                    message: format!("Anomaly detected in {}", metric_name),
186                    details: serde_json::json!({
187                        "metric": metric_name,
188                        "baseline": baseline,
189                        "current": current_value,
190                        "deviation_percent": deviation * 100.0
191                    }),
192                });
193            }
194        }
195        None
196    }
197}