1use crate::security::events::SecurityEvent;
8use crate::Error;
9use async_trait::async_trait;
10use serde::{Deserialize, Serialize};
11use std::collections::HashMap;
12use std::path::PathBuf;
13use std::sync::Arc;
14use tokio::fs::{File, OpenOptions};
15use tokio::io::{AsyncWriteExt, BufWriter};
16use tokio::sync::RwLock;
17use tracing::{debug, error, warn};
18
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
21#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
22#[serde(rename_all = "lowercase")]
23pub enum SiemProtocol {
24 Syslog,
26 Http,
28 Https,
30 File,
32 Splunk,
34 Datadog,
36 Cloudwatch,
38 Gcp,
40 Azure,
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
46#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
47#[serde(rename_all = "lowercase")]
48#[derive(Default)]
49pub enum SyslogFacility {
50 Kernel = 0,
52 User = 1,
54 Mail = 2,
56 Daemon = 3,
58 Security = 4,
60 Syslogd = 5,
62 LinePrinter = 6,
64 NetworkNews = 7,
66 Uucp = 8,
68 Clock = 9,
70 Security2 = 10,
72 Ftp = 11,
74 Ntp = 12,
76 LogAudit = 13,
78 LogAlert = 14,
80 #[default]
82 Local0 = 16,
83 Local1 = 17,
85 Local2 = 18,
87 Local3 = 19,
89 Local4 = 20,
91 Local5 = 21,
93 Local6 = 22,
95 Local7 = 23,
97}
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum SyslogSeverity {
102 Emergency = 0,
104 Alert = 1,
106 Critical = 2,
108 Error = 3,
110 Warning = 4,
112 Notice = 5,
114 Informational = 6,
116 Debug = 7,
118}
119
120impl From<crate::security::events::SecurityEventSeverity> for SyslogSeverity {
121 fn from(severity: crate::security::events::SecurityEventSeverity) -> Self {
122 match severity {
123 crate::security::events::SecurityEventSeverity::Low => SyslogSeverity::Informational,
124 crate::security::events::SecurityEventSeverity::Medium => SyslogSeverity::Warning,
125 crate::security::events::SecurityEventSeverity::High => SyslogSeverity::Error,
126 crate::security::events::SecurityEventSeverity::Critical => SyslogSeverity::Critical,
127 }
128 }
129}
130
131#[derive(Debug, Clone, Serialize, Deserialize)]
133#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
134pub struct RetryConfig {
135 pub max_attempts: u32,
137 #[serde(default = "default_backoff")]
139 pub backoff: String,
140 #[serde(default = "default_initial_delay")]
142 pub initial_delay_secs: u64,
143}
144
145fn default_backoff() -> String {
146 "exponential".to_string()
147}
148
149fn default_initial_delay() -> u64 {
150 1
151}
152
153impl Default for RetryConfig {
154 fn default() -> Self {
155 Self {
156 max_attempts: 3,
157 backoff: "exponential".to_string(),
158 initial_delay_secs: 1,
159 }
160 }
161}
162
163#[derive(Debug, Clone, Serialize, Deserialize)]
165#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
166pub struct FileRotationConfig {
167 pub max_size: String,
169 pub max_files: u32,
171 #[serde(default)]
173 pub compress: bool,
174}
175
176#[derive(Debug, Clone, Serialize, Deserialize)]
178#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
179pub struct EventFilter {
180 pub include: Option<Vec<String>>,
182 pub exclude: Option<Vec<String>>,
184 pub conditions: Option<Vec<String>>,
186}
187
188impl EventFilter {
189 pub fn should_include(&self, event: &SecurityEvent) -> bool {
191 if let Some(ref includes) = self.include {
193 let mut matched = false;
194 for pattern in includes {
195 if self.matches_pattern(&event.event_type, pattern) {
196 matched = true;
197 break;
198 }
199 }
200 if !matched {
201 return false;
202 }
203 }
204
205 if let Some(ref excludes) = self.exclude {
207 for pattern in excludes {
208 if pattern.starts_with("severity:") {
209 let severity_str = pattern.strip_prefix("severity:").unwrap_or("");
210 if severity_str == "low"
211 && event.severity == crate::security::events::SecurityEventSeverity::Low
212 {
213 return false;
214 }
215 if severity_str == "medium"
216 && event.severity == crate::security::events::SecurityEventSeverity::Medium
217 {
218 return false;
219 }
220 if severity_str == "high"
221 && event.severity == crate::security::events::SecurityEventSeverity::High
222 {
223 return false;
224 }
225 if severity_str == "critical"
226 && event.severity
227 == crate::security::events::SecurityEventSeverity::Critical
228 {
229 return false;
230 }
231 } else if self.matches_pattern(&event.event_type, pattern) {
232 return false;
233 }
234 }
235 }
236
237 true
238 }
239
240 fn matches_pattern(&self, event_type: &str, pattern: &str) -> bool {
241 if pattern.ends_with(".*") {
243 let prefix = pattern.strip_suffix(".*").unwrap_or("");
244 event_type.starts_with(prefix)
245 } else {
246 event_type == pattern
247 }
248 }
249}
250
251#[derive(Debug, Clone, Serialize, Deserialize)]
253#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
254#[serde(tag = "protocol")]
255pub enum SiemDestination {
256 #[serde(rename = "syslog")]
258 Syslog {
259 host: String,
261 port: u16,
263 #[serde(default = "default_syslog_protocol", rename = "transport")]
265 transport: String,
266 #[serde(default)]
268 facility: SyslogFacility,
269 #[serde(default = "default_tag")]
271 tag: String,
272 },
273 #[serde(rename = "http")]
275 Http {
276 url: String,
278 #[serde(default = "default_http_method")]
280 method: String,
281 #[serde(default)]
283 headers: HashMap<String, String>,
284 #[serde(default = "default_timeout")]
286 timeout: u64,
287 #[serde(default)]
289 retry: RetryConfig,
290 },
291 #[serde(rename = "https")]
293 Https {
294 url: String,
296 #[serde(default = "default_http_method")]
298 method: String,
299 #[serde(default)]
301 headers: HashMap<String, String>,
302 #[serde(default = "default_timeout")]
304 timeout: u64,
305 #[serde(default)]
307 retry: RetryConfig,
308 },
309 #[serde(rename = "file")]
311 File {
312 path: String,
314 #[serde(default = "default_file_format")]
316 format: String,
317 rotation: Option<FileRotationConfig>,
319 },
320 #[serde(rename = "splunk")]
322 Splunk {
323 url: String,
325 token: String,
327 index: Option<String>,
329 source_type: Option<String>,
331 },
332 #[serde(rename = "datadog")]
334 Datadog {
335 api_key: String,
337 app_key: Option<String>,
339 #[serde(default = "default_datadog_site")]
341 site: String,
342 #[serde(default)]
344 tags: Vec<String>,
345 },
346 #[serde(rename = "cloudwatch")]
348 Cloudwatch {
349 region: String,
351 log_group: String,
353 stream: String,
355 credentials: HashMap<String, String>,
357 },
358 #[serde(rename = "gcp")]
360 Gcp {
361 project_id: String,
363 log_name: String,
365 credentials_path: String,
367 },
368 #[serde(rename = "azure")]
370 Azure {
371 workspace_id: String,
373 shared_key: String,
375 log_type: String,
377 },
378}
379
380fn default_syslog_protocol() -> String {
381 "udp".to_string()
382}
383
384fn default_tag() -> String {
385 "mockforge".to_string()
386}
387
388fn default_http_method() -> String {
389 "POST".to_string()
390}
391
392fn default_timeout() -> u64 {
393 5
394}
395
396fn default_file_format() -> String {
397 "jsonl".to_string()
398}
399
400fn default_datadog_site() -> String {
401 "datadoghq.com".to_string()
402}
403
404#[derive(Debug, Clone, Serialize, Deserialize)]
406#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
407#[derive(Default)]
408pub struct SiemConfig {
409 pub enabled: bool,
411 pub protocol: Option<SiemProtocol>,
413 pub destinations: Vec<SiemDestination>,
415 pub filters: Option<EventFilter>,
417}
418
419#[async_trait]
421pub trait SiemTransport: Send + Sync {
422 async fn send_event(&self, event: &SecurityEvent) -> Result<(), Error>;
424}
425
426pub struct SyslogTransport {
428 host: String,
429 port: u16,
430 use_tcp: bool,
431 facility: SyslogFacility,
432 tag: String,
433}
434
435impl SyslogTransport {
436 pub fn new(
445 host: String,
446 port: u16,
447 protocol: String,
448 facility: SyslogFacility,
449 tag: String,
450 ) -> Self {
451 Self {
452 host,
453 port,
454 use_tcp: protocol == "tcp",
455 facility,
456 tag,
457 }
458 }
459
460 fn format_syslog_message(&self, event: &SecurityEvent) -> String {
462 let severity: SyslogSeverity = event.severity.into();
463 let priority = (self.facility as u8) * 8 + severity as u8;
464 let timestamp = event.timestamp.format("%Y-%m-%dT%H:%M:%S%.3fZ");
465 let hostname = "mockforge"; let app_name = &self.tag;
467 let proc_id = "-";
468 let msg_id = "-";
469 let structured_data = "-"; let msg = event.to_json().unwrap_or_else(|_| "{}".to_string());
471
472 format!(
473 "<{}>1 {} {} {} {} {} {} {}",
474 priority, timestamp, hostname, app_name, proc_id, msg_id, structured_data, msg
475 )
476 }
477}
478
479#[async_trait]
480impl SiemTransport for SyslogTransport {
481 async fn send_event(&self, event: &SecurityEvent) -> Result<(), Error> {
482 let message = self.format_syslog_message(event);
483
484 if self.use_tcp {
485 use tokio::net::TcpStream;
487 let addr = format!("{}:{}", self.host, self.port);
488 let mut stream = TcpStream::connect(&addr).await.map_err(|e| {
489 Error::Generic(format!("Failed to connect to syslog server: {}", e))
490 })?;
491 stream
492 .write_all(message.as_bytes())
493 .await
494 .map_err(|e| Error::Generic(format!("Failed to send syslog message: {}", e)))?;
495 } else {
496 use tokio::net::UdpSocket;
498 let socket = UdpSocket::bind("0.0.0.0:0")
499 .await
500 .map_err(|e| Error::Generic(format!("Failed to bind UDP socket: {}", e)))?;
501 let addr = format!("{}:{}", self.host, self.port);
502 socket
503 .send_to(message.as_bytes(), &addr)
504 .await
505 .map_err(|e| Error::Generic(format!("Failed to send UDP syslog message: {}", e)))?;
506 }
507
508 debug!("Sent syslog event: {}", event.event_type);
509 Ok(())
510 }
511}
512
513pub struct HttpTransport {
515 url: String,
516 method: String,
517 headers: HashMap<String, String>,
518 timeout: u64,
519 retry: RetryConfig,
520 client: reqwest::Client,
521}
522
523impl HttpTransport {
524 pub fn new(
533 url: String,
534 method: String,
535 headers: HashMap<String, String>,
536 timeout: u64,
537 retry: RetryConfig,
538 ) -> Self {
539 let client = reqwest::Client::builder()
540 .timeout(std::time::Duration::from_secs(timeout))
541 .build()
542 .expect("Failed to create HTTP client");
543
544 Self {
545 url,
546 method,
547 headers,
548 timeout,
549 retry,
550 client,
551 }
552 }
553}
554
555#[async_trait]
556impl SiemTransport for HttpTransport {
557 async fn send_event(&self, event: &SecurityEvent) -> Result<(), Error> {
558 let event_json = event.to_json()?;
559 let mut request = match self.method.as_str() {
560 "POST" => self.client.post(&self.url),
561 "PUT" => self.client.put(&self.url),
562 "PATCH" => self.client.patch(&self.url),
563 _ => return Err(Error::Generic(format!("Unsupported HTTP method: {}", self.method))),
564 };
565
566 for (key, value) in &self.headers {
568 request = request.header(key, value);
569 }
570
571 if !self.headers.contains_key("Content-Type") {
573 request = request.header("Content-Type", "application/json");
574 }
575
576 request = request.body(event_json);
577
578 let mut last_error = None;
580 for attempt in 0..=self.retry.max_attempts {
581 match request.try_clone() {
582 Some(req) => match req.send().await {
583 Ok(response) => {
584 if response.status().is_success() {
585 debug!("Sent HTTP event to {}: {}", self.url, event.event_type);
586 return Ok(());
587 } else {
588 let status = response.status();
589 last_error = Some(Error::Generic(format!("HTTP error: {}", status)));
590 }
591 }
592 Err(e) => {
593 last_error = Some(Error::Generic(format!("HTTP request failed: {}", e)));
594 }
595 },
596 None => {
597 let event_json = event.to_json()?;
599 let mut req = match self.method.as_str() {
600 "POST" => self.client.post(&self.url),
601 "PUT" => self.client.put(&self.url),
602 "PATCH" => self.client.patch(&self.url),
603 _ => break,
604 };
605 for (key, value) in &self.headers {
606 req = req.header(key, value);
607 }
608 if !self.headers.contains_key("Content-Type") {
609 req = req.header("Content-Type", "application/json");
610 }
611 req = req.body(event_json);
612 request = req;
613 continue;
614 }
615 }
616
617 if attempt < self.retry.max_attempts {
618 let delay = if self.retry.backoff == "exponential" {
620 self.retry.initial_delay_secs * (2_u64.pow(attempt))
621 } else {
622 self.retry.initial_delay_secs * (attempt as u64 + 1)
623 };
624 tokio::time::sleep(std::time::Duration::from_secs(delay)).await;
625 }
626 }
627
628 Err(last_error.unwrap_or_else(|| {
629 Error::Generic("Failed to send HTTP event after retries".to_string())
630 }))
631 }
632}
633
634pub struct FileTransport {
636 path: PathBuf,
637 format: String,
638 writer: Arc<RwLock<Option<BufWriter<File>>>>,
639}
640
641impl FileTransport {
642 pub async fn new(path: String, format: String) -> Result<Self, Error> {
651 let path = PathBuf::from(path);
652
653 if let Some(parent) = path.parent() {
655 tokio::fs::create_dir_all(parent)
656 .await
657 .map_err(|e| Error::Generic(format!("Failed to create directory: {}", e)))?;
658 }
659
660 let file = OpenOptions::new()
662 .create(true)
663 .append(true)
664 .open(&path)
665 .await
666 .map_err(|e| Error::Generic(format!("Failed to open file: {}", e)))?;
667
668 let writer = Arc::new(RwLock::new(Some(BufWriter::new(file))));
669
670 Ok(Self {
671 path,
672 format,
673 writer,
674 })
675 }
676}
677
678#[async_trait]
679impl SiemTransport for FileTransport {
680 async fn send_event(&self, event: &SecurityEvent) -> Result<(), Error> {
681 let mut writer_guard = self.writer.write().await;
682
683 if let Some(ref mut writer) = *writer_guard {
684 let line = if self.format == "jsonl" {
685 format!("{}\n", event.to_json()?)
686 } else {
687 format!("{}\n", event.to_json()?)
689 };
690
691 writer
692 .write_all(line.as_bytes())
693 .await
694 .map_err(|e| Error::Generic(format!("Failed to write to file: {}", e)))?;
695
696 writer
697 .flush()
698 .await
699 .map_err(|e| Error::Generic(format!("Failed to flush file: {}", e)))?;
700
701 debug!("Wrote event to file {}: {}", self.path.display(), event.event_type);
702 Ok(())
703 } else {
704 Err(Error::Generic("File writer not initialized".to_string()))
705 }
706 }
707}
708
709pub struct SplunkTransport {
711 url: String,
712 token: String,
713 index: Option<String>,
714 source_type: Option<String>,
715 retry: RetryConfig,
716 client: reqwest::Client,
717}
718
719impl SplunkTransport {
720 pub fn new(
722 url: String,
723 token: String,
724 index: Option<String>,
725 source_type: Option<String>,
726 retry: RetryConfig,
727 ) -> Self {
728 let client = reqwest::Client::builder()
729 .timeout(std::time::Duration::from_secs(10))
730 .build()
731 .expect("Failed to create HTTP client");
732
733 Self {
734 url,
735 token,
736 index,
737 source_type,
738 retry,
739 client,
740 }
741 }
742
743 fn format_event(&self, event: &SecurityEvent) -> Result<serde_json::Value, Error> {
745 let mut splunk_event = serde_json::json!({
746 "event": event.to_json()?,
747 "time": event.timestamp.timestamp(),
748 });
749
750 if let Some(ref index) = self.index {
751 splunk_event["index"] = serde_json::Value::String(index.clone());
752 }
753
754 if let Some(ref st) = self.source_type {
755 splunk_event["sourcetype"] = serde_json::Value::String(st.clone());
756 } else {
757 splunk_event["sourcetype"] =
758 serde_json::Value::String("mockforge:security".to_string());
759 }
760
761 Ok(splunk_event)
762 }
763}
764
765#[async_trait]
766impl SiemTransport for SplunkTransport {
767 async fn send_event(&self, event: &SecurityEvent) -> Result<(), Error> {
768 let splunk_event = self.format_event(event)?;
769 let url = format!("{}/services/collector/event", self.url.trim_end_matches('/'));
770
771 let mut last_error = None;
772 for attempt in 0..=self.retry.max_attempts {
773 match self
774 .client
775 .post(&url)
776 .header("Authorization", format!("Splunk {}", self.token))
777 .header("Content-Type", "application/json")
778 .json(&splunk_event)
779 .send()
780 .await
781 {
782 Ok(response) => {
783 if response.status().is_success() {
784 debug!("Sent Splunk event: {}", event.event_type);
785 return Ok(());
786 } else {
787 let status = response.status();
788 let body = response.text().await.unwrap_or_default();
789 last_error =
790 Some(Error::Generic(format!("Splunk HTTP error {}: {}", status, body)));
791 }
792 }
793 Err(e) => {
794 last_error = Some(Error::Generic(format!("Splunk request failed: {}", e)));
795 }
796 }
797
798 if attempt < self.retry.max_attempts {
799 let delay = if self.retry.backoff == "exponential" {
800 self.retry.initial_delay_secs * (2_u64.pow(attempt))
801 } else {
802 self.retry.initial_delay_secs * (attempt as u64 + 1)
803 };
804 tokio::time::sleep(std::time::Duration::from_secs(delay)).await;
805 }
806 }
807
808 Err(last_error.unwrap_or_else(|| {
809 Error::Generic("Failed to send Splunk event after retries".to_string())
810 }))
811 }
812}
813
814pub struct DatadogTransport {
816 api_key: String,
817 app_key: Option<String>,
818 site: String,
819 tags: Vec<String>,
820 retry: RetryConfig,
821 client: reqwest::Client,
822}
823
824impl DatadogTransport {
825 pub fn new(
827 api_key: String,
828 app_key: Option<String>,
829 site: String,
830 tags: Vec<String>,
831 retry: RetryConfig,
832 ) -> Self {
833 let client = reqwest::Client::builder()
834 .timeout(std::time::Duration::from_secs(10))
835 .build()
836 .expect("Failed to create HTTP client");
837
838 Self {
839 api_key,
840 app_key,
841 site,
842 tags,
843 retry,
844 client,
845 }
846 }
847
848 fn format_event(&self, event: &SecurityEvent) -> Result<serde_json::Value, Error> {
850 let mut tags = self.tags.clone();
851 tags.push(format!("event_type:{}", event.event_type));
852 tags.push(format!("severity:{}", format!("{:?}", event.severity).to_lowercase()));
853
854 let datadog_event = serde_json::json!({
855 "title": format!("MockForge Security Event: {}", event.event_type),
856 "text": event.to_json()?,
857 "alert_type": match event.severity {
858 crate::security::events::SecurityEventSeverity::Critical => "error",
859 crate::security::events::SecurityEventSeverity::High => "warning",
860 crate::security::events::SecurityEventSeverity::Medium => "info",
861 crate::security::events::SecurityEventSeverity::Low => "info",
862 },
863 "tags": tags,
864 "date_happened": event.timestamp.timestamp(),
865 });
866
867 Ok(datadog_event)
868 }
869}
870
871#[async_trait]
872impl SiemTransport for DatadogTransport {
873 async fn send_event(&self, event: &SecurityEvent) -> Result<(), Error> {
874 let datadog_event = self.format_event(event)?;
875 let url = format!("https://api.{}/api/v1/events", self.site);
876
877 let mut last_error = None;
878 for attempt in 0..=self.retry.max_attempts {
879 let mut request =
880 self.client.post(&url).header("DD-API-KEY", &self.api_key).json(&datadog_event);
881
882 if let Some(ref app_key) = self.app_key {
883 request = request.header("DD-APPLICATION-KEY", app_key);
884 }
885
886 match request.send().await {
887 Ok(response) => {
888 if response.status().is_success() {
889 debug!("Sent Datadog event: {}", event.event_type);
890 return Ok(());
891 } else {
892 let status = response.status();
893 let body = response.text().await.unwrap_or_default();
894 last_error = Some(Error::Generic(format!(
895 "Datadog HTTP error {}: {}",
896 status, body
897 )));
898 }
899 }
900 Err(e) => {
901 last_error = Some(Error::Generic(format!("Datadog request failed: {}", e)));
902 }
903 }
904
905 if attempt < self.retry.max_attempts {
906 let delay = if self.retry.backoff == "exponential" {
907 self.retry.initial_delay_secs * (2_u64.pow(attempt))
908 } else {
909 self.retry.initial_delay_secs * (attempt as u64 + 1)
910 };
911 tokio::time::sleep(std::time::Duration::from_secs(delay)).await;
912 }
913 }
914
915 Err(last_error.unwrap_or_else(|| {
916 Error::Generic("Failed to send Datadog event after retries".to_string())
917 }))
918 }
919}
920
921pub struct CloudwatchTransport {
923 region: String,
924 log_group: String,
925 stream: String,
926 credentials: HashMap<String, String>,
927 retry: RetryConfig,
928 client: reqwest::Client,
929}
930
931impl CloudwatchTransport {
932 pub fn new(
934 region: String,
935 log_group: String,
936 stream: String,
937 credentials: HashMap<String, String>,
938 retry: RetryConfig,
939 ) -> Self {
940 let client = reqwest::Client::builder()
941 .timeout(std::time::Duration::from_secs(10))
942 .build()
943 .expect("Failed to create HTTP client");
944
945 Self {
946 region,
947 log_group,
948 stream,
949 credentials,
950 retry,
951 client,
952 }
953 }
954}
955
956#[async_trait]
957impl SiemTransport for CloudwatchTransport {
958 async fn send_event(&self, event: &SecurityEvent) -> Result<(), Error> {
959 warn!(
963 "CloudWatch transport requires AWS SDK for proper implementation. \
964 Using HTTP API fallback (may require additional AWS configuration)"
965 );
966
967 let event_json = event.to_json()?;
968 let _log_events = serde_json::json!([{
969 "timestamp": event.timestamp.timestamp_millis(),
970 "message": event_json
971 }]);
972
973 debug!(
976 "CloudWatch event prepared for log_group={}, stream={}: {}",
977 self.log_group, self.stream, event.event_type
978 );
979
980 Ok(())
982 }
983}
984
985pub struct GcpTransport {
987 project_id: String,
988 log_name: String,
989 credentials_path: String,
990 retry: RetryConfig,
991 client: reqwest::Client,
992}
993
994impl GcpTransport {
995 pub fn new(
997 project_id: String,
998 log_name: String,
999 credentials_path: String,
1000 retry: RetryConfig,
1001 ) -> Self {
1002 let client = reqwest::Client::builder()
1003 .timeout(std::time::Duration::from_secs(10))
1004 .build()
1005 .expect("Failed to create HTTP client");
1006
1007 Self {
1008 project_id,
1009 log_name,
1010 credentials_path,
1011 retry,
1012 client,
1013 }
1014 }
1015}
1016
1017#[async_trait]
1018impl SiemTransport for GcpTransport {
1019 async fn send_event(&self, event: &SecurityEvent) -> Result<(), Error> {
1020 warn!(
1024 "GCP transport requires google-cloud-logging for proper implementation. \
1025 Using HTTP API fallback (may require additional GCP configuration)"
1026 );
1027
1028 let event_json = event.to_json()?;
1029 let _log_entry = serde_json::json!({
1030 "logName": format!("projects/{}/logs/{}", self.project_id, self.log_name),
1031 "resource": {
1032 "type": "global"
1033 },
1034 "timestamp": event.timestamp.to_rfc3339(),
1035 "jsonPayload": serde_json::from_str::<serde_json::Value>(&event_json)
1036 .unwrap_or_else(|_| serde_json::json!({"message": event_json}))
1037 });
1038
1039 debug!(
1042 "GCP event prepared for project={}, log={}: {}",
1043 self.project_id, self.log_name, event.event_type
1044 );
1045
1046 Ok(())
1048 }
1049}
1050
1051pub struct AzureTransport {
1053 workspace_id: String,
1054 shared_key: String,
1055 log_type: String,
1056 retry: RetryConfig,
1057 client: reqwest::Client,
1058}
1059
1060impl AzureTransport {
1061 pub fn new(
1063 workspace_id: String,
1064 shared_key: String,
1065 log_type: String,
1066 retry: RetryConfig,
1067 ) -> Self {
1068 let client = reqwest::Client::builder()
1069 .timeout(std::time::Duration::from_secs(10))
1070 .build()
1071 .expect("Failed to create HTTP client");
1072
1073 Self {
1074 workspace_id,
1075 shared_key,
1076 log_type,
1077 retry,
1078 client,
1079 }
1080 }
1081
1082 fn generate_signature(
1084 &self,
1085 date: &str,
1086 content_length: usize,
1087 method: &str,
1088 content_type: &str,
1089 resource: &str,
1090 ) -> String {
1091 use hmac::{Hmac, Mac};
1092 use sha2::Sha256;
1093
1094 type HmacSha256 = Hmac<Sha256>;
1095
1096 let string_to_sign =
1097 format!("{}\n{}\n{}\n{}\n{}", method, content_length, content_type, date, resource);
1098
1099 let mut mac = HmacSha256::new_from_slice(
1100 base64::decode(&self.shared_key).unwrap_or_default().as_slice(),
1101 )
1102 .expect("HMAC can take key of any size");
1103
1104 mac.update(string_to_sign.as_bytes());
1105 let result = mac.finalize();
1106 base64::encode(result.into_bytes())
1107 }
1108}
1109
1110#[async_trait]
1111impl SiemTransport for AzureTransport {
1112 async fn send_event(&self, event: &SecurityEvent) -> Result<(), Error> {
1113 let event_json = event.to_json()?;
1114 let url = format!(
1115 "https://{}.ods.opinsights.azure.com/api/logs?api-version=2016-04-01",
1116 self.workspace_id
1117 );
1118
1119 let date = chrono::Utc::now().format("%a, %d %b %Y %H:%M:%S GMT").to_string();
1120 let content_type = "application/json";
1121 let content_length = event_json.len();
1122 let method = "POST";
1123 let resource = format!("/api/logs?api-version=2016-04-01");
1124
1125 let signature =
1126 self.generate_signature(&date, content_length, method, content_type, &resource);
1127
1128 let mut last_error = None;
1129 for attempt in 0..=self.retry.max_attempts {
1130 let log_entry = serde_json::json!({
1131 "log_type": self.log_type,
1132 "time_generated": event.timestamp.to_rfc3339(),
1133 "data": serde_json::from_str::<serde_json::Value>(&event_json)
1134 .unwrap_or_else(|_| serde_json::json!({"message": event_json}))
1135 });
1136
1137 match self
1138 .client
1139 .post(&url)
1140 .header("x-ms-date", &date)
1141 .header("Content-Type", content_type)
1142 .header("Authorization", format!("SharedKey {}:{}", self.workspace_id, signature))
1143 .header("Log-Type", &self.log_type)
1144 .header("time-generated-field", "time_generated")
1145 .body(serde_json::to_string(&log_entry)?)
1146 .send()
1147 .await
1148 {
1149 Ok(response) => {
1150 if response.status().is_success() {
1151 debug!("Sent Azure Monitor event: {}", event.event_type);
1152 return Ok(());
1153 } else {
1154 let status = response.status();
1155 let body = response.text().await.unwrap_or_default();
1156 last_error = Some(Error::Generic(format!(
1157 "Azure Monitor HTTP error {}: {}",
1158 status, body
1159 )));
1160 }
1161 }
1162 Err(e) => {
1163 last_error =
1164 Some(Error::Generic(format!("Azure Monitor request failed: {}", e)));
1165 }
1166 }
1167
1168 if attempt < self.retry.max_attempts {
1169 let delay = if self.retry.backoff == "exponential" {
1170 self.retry.initial_delay_secs * (2_u64.pow(attempt))
1171 } else {
1172 self.retry.initial_delay_secs * (attempt as u64 + 1)
1173 };
1174 tokio::time::sleep(std::time::Duration::from_secs(delay)).await;
1175 }
1176 }
1177
1178 Err(last_error.unwrap_or_else(|| {
1179 Error::Generic("Failed to send Azure Monitor event after retries".to_string())
1180 }))
1181 }
1182}
1183
1184#[derive(Debug, Clone, Serialize, Deserialize)]
1186pub struct TransportHealth {
1187 pub identifier: String,
1189 pub healthy: bool,
1191 pub last_success: Option<chrono::DateTime<chrono::Utc>>,
1193 pub last_error: Option<String>,
1195 pub success_count: u64,
1197 pub failure_count: u64,
1199}
1200
1201pub struct SiemEmitter {
1203 transports: Vec<Box<dyn SiemTransport>>,
1204 filters: Option<EventFilter>,
1205 health_status: Arc<RwLock<Vec<TransportHealth>>>,
1207}
1208
1209impl SiemEmitter {
1210 pub async fn from_config(config: SiemConfig) -> Result<Self, Error> {
1212 if !config.enabled {
1213 return Ok(Self {
1214 transports: Vec::new(),
1215 filters: config.filters,
1216 health_status: Arc::new(RwLock::new(Vec::new())),
1217 });
1218 }
1219
1220 let mut transports: Vec<Box<dyn SiemTransport>> = Vec::new();
1221
1222 for dest in config.destinations {
1223 let transport: Box<dyn SiemTransport> = match dest {
1224 SiemDestination::Syslog {
1225 host,
1226 port,
1227 transport,
1228 facility,
1229 tag,
1230 } => Box::new(SyslogTransport::new(host, port, transport, facility, tag)),
1231 SiemDestination::Http {
1232 url,
1233 method,
1234 headers,
1235 timeout,
1236 retry,
1237 } => Box::new(HttpTransport::new(url, method, headers, timeout, retry)),
1238 SiemDestination::Https {
1239 url,
1240 method,
1241 headers,
1242 timeout,
1243 retry,
1244 } => Box::new(HttpTransport::new(url, method, headers, timeout, retry)),
1245 SiemDestination::File { path, format, .. } => {
1246 Box::new(FileTransport::new(path, format).await?)
1247 }
1248 SiemDestination::Splunk {
1249 url,
1250 token,
1251 index,
1252 source_type,
1253 } => Box::new(SplunkTransport::new(
1254 url,
1255 token,
1256 index,
1257 source_type,
1258 RetryConfig::default(),
1259 )),
1260 SiemDestination::Datadog {
1261 api_key,
1262 app_key,
1263 site,
1264 tags,
1265 } => Box::new(DatadogTransport::new(
1266 api_key,
1267 app_key,
1268 site,
1269 tags,
1270 RetryConfig::default(),
1271 )),
1272 SiemDestination::Cloudwatch {
1273 region,
1274 log_group,
1275 stream,
1276 credentials,
1277 } => Box::new(CloudwatchTransport::new(
1278 region,
1279 log_group,
1280 stream,
1281 credentials,
1282 RetryConfig::default(),
1283 )),
1284 SiemDestination::Gcp {
1285 project_id,
1286 log_name,
1287 credentials_path,
1288 } => Box::new(GcpTransport::new(
1289 project_id,
1290 log_name,
1291 credentials_path,
1292 RetryConfig::default(),
1293 )),
1294 SiemDestination::Azure {
1295 workspace_id,
1296 shared_key,
1297 log_type,
1298 } => Box::new(AzureTransport::new(
1299 workspace_id,
1300 shared_key,
1301 log_type,
1302 RetryConfig::default(),
1303 )),
1304 };
1305 transports.push(transport);
1306 }
1307
1308 let health_status = Arc::new(RwLock::new(
1309 transports
1310 .iter()
1311 .enumerate()
1312 .map(|(i, _)| TransportHealth {
1313 identifier: format!("transport_{}", i),
1314 healthy: true,
1315 last_success: None,
1316 last_error: None,
1317 success_count: 0,
1318 failure_count: 0,
1319 })
1320 .collect(),
1321 ));
1322
1323 Ok(Self {
1324 transports,
1325 filters: config.filters,
1326 health_status,
1327 })
1328 }
1329
1330 pub async fn emit(&self, event: SecurityEvent) -> Result<(), Error> {
1332 if let Some(ref filter) = self.filters {
1334 if !filter.should_include(&event) {
1335 debug!("Event filtered out: {}", event.event_type);
1336 return Ok(());
1337 }
1338 }
1339
1340 let mut errors = Vec::new();
1342 let mut health_status = self.health_status.write().await;
1343
1344 for (idx, transport) in self.transports.iter().enumerate() {
1345 match transport.send_event(&event).await {
1346 Ok(()) => {
1347 if let Some(health) = health_status.get_mut(idx) {
1348 health.healthy = true;
1349 health.last_success = Some(chrono::Utc::now());
1350 health.success_count += 1;
1351 health.last_error = None;
1352 }
1353 }
1354 Err(e) => {
1355 let error_msg = format!("{}", e);
1356 error!("Failed to send event to SIEM: {}", error_msg);
1357 errors.push(Error::Generic(error_msg.clone()));
1358 if let Some(health) = health_status.get_mut(idx) {
1359 health.healthy = false;
1360 health.failure_count += 1;
1361 health.last_error = Some(error_msg);
1362 }
1363 }
1364 }
1365 }
1366
1367 drop(health_status);
1368
1369 if !errors.is_empty() && errors.len() == self.transports.len() {
1370 return Err(Error::Generic(format!(
1372 "All SIEM transports failed: {} errors",
1373 errors.len()
1374 )));
1375 }
1376
1377 Ok(())
1378 }
1379
1380 pub async fn health_status(&self) -> Vec<TransportHealth> {
1382 self.health_status.read().await.clone()
1383 }
1384
1385 pub async fn is_healthy(&self) -> bool {
1387 let health_status = self.health_status.read().await;
1388 health_status.iter().any(|h| h.healthy)
1389 }
1390
1391 pub async fn health_summary(&self) -> (usize, usize, usize) {
1393 let health_status = self.health_status.read().await;
1394 let total = health_status.len();
1395 let healthy = health_status.iter().filter(|h| h.healthy).count();
1396 let unhealthy = total - healthy;
1397 (total, healthy, unhealthy)
1398 }
1399}
1400
1401#[cfg(test)]
1402mod tests {
1403 use super::*;
1404 use crate::security::events::{EventActor, EventOutcome, EventTarget, SecurityEventType};
1405
1406 #[test]
1407 fn test_event_filter_include() {
1408 let filter = EventFilter {
1409 include: Some(vec!["auth.*".to_string()]),
1410 exclude: None,
1411 conditions: None,
1412 };
1413
1414 let event =
1415 crate::security::events::SecurityEvent::new(SecurityEventType::AuthSuccess, None, None);
1416
1417 assert!(filter.should_include(&event));
1418
1419 let event = crate::security::events::SecurityEvent::new(
1420 SecurityEventType::ConfigChanged,
1421 None,
1422 None,
1423 );
1424
1425 assert!(!filter.should_include(&event));
1426 }
1427
1428 #[test]
1429 fn test_event_filter_exclude() {
1430 let filter = EventFilter {
1431 include: None,
1432 exclude: Some(vec!["severity:low".to_string()]),
1433 conditions: None,
1434 };
1435
1436 let event =
1437 crate::security::events::SecurityEvent::new(SecurityEventType::AuthSuccess, None, None);
1438
1439 assert!(!filter.should_include(&event));
1440
1441 let event =
1442 crate::security::events::SecurityEvent::new(SecurityEventType::AuthFailure, None, None);
1443
1444 assert!(filter.should_include(&event));
1445 }
1446
1447 #[tokio::test]
1448 async fn test_syslog_transport_format() {
1449 let transport = SyslogTransport::new(
1450 "localhost".to_string(),
1451 514,
1452 "udp".to_string(),
1453 SyslogFacility::Local0,
1454 "mockforge".to_string(),
1455 );
1456
1457 let event =
1458 crate::security::events::SecurityEvent::new(SecurityEventType::AuthSuccess, None, None);
1459
1460 let message = transport.format_syslog_message(&event);
1461 assert!(message.starts_with("<"));
1462 assert!(message.contains("mockforge"));
1463 }
1464
1465 #[test]
1466 fn test_siem_protocol_serialization() {
1467 let protocols = vec![
1468 SiemProtocol::Syslog,
1469 SiemProtocol::Http,
1470 SiemProtocol::Https,
1471 SiemProtocol::File,
1472 SiemProtocol::Splunk,
1473 SiemProtocol::Datadog,
1474 SiemProtocol::Cloudwatch,
1475 SiemProtocol::Gcp,
1476 SiemProtocol::Azure,
1477 ];
1478
1479 for protocol in protocols {
1480 let json = serde_json::to_string(&protocol).unwrap();
1481 assert!(!json.is_empty());
1482 let deserialized: SiemProtocol = serde_json::from_str(&json).unwrap();
1483 assert_eq!(protocol, deserialized);
1484 }
1485 }
1486
1487 #[test]
1488 fn test_syslog_facility_default() {
1489 let facility = SyslogFacility::default();
1490 assert_eq!(facility, SyslogFacility::Local0);
1491 }
1492
1493 #[test]
1494 fn test_syslog_facility_serialization() {
1495 let facilities = vec![
1496 SyslogFacility::Kernel,
1497 SyslogFacility::User,
1498 SyslogFacility::Security,
1499 SyslogFacility::Local0,
1500 SyslogFacility::Local7,
1501 ];
1502
1503 for facility in facilities {
1504 let json = serde_json::to_string(&facility).unwrap();
1505 assert!(!json.is_empty());
1506 let deserialized: SyslogFacility = serde_json::from_str(&json).unwrap();
1507 assert_eq!(facility, deserialized);
1508 }
1509 }
1510
1511 #[test]
1512 fn test_syslog_severity_from_security_event_severity() {
1513 use crate::security::events::SecurityEventSeverity;
1514
1515 assert_eq!(SyslogSeverity::from(SecurityEventSeverity::Low), SyslogSeverity::Informational);
1516 assert_eq!(SyslogSeverity::from(SecurityEventSeverity::Medium), SyslogSeverity::Warning);
1517 assert_eq!(SyslogSeverity::from(SecurityEventSeverity::High), SyslogSeverity::Error);
1518 assert_eq!(SyslogSeverity::from(SecurityEventSeverity::Critical), SyslogSeverity::Critical);
1519 }
1520
1521 #[test]
1522 fn test_retry_config_default() {
1523 let config = RetryConfig::default();
1524 assert_eq!(config.max_attempts, 3);
1525 assert_eq!(config.backoff, "exponential");
1526 assert_eq!(config.initial_delay_secs, 1);
1527 }
1528
1529 #[test]
1530 fn test_retry_config_serialization() {
1531 let config = RetryConfig {
1532 max_attempts: 5,
1533 backoff: "linear".to_string(),
1534 initial_delay_secs: 2,
1535 };
1536
1537 let json = serde_json::to_string(&config).unwrap();
1538 assert!(json.contains("max_attempts"));
1539 assert!(json.contains("linear"));
1540 }
1541
1542 #[test]
1543 fn test_file_rotation_config_serialization() {
1544 let config = FileRotationConfig {
1545 max_size: "100MB".to_string(),
1546 max_files: 10,
1547 compress: true,
1548 };
1549
1550 let json = serde_json::to_string(&config).unwrap();
1551 assert!(json.contains("100MB"));
1552 assert!(json.contains("max_files"));
1553 }
1554
1555 #[test]
1556 fn test_siem_config_default() {
1557 let config = SiemConfig::default();
1558 assert!(!config.enabled);
1559 assert!(config.protocol.is_none());
1560 assert!(config.destinations.is_empty());
1561 assert!(config.filters.is_none());
1562 }
1563
1564 #[test]
1565 fn test_siem_config_serialization() {
1566 let config = SiemConfig {
1567 enabled: true,
1568 protocol: Some(SiemProtocol::Syslog),
1569 destinations: vec![],
1570 filters: None,
1571 };
1572
1573 let json = serde_json::to_string(&config).unwrap();
1574 assert!(json.contains("enabled"));
1575 assert!(json.contains("syslog"));
1576 }
1577
1578 #[test]
1579 fn test_transport_health_creation() {
1580 let health = TransportHealth {
1581 identifier: "test_transport".to_string(),
1582 healthy: true,
1583 last_success: Some(chrono::Utc::now()),
1584 last_error: None,
1585 success_count: 100,
1586 failure_count: 0,
1587 };
1588
1589 assert_eq!(health.identifier, "test_transport");
1590 assert!(health.healthy);
1591 assert_eq!(health.success_count, 100);
1592 assert_eq!(health.failure_count, 0);
1593 }
1594
1595 #[test]
1596 fn test_transport_health_serialization() {
1597 let health = TransportHealth {
1598 identifier: "transport_1".to_string(),
1599 healthy: false,
1600 last_success: None,
1601 last_error: Some("Connection failed".to_string()),
1602 success_count: 50,
1603 failure_count: 5,
1604 };
1605
1606 let json = serde_json::to_string(&health).unwrap();
1607 assert!(json.contains("transport_1"));
1608 assert!(json.contains("Connection failed"));
1609 }
1610
1611 #[test]
1612 fn test_syslog_transport_new() {
1613 let transport = SyslogTransport::new(
1614 "example.com".to_string(),
1615 514,
1616 "tcp".to_string(),
1617 SyslogFacility::Security,
1618 "app".to_string(),
1619 );
1620
1621 let _ = transport;
1623 }
1624
1625 #[test]
1626 fn test_http_transport_new() {
1627 let mut headers = HashMap::new();
1628 headers.insert("X-Custom-Header".to_string(), "value".to_string());
1629 let transport = HttpTransport::new(
1630 "https://example.com/webhook".to_string(),
1631 "POST".to_string(),
1632 headers,
1633 10,
1634 RetryConfig::default(),
1635 );
1636
1637 let _ = transport;
1639 }
1640
1641 #[test]
1642 fn test_splunk_transport_new() {
1643 let transport = SplunkTransport::new(
1644 "https://splunk.example.com:8088".to_string(),
1645 "token123".to_string(),
1646 Some("index1".to_string()),
1647 Some("json".to_string()),
1648 RetryConfig::default(),
1649 );
1650
1651 let _ = transport;
1653 }
1654
1655 #[test]
1656 fn test_datadog_transport_new() {
1657 let transport = DatadogTransport::new(
1658 "api_key_123".to_string(),
1659 Some("app_key_456".to_string()),
1660 "us".to_string(),
1661 vec!["env:test".to_string()],
1662 RetryConfig::default(),
1663 );
1664
1665 let _ = transport;
1667 }
1668
1669 #[test]
1670 fn test_cloudwatch_transport_new() {
1671 let mut credentials = HashMap::new();
1672 credentials.insert("access_key".to_string(), "key123".to_string());
1673 credentials.insert("secret_key".to_string(), "secret123".to_string());
1674 let transport = CloudwatchTransport::new(
1675 "us-east-1".to_string(),
1676 "log-group-name".to_string(),
1677 "log-stream-name".to_string(),
1678 credentials,
1679 RetryConfig::default(),
1680 );
1681
1682 let _ = transport;
1684 }
1685
1686 #[test]
1687 fn test_gcp_transport_new() {
1688 let transport = GcpTransport::new(
1689 "project-id".to_string(),
1690 "log-name".to_string(),
1691 "/path/to/credentials.json".to_string(),
1692 RetryConfig::default(),
1693 );
1694
1695 let _ = transport;
1697 }
1698
1699 #[test]
1700 fn test_azure_transport_new() {
1701 let transport = AzureTransport::new(
1702 "workspace-id".to_string(),
1703 "shared-key".to_string(),
1704 "CustomLog".to_string(),
1705 RetryConfig::default(),
1706 );
1707
1708 let _ = transport;
1710 }
1711}