Skip to content

Commit

Permalink
fix test typo and merge #301
Browse files Browse the repository at this point in the history
  • Loading branch information
hitenkoku committed Dec 20, 2021
1 parent 78926eb commit 617f121
Show file tree
Hide file tree
Showing 6 changed files with 108 additions and 15 deletions.
4 changes: 2 additions & 2 deletions src/detections/configs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ impl TargetEventTime {
Err(err) => {
AlertMessage::alert(
&mut std::io::stderr().lock(),
format!("starttimeline field: {}", err),
format!("start-timeline field: {}", err),
)
.ok();
None
Expand All @@ -157,7 +157,7 @@ impl TargetEventTime {
Err(err) => {
AlertMessage::alert(
&mut std::io::stderr().lock(),
format!("endtimeline field: {}", err),
format!("end-timeline field: {}", err),
)
.ok();
None
Expand Down
13 changes: 10 additions & 3 deletions src/detections/detection.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
extern crate csv;

use crate::detections::print::AlertMessage;
use crate::detections::print::ERROR_LOG_PATH;
use crate::detections::print::MESSAGES;
use crate::detections::rule;
use crate::detections::rule::AggResult;
Expand All @@ -11,9 +12,10 @@ use crate::yaml::ParseYaml;
use hashbrown;
use serde_json::Value;
use std::collections::HashMap;
use tokio::{runtime::Runtime, spawn, task::JoinHandle};

use std::fs::OpenOptions;
use std::io::BufWriter;
use std::sync::Arc;
use tokio::{runtime::Runtime, spawn, task::JoinHandle};

const DIRPATH_RULES: &str = "rules";

Expand Down Expand Up @@ -58,7 +60,12 @@ impl Detection {
rulefile_loader.read_dir(rulespath.unwrap_or(DIRPATH_RULES), &level, exclude_ids);
if result_readdir.is_err() {
AlertMessage::alert(
&mut std::io::stderr().lock(),
&mut BufWriter::new(
OpenOptions::new()
.append(true)
.open(ERROR_LOG_PATH.to_string())
.unwrap(),
),
format!("{}", result_readdir.unwrap_err()),
)
.ok();
Expand Down
43 changes: 41 additions & 2 deletions src/detections/print.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ extern crate lazy_static;
use crate::detections::configs;
use crate::detections::utils;
use crate::detections::utils::get_serde_number_to_string;
use chrono::{DateTime, TimeZone, Utc};
use chrono::{DateTime, Local, TimeZone, Utc};
use lazy_static::lazy_static;
use regex::Regex;
use serde_json::Value;
Expand All @@ -13,6 +13,7 @@ use std::fs::create_dir;
use std::fs::File;
use std::io::BufWriter;
use std::io::{self, Write};
use std::path::Path;
use std::sync::Mutex;

#[derive(Debug)]
Expand All @@ -36,6 +37,15 @@ pub struct AlertMessage {}
lazy_static! {
pub static ref MESSAGES: Mutex<Message> = Mutex::new(Message::new());
pub static ref ALIASREGEX: Regex = Regex::new(r"%[a-zA-Z0-9-_]+%").unwrap();
pub static ref ERROR_LOG_PATH: String = format!(
"./logs/errorlog-{}.log",
Local::now().format("%Y%m%d_%H%M%S")
);
pub static ref QUIET_ERRORS_FLAG: bool = configs::CONFIG
.read()
.unwrap()
.args
.is_present("quiet-errors");
}

impl Message {
Expand Down Expand Up @@ -184,13 +194,42 @@ impl Message {
}

impl AlertMessage {
///対象のディレクトリが存在することを確認後、最初の定型文を追加して、ファイルのbufwriterを返す関数
pub fn create_error_log(path_str: String) {
let path = Path::new(&path_str);
if !path.parent().unwrap().exists() {
create_dir(path.parent().unwrap()).ok();
}
// 1行目は必ず実行したコマンド情報を入れておく。
let mut ret = BufWriter::new(File::create(path).unwrap());

ret.write(
format!(
"user input: {:?}\n",
format_args!(
"{}",
env::args()
.map(|arg| arg)
.collect::<Vec<String>>()
.join(" ")
)
)
.as_bytes(),
)
.unwrap();
ret.flush().ok();
}

/// ERRORメッセージを表示する関数
pub fn alert<W: Write>(w: &mut W, contents: String) -> io::Result<()> {
if !*QUIET_ERRORS_FLAG {
writeln!(w, "[ERROR] {}", contents)
} else {
Ok(())
}
}

/// WARNメッセージを表示する関数
pub fn warn<W: Write>(w: &mut W, contents: String) -> io::Result<()> {
if !*QUIET_ERRORS_FLAG {
writeln!(w, "[WARN] {}", contents)
Expand Down Expand Up @@ -334,7 +373,7 @@ mod tests {
let input = "TESTWarn!";
let stdout = std::io::stdout();
let mut stdout = stdout.lock();
AlertMessage::alert(&mut stdout, input.to_string()).expect("[WARN] TESTWarn!");
AlertMessage::warn(&mut stdout, input.to_string()).expect("[WARN] TESTWarn!");
}

#[test]
Expand Down
17 changes: 15 additions & 2 deletions src/detections/rule/count.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
use crate::detections::print::AlertMessage;
use crate::detections::print::ERROR_LOG_PATH;
use crate::detections::rule::AggResult;
use crate::detections::rule::AggregationParseInfo;
use crate::detections::rule::Message;
use crate::detections::rule::RuleNode;
use chrono::{DateTime, TimeZone, Utc};
use hashbrown::HashMap;
use serde_json::Value;
use std::fs::OpenOptions;
use std::io::BufWriter;
use std::num::ParseIntError;
use std::path::Path;

Expand Down Expand Up @@ -183,7 +186,12 @@ impl TimeFrameInfo {
tnum.retain(|c| c != 'd');
} else {
AlertMessage::alert(
&mut std::io::stderr().lock(),
&mut BufWriter::new(
OpenOptions::new()
.append(true)
.open(ERROR_LOG_PATH.to_string())
.unwrap(),
),
format!("Timeframe is invalid. Input value:{}", value),
)
.ok();
Expand Down Expand Up @@ -215,7 +223,12 @@ pub fn get_sec_timeframe(timeframe: &Option<TimeFrameInfo>) -> Option<i64> {
}
Err(err) => {
AlertMessage::alert(
&mut std::io::stderr().lock(),
&mut BufWriter::new(
OpenOptions::new()
.append(true)
.open(ERROR_LOG_PATH.to_string())
.unwrap(),
),
format!("Timeframe number is invalid. timeframe.{}", err),
)
.ok();
Expand Down
29 changes: 25 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use chrono::{DateTime, Local};
use evtx::{EvtxParser, ParserSettings};
use hayabusa::detections::detection::{self, EvtxRecordInfo};
use hayabusa::detections::print::AlertMessage;
use hayabusa::detections::print::ERROR_LOG_PATH;
use hayabusa::detections::rule::{get_detection_keys, RuleNode};
use hayabusa::filter;
use hayabusa::omikuji::Omikuji;
Expand All @@ -16,6 +17,9 @@ use pbr::ProgressBar;
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::fmt::Display;
use std::fs::OpenOptions;
use std::io::BufWriter;
use std::path::Path;
use std::sync::Arc;
use std::{
fs::{self, File},
Expand Down Expand Up @@ -113,14 +117,22 @@ impl App {
let analysis_duration = analysis_end_time.signed_duration_since(analysis_start_time);
println!("Elapsed Time: {}", &analysis_duration.hhmmssxxx());
println!("");
AlertMessage::output_error_log_exist();
}

fn collect_evtxfiles(&self, dirpath: &str) -> Vec<PathBuf> {
let entries = fs::read_dir(dirpath);
if entries.is_err() {
let stderr = std::io::stderr();
let mut stderr = stderr.lock();
AlertMessage::alert(&mut stderr, format!("{}", entries.unwrap_err())).ok();
AlertMessage::alert(
&mut BufWriter::new(
OpenOptions::new()
.append(true)
.open(ERROR_LOG_PATH.to_string())
.unwrap(),
),
format!("{}", entries.unwrap_err()),
)
.ok();
return vec![];
}

Expand Down Expand Up @@ -219,7 +231,16 @@ impl App {
evtx_filepath,
record_result.unwrap_err()
);
AlertMessage::alert(&mut std::io::stderr().lock(), errmsg).ok();
AlertMessage::alert(
&mut BufWriter::new(
OpenOptions::new()
.append(true)
.open(ERROR_LOG_PATH.to_string())
.unwrap(),
),
errmsg,
)
.ok();
continue;
}

Expand Down
17 changes: 15 additions & 2 deletions src/yaml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@ extern crate yaml_rust;

use crate::detections::configs;
use crate::detections::print::AlertMessage;
use crate::detections::print::ERROR_LOG_PATH;
use crate::filter::RuleExclude;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs;
use std::fs::OpenOptions;
use std::io;
use std::io::BufWriter;
use std::io::{BufReader, Read};
use std::path::{Path, PathBuf};
use yaml_rust::Yaml;
Expand Down Expand Up @@ -72,7 +75,12 @@ impl ParseYaml {
let read_content = self.read_file(path);
if read_content.is_err() {
AlertMessage::warn(
&mut std::io::stdout().lock(),
&mut BufWriter::new(
OpenOptions::new()
.append(true)
.open(ERROR_LOG_PATH.to_string())
.unwrap(),
),
format!(
"fail to read file: {}\n{} ",
entry.path().display(),
Expand All @@ -87,7 +95,12 @@ impl ParseYaml {
let yaml_contents = YamlLoader::load_from_str(&read_content.unwrap());
if yaml_contents.is_err() {
AlertMessage::warn(
&mut std::io::stdout().lock(),
&mut BufWriter::new(
OpenOptions::new()
.append(true)
.open(ERROR_LOG_PATH.to_string())
.unwrap(),
),
format!(
"Failed to parse yml: {}\n{} ",
entry.path().display(),
Expand Down

0 comments on commit 617f121

Please sign in to comment.