diff --git a/src/afterfact.rs b/src/afterfact.rs new file mode 100644 index 00000000..38b31e5f --- /dev/null +++ b/src/afterfact.rs @@ -0,0 +1,63 @@ +use crate::detections::configs; +use crate::detections::print; +use chrono::{DateTime, TimeZone, Utc}; +use serde::Serialize; +use std::error::Error; +use std::process; + +#[derive(Debug, Serialize)] +#[serde(rename_all = "PascalCase")] +pub struct CsvFormat<'a> { + time: DateTime, + message: &'a str, +} + +pub fn after_fact() { + if let Some(csv_path) = configs::singleton().args.value_of("csv-timeline") { + if let Err(err) = emit_csv(csv_path) { + println!("{}", err); + process::exit(1); + } + } +} + +fn emit_csv(path: &str) -> Result<(), Box> { + let mut wtr = csv::Writer::from_path(path)?; + let messages = print::MESSAGES.lock().unwrap(); + + for (time, texts) in messages.iter() { + for text in texts { + wtr.serialize(CsvFormat { + time: *time, + message: text, + })?; + } + } + wtr.flush()?; + Ok(()) +} + +use std::fs::{read_to_string, remove_file}; +use std::io::Read; + +#[test] +fn test_emit_csv() { + { + let mut messages = print::MESSAGES.lock().unwrap(); + let poke = Utc.ymd(1996, 2, 27).and_hms(1, 5, 1); + messages.insert(poke, "pokepoke".to_string()); + } + + let expect = "Time,Message +1996-02-27T01:05:01Z,pokepoke +"; + + assert!(emit_csv(&"./test_emit_csv.csv".to_string()).is_ok()); + + match read_to_string("./test_emit_csv.csv") { + Err(_) => panic!("Failed to open file"), + Ok(s) => assert_eq!(s, expect), + }; + + assert!(remove_file("./test_emit_csv.csv").is_ok()); +} diff --git a/src/detections/print.rs b/src/detections/print.rs index 793737e4..fc1a4955 100644 --- a/src/detections/print.rs +++ b/src/detections/print.rs @@ -45,6 +45,10 @@ impl Message { pub fn debug(&self) { println!("{:?}", self.map); } + + pub fn iter(&self) -> &BTreeMap, Vec> { + &self.map + } } #[test] diff --git a/src/lib.rs b/src/lib.rs index d9abfe41..2f0bb054 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,4 @@ +pub mod afterfact; pub mod detections; pub mod models; pub mod omikuji; diff --git a/src/main.rs b/src/main.rs index c2e44c76..ddfc4c4e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,8 +1,11 @@ extern crate serde; +#[macro_use] +extern crate serde_derive; use evtx::EvtxParser; use quick_xml::de::DeError; use std::{fs, path::PathBuf, process}; +use yamato_event_analyzer::afterfact::after_fact; use yamato_event_analyzer::detections::configs; use yamato_event_analyzer::detections::detection; use yamato_event_analyzer::omikuji::Omikuji; @@ -17,6 +20,8 @@ fn main() -> Result<(), DeError> { parse_file(&filepath); } + after_fact(); + Ok(()) }