Merge branch 'feature/timeline_template_#104' of github.com:YamatoSecurity/YamatoEventAnalyzer

This commit is contained in:
Alan Smithee
2021-05-15 22:04:47 +09:00
13 changed files with 1771 additions and 275 deletions

7
Cargo.lock generated
View File

@@ -632,6 +632,12 @@ dependencies = [
"winapi",
]
[[package]]
name = "mopa"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a785740271256c230f57462d3b83e52f998433a7062fc18f96d5999474a9f915"
[[package]]
name = "ntapi"
version = "0.3.6"
@@ -1358,6 +1364,7 @@ dependencies = [
"flate2",
"lazy_static",
"linked-hash-map",
"mopa",
"num_cpus",
"quick-xml 0.17.2",
"regex",

View File

@@ -23,6 +23,7 @@ yaml-rust = "0.4"
linked-hash-map = "0.5.3"
tokio = { version = "1", features = ["full"] }
num_cpus = "1.13.0"
mopa = "0.2.2"
[target.x86_64-pc-windows-gnu]
linker = "x86_64-w64-mingw32-gcc"

View File

@@ -21,4 +21,6 @@ LogFileCleared,Event.UserData.LogFileCleared.SubjectUserName
LogFileClearedSubjectUserName,Event.UserData.SubjectUserName
SubjectUserName,Event.EventData.SubjectUserName
SubjectUserSid,Event.EventData.SubjectUserSid
DomainName,Event.EventData.SubjectDomainName
DomainName,Event.EventData.SubjectDomainName
TicketEncryptionType,Event.EventData.TicketEncryptionType
PreAuthType,Event.EventData.PreAuthType

View File

@@ -0,0 +1,18 @@
title: AS-REP Roasting
description: For each account found without preauthentication, an adversary may send an AS-REQ message without the encrypted timestamp and receive an AS-REP message with TGT data which may be encrypted with an insecure algorithm such as RC4.
enabled: true
author: Yea
logsource:
product: windows
detection:
selection:
Channel: Security
EventID: 4768
TicketEncryptionType: '0x17'
PreAuthType: 0
falsepositives:
- unknown
level: medium
output: 'Detected AS-REP Roasting Risk Actvity.'
creation_date: 2021/4/31
updated_date: 2021/4/31

View File

@@ -0,0 +1,18 @@
title: Kerberoasting
description: Adversaries may abuse a valid Kerberos ticket-granting ticket (TGT) or sniff network traffic to obtain a ticket-granting service (TGS) ticket that may be vulnerable to Brute Force.
enabled: true
author: Yea
logsource:
product: windows
detection:
selection:
Channel: Security
EventID: 4768
TicketEncryptionType: '0x17'
PreAuthType: 2
falsepositives:
- unknown
level: medium
output: 'Detected Kerberoasting Risk Activity.'
creation_date: 2021/4/31
updated_date: 2021/4/31

View File

@@ -1,53 +1,49 @@
extern crate csv;
use serde_json::Value;
use tokio::{spawn, task::JoinHandle};
use crate::detections::print::MESSAGES;
use crate::detections::rule;
use crate::detections::rule::RuleNode;
use crate::detections::{print::AlertMessage, utils};
use crate::yaml::ParseYaml;
use evtx::err;
use evtx::{EvtxParser, ParserSettings, SerializedEvtxRecord};
use serde_json::Value;
use tokio::{spawn, task::JoinHandle};
use std::{collections::HashSet, path::PathBuf};
use std::{fs::File, sync::Arc};
use std::sync::Arc;
const DIRPATH_RULES: &str = "rules";
// イベントファイルの1レコード分の情報を保持する構造体
#[derive(Clone, Debug)]
pub struct EvtxRecordInfo {
evtx_filepath: String,
record: Value,
pub evtx_filepath: String, // イベントファイルのファイルパス ログで出力するときに使う
pub record: Value, // 1レコード分のデータをJSON形式にシリアライズしたもの
}
impl EvtxRecordInfo {
pub fn new(evtx_filepath: String, record: Value) -> EvtxRecordInfo {
return EvtxRecordInfo {
evtx_filepath: evtx_filepath,
record: record,
};
}
}
// TODO テストケースかかなきゃ...
#[derive(Debug)]
pub struct Detection {
parseinfos: Vec<EvtxRecordInfo>,
}
pub struct Detection {}
impl Detection {
pub fn new() -> Detection {
let initializer: Vec<EvtxRecordInfo> = Vec::new();
Detection {
parseinfos: initializer,
}
return Detection {};
}
pub fn start(&mut self, evtx_files: Vec<PathBuf>) {
if evtx_files.is_empty() {
return;
}
pub fn start(&mut self, records: Vec<EvtxRecordInfo>) {
let rules = self.parse_rule_files();
if rules.is_empty() {
return;
}
let records = self.evtx_to_jsons(&evtx_files, &rules);
let tokio_rt = utils::create_tokio_runtime();
tokio_rt.block_on(self.execute_rule(rules, records));
tokio_rt.shutdown_background();
@@ -98,195 +94,6 @@ impl Detection {
.collect();
}
// evtxファイルをjsonに変換します。
fn evtx_to_jsons(
&mut self,
evtx_files: &Vec<PathBuf>,
rules: &Vec<RuleNode>,
) -> Vec<EvtxRecordInfo> {
// EvtxParserを生成する。
let evtx_parsers: Vec<EvtxParser<File>> = evtx_files
.clone()
.into_iter()
.filter_map(|evtx_file| {
// convert to evtx parser
// println!("PathBuf:{}", evtx_file.display());
match EvtxParser::from_path(evtx_file) {
Ok(parser) => Option::Some(parser),
Err(e) => {
eprintln!("{}", e);
return Option::None;
}
}
})
.collect();
let tokio_rt = utils::create_tokio_runtime();
let xml_records = tokio_rt.block_on(self.evtx_to_xml(evtx_parsers, &evtx_files));
let json_records = tokio_rt.block_on(self.xml_to_json(xml_records, &evtx_files, &rules));
tokio_rt.shutdown_background();
return json_records
.into_iter()
.map(|(parser_idx, json_record)| {
let evtx_filepath = evtx_files[parser_idx].display().to_string();
return EvtxRecordInfo {
evtx_filepath: String::from(&evtx_filepath),
record: json_record,
};
})
.collect();
}
// evtxファイルからxmlを生成する。
// 戻り値は「どのイベントファイルから生成されたXMLかを示すindex」と「変換されたXML」のタプルです。
// タプルのindexは、引数で指定されるevtx_filesのindexに対応しています。
async fn evtx_to_xml(
&mut self,
evtx_parsers: Vec<EvtxParser<File>>,
evtx_files: &Vec<PathBuf>,
) -> Vec<(usize, SerializedEvtxRecord<String>)> {
// evtx_parser.records_json()でevtxをxmlに変換するJobを作成
let handles: Vec<JoinHandle<Vec<err::Result<SerializedEvtxRecord<String>>>>> = evtx_parsers
.into_iter()
.map(|mut evtx_parser| {
return spawn(async move {
let mut parse_config = ParserSettings::default();
parse_config = parse_config.separate_json_attributes(true);
parse_config = parse_config.num_threads(utils::get_thread_num());
evtx_parser = evtx_parser.with_configuration(parse_config);
let values = evtx_parser.records_json().collect();
return values;
});
})
.collect();
// 作成したjobを実行し(handle.awaitの部分)、スレッドの実行時にエラーが発生した場合、標準エラー出力に出しておく
let mut ret = vec![];
for (parser_idx, handle) in handles.into_iter().enumerate() {
let future_result = handle.await;
if future_result.is_err() {
let evtx_filepath = &evtx_files[parser_idx].display();
let errmsg = format!(
"Failed to parse event file. EventFile:{} Error:{}",
evtx_filepath,
future_result.unwrap_err()
);
AlertMessage::alert(&mut std::io::stdout().lock(), errmsg).ok();
continue;
}
future_result.unwrap().into_iter().for_each(|parse_result| {
ret.push((parser_idx, parse_result));
});
}
return ret
.into_iter()
.filter_map(|(parser_idx, parse_result)| {
if parse_result.is_err() {
let evtx_filepath = &evtx_files[parser_idx].display();
let errmsg = format!(
"Failed to parse event file. EventFile:{} Error:{}",
evtx_filepath,
parse_result.unwrap_err()
);
AlertMessage::alert(&mut std::io::stdout().lock(), errmsg).ok();
return Option::None;
}
return Option::Some((parser_idx, parse_result.unwrap()));
})
.collect();
}
// xmlからjsonに変換します。
// 戻り値は「どのイベントファイルから生成されたXMLかを示すindex」と「変換されたJSON」のタプルです。
// タプルのindexは、引数で指定されるevtx_filesのindexに対応しています。
async fn xml_to_json(
&mut self,
xml_records: Vec<(usize, SerializedEvtxRecord<String>)>,
evtx_files: &Vec<PathBuf>,
rules: &Vec<RuleNode>,
) -> Vec<(usize, Value)> {
// TODO スレッド作り過ぎなので、数を減らす
// 非同期で実行される無名関数を定義
let async_job = |pair: (usize, SerializedEvtxRecord<String>),
event_id_set: Arc<HashSet<i64>>,
evtx_files: Arc<Vec<PathBuf>>| {
let parser_idx = pair.0;
let handle = spawn(async move {
let parse_result = serde_json::from_str(&pair.1.data);
// パースに失敗した場合はエラー出力しておく。
if parse_result.is_err() {
let evtx_filepath = &evtx_files[parser_idx].display();
let errmsg = format!(
"Failed to serialize from event xml to json. EventFile:{} Error:{}",
evtx_filepath,
parse_result.unwrap_err()
);
AlertMessage::alert(&mut std::io::stdout().lock(), errmsg).ok();
return Option::None;
}
// ルールファイルで検知しようとしているEventIDでないレコードはここで捨てる。
let parsed_json: Value = parse_result.unwrap();
let event_id_opt = utils::get_event_value(&utils::get_event_id_key(), &parsed_json);
return event_id_opt
.and_then(|event_id| event_id.as_i64())
.and_then(|event_id| {
if event_id_set.contains(&event_id) {
return Option::Some(parsed_json);
} else {
return Option::None;
}
});
});
return (parser_idx, handle);
};
// 非同期で実行するスレッドを生成し、実行する。
let event_id_set_arc = Arc::new(Detection::get_event_ids(rules));
let evtx_files_arc = Arc::new(evtx_files.clone());
let handles: Vec<(usize, JoinHandle<Option<Value>>)> = xml_records
.into_iter()
.map(|xml_record_pair| {
let event_id_set_clone = Arc::clone(&event_id_set_arc);
let evtx_files_clone = Arc::clone(&evtx_files_arc);
return async_job(xml_record_pair, event_id_set_clone, evtx_files_clone);
})
.collect();
// スレッドの終了待ちをしている。
let mut ret = vec![];
for (parser_idx, handle) in handles {
let future = handle.await;
// スレッドが正常に完了しなかった場合はエラーメッセージを出力する。
if future.is_err() {
let evtx_filepath = &evtx_files[parser_idx].display();
let errmsg = format!(
"Failed to serialize from event xml to json. EventFile:{} Error:{}",
evtx_filepath,
future.unwrap_err()
);
AlertMessage::alert(&mut std::io::stdout().lock(), errmsg).ok();
continue;
}
// パース失敗やルールファイルで検知しようとしていないEventIDの場合等はis_none()==trueになる。
let parse_result = future.unwrap();
if parse_result.is_none() {
continue;
}
ret.push((parser_idx, parse_result.unwrap()));
}
return ret;
}
// 検知ロジックを実行します。
async fn execute_rule(&mut self, rules: Vec<RuleNode>, records: Vec<EvtxRecordInfo>) {
// 複数スレッドで所有権を共有するため、recordsをArcでwwap
@@ -340,13 +147,13 @@ impl Detection {
}
}
fn get_event_ids(rules: &Vec<RuleNode>) -> HashSet<i64> {
return rules
.iter()
.map(|rule| rule.get_event_ids())
.flatten()
.collect();
}
// fn get_event_ids(rules: &Vec<RuleNode>) -> HashSet<i64> {
// return rules
// .iter()
// .map(|rule| rule.get_event_ids())
// .flatten()
// .collect();
// }
// 配列を指定したサイズで分割する。Vector.chunksと同じ動作をするが、Vectorの関数だとinto的なことができないので自作
fn chunks<T>(ary: Vec<T>, size: usize) -> Vec<Vec<T>> {

View File

@@ -2,4 +2,4 @@ pub mod configs;
pub mod detection;
pub mod print;
mod rule;
mod utils;
pub mod utils;

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,5 @@
pub mod afterfact;
pub mod detections;
pub mod omikuji;
pub mod timeline;
pub mod yaml;

View File

@@ -1,12 +1,18 @@
extern crate serde;
extern crate serde_derive;
use std::{fs, path::PathBuf};
use yamato_event_analyzer::afterfact::after_fact;
use yamato_event_analyzer::detections::configs;
use evtx::{err, EvtxParser, ParserSettings, SerializedEvtxRecord};
use std::{
fs::{self, File},
path::PathBuf,
};
use tokio::{spawn, task::JoinHandle};
use yamato_event_analyzer::detections::detection;
use yamato_event_analyzer::detections::detection::EvtxRecordInfo;
use yamato_event_analyzer::detections::print::AlertMessage;
use yamato_event_analyzer::omikuji::Omikuji;
use yamato_event_analyzer::{afterfact::after_fact, detections::utils};
use yamato_event_analyzer::{detections::configs, timeline::timeline::Timeline};
fn main() {
if let Some(filepath) = configs::CONFIG.read().unwrap().args.value_of("filepath") {
@@ -64,12 +70,111 @@ fn print_credits() {
}
fn detect_files(evtx_files: Vec<PathBuf>) {
let evnt_records = evtx_to_jsons(&evtx_files);
let mut tl = Timeline::new();
tl.start(&evnt_records);
let mut detection = detection::Detection::new();
&detection.start(evtx_files);
&detection.start(evnt_records);
after_fact();
}
// evtxファイルをjsonに変換します。
fn evtx_to_jsons(evtx_files: &Vec<PathBuf>) -> Vec<EvtxRecordInfo> {
// EvtxParserを生成する。
let evtx_parsers: Vec<EvtxParser<File>> = evtx_files
.clone()
.into_iter()
.filter_map(|evtx_file| {
// convert to evtx parser
// println!("PathBuf:{}", evtx_file.display());
match EvtxParser::from_path(evtx_file) {
Ok(parser) => Option::Some(parser),
Err(e) => {
eprintln!("{}", e);
return Option::None;
}
}
})
.collect();
let tokio_rt = utils::create_tokio_runtime();
let ret = tokio_rt.block_on(evtx_to_json(evtx_parsers, &evtx_files));
tokio_rt.shutdown_background();
return ret;
}
// evtxファイルからEvtxRecordInfoを生成する。
// 戻り値は「どのイベントファイルから生成されたXMLかを示すindex」と「変換されたXML」のタプルです。
// タプルのindexは、引数で指定されるevtx_filesのindexに対応しています。
async fn evtx_to_json(
evtx_parsers: Vec<EvtxParser<File>>,
evtx_files: &Vec<PathBuf>,
) -> Vec<EvtxRecordInfo> {
// evtx_parser.records_json()でevtxをxmlに変換するJobを作成
let handles: Vec<JoinHandle<Vec<err::Result<SerializedEvtxRecord<serde_json::Value>>>>> =
evtx_parsers
.into_iter()
.map(|mut evtx_parser| {
return spawn(async move {
let mut parse_config = ParserSettings::default();
parse_config = parse_config.separate_json_attributes(true);
parse_config = parse_config.num_threads(utils::get_thread_num());
evtx_parser = evtx_parser.with_configuration(parse_config);
let values = evtx_parser.records_json_value().collect();
return values;
});
})
.collect();
// 作成したjobを実行し(handle.awaitの部分)、スレッドの実行時にエラーが発生した場合、標準エラー出力に出しておく
let mut ret = vec![];
for (parser_idx, handle) in handles.into_iter().enumerate() {
let future_result = handle.await;
if future_result.is_err() {
let evtx_filepath = &evtx_files[parser_idx].display();
let errmsg = format!(
"Failed to parse event file. EventFile:{} Error:{}",
evtx_filepath,
future_result.unwrap_err()
);
AlertMessage::alert(&mut std::io::stdout().lock(), errmsg).ok();
continue;
}
future_result.unwrap().into_iter().for_each(|parse_result| {
ret.push((parser_idx, parse_result));
});
}
return ret
.into_iter()
.filter_map(|(parser_idx, parse_result)| {
// パースに失敗している場合、エラーメッセージを出力
if parse_result.is_err() {
let evtx_filepath = &evtx_files[parser_idx].display();
let errmsg = format!(
"Failed to parse event file. EventFile:{} Error:{}",
evtx_filepath,
parse_result.unwrap_err()
);
AlertMessage::alert(&mut std::io::stdout().lock(), errmsg).ok();
return Option::None;
}
let record_info = EvtxRecordInfo::new(
evtx_files[parser_idx].display().to_string(),
parse_result.unwrap().data,
);
return Option::Some(record_info);
})
.collect();
}
fn _output_with_omikuji(omikuji: Omikuji) {
let fp = &format!("art/omikuji/{}", omikuji);
let content = fs::read_to_string(fp).unwrap();

2
src/timeline/mod.rs Normal file
View File

@@ -0,0 +1,2 @@
pub mod statistics;
pub mod timeline;

View File

@@ -0,0 +1,36 @@
use crate::detections::{configs, detection::EvtxRecordInfo};
#[derive(Debug)]
pub struct EventStatistics {}
/**
* Windows Event Logの統計情報を出力する
*/
impl EventStatistics {
pub fn new() -> EventStatistics {
return EventStatistics {};
}
// この関数の戻り値として、コンソールに出力する内容をStringの可変配列(Vec)として返却してください。
// 可変配列にしているのは改行を表すためで、可変配列にコンソールに出力する内容を1行ずつ追加してください。
// 引数の_recordsが読み込んだWindowsイベントログのを表す、EvtxRecordInfo構造体の配列になっています。
// EvtxRecordInfo構造体の pub record: Value というメンバーがいて、それがWindowsイベントログの1レコード分を表していますので、
// EvtxRecordInfo構造体のrecordから、EventIDとか統計情報を取得するようにしてください。
// recordからEventIDを取得するには、detection::utils::get_event_value()という関数があるので、それを使うと便利かもしれません。
// 現状では、この関数の戻り値として返すVec<String>を表示するコードは実装していません。
pub fn start(&mut self, _records: &Vec<EvtxRecordInfo>) -> Vec<String> {
// 引数でstatisticsオプションが指定されている時だけ、統計情報を出力する。
if !configs::CONFIG
.read()
.unwrap()
.args
.is_present("statistics")
{
return vec![];
}
// TODO ここから下を書いて欲しいです。
return vec![];
}
}

17
src/timeline/timeline.rs Normal file
View File

@@ -0,0 +1,17 @@
use crate::detections::detection::EvtxRecordInfo;
use super::statistics::EventStatistics;
#[derive(Debug)]
pub struct Timeline {}
impl Timeline {
pub fn new() -> Timeline {
return Timeline {};
}
pub fn start(&mut self, records: &Vec<EvtxRecordInfo>) {
let mut statistic = EventStatistics::new();
statistic.start(records);
}
}