-
Notifications
You must be signed in to change notification settings - Fork 203
/
afterfact.rs
4512 lines (4371 loc) · 173 KB
/
afterfact.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::detections::configs::{
Action, OutputOption, StoredStatic, CONTROL_CHAT_REPLACE_MAP, CURRENT_EXE_PATH, GEOIP_DB_PARSER,
};
use crate::detections::message::{AlertMessage, DetectInfo, COMPUTER_MITRE_ATTCK_MAP, LEVEL_FULL};
use crate::detections::utils::{
self, format_time, get_writable_color, output_and_data_stack_for_html, write_color_buffer,
};
use crate::options::htmlreport;
use crate::options::profile::Profile;
use crate::yaml::ParseYaml;
use aho_corasick::{AhoCorasick, AhoCorasickBuilder, MatchKind};
use chrono::{DateTime, Local, TimeZone, Utc};
use comfy_table::modifiers::UTF8_ROUND_CORNERS;
use comfy_table::presets::UTF8_FULL;
use compact_str::CompactString;
use hashbrown::hash_map::RawEntryMut;
use terminal_size::terminal_size;
use csv::{QuoteStyle, Writer, WriterBuilder};
use itertools::Itertools;
use krapslog::{build_sparkline, build_time_markers};
use nested::Nested;
use std::path::Path;
use std::str::FromStr;
use yaml_rust::YamlLoader;
use comfy_table::*;
use hashbrown::{HashMap, HashSet};
use num_format::{Locale, ToFormattedString};
use std::cmp::{self, min, Ordering};
use std::error::Error;
use std::io::{self, BufWriter, Write};
use lazy_static::lazy_static;
use std::fs::File;
use std::process;
use termcolor::{Buffer, BufferWriter, Color, ColorChoice, ColorSpec, WriteColor};
use terminal_size::Width;
lazy_static! {
// ここで字句解析するときに使う正規表現の一覧を定義する。
// ここはSigmaのGithubレポジトリにある、toos/sigma/parser/condition.pyのSigmaConditionTokenizerのtokendefsを参考にしています。
pub static ref LEVEL_MAP: HashMap<String, u128> = HashMap::from([
("INFORMATIONAL".to_string(), 1),
("LOW".to_string(), 2),
("MEDIUM".to_string(), 3),
("HIGH".to_string(), 4),
("CRITICAL".to_string(), 5),
]);
}
#[derive(Debug)]
pub struct Colors {
pub output_color: termcolor::Color,
pub table_color: comfy_table::Color,
}
pub struct AfterfactInfo {
pub tl_starttime: Option<DateTime<Utc>>,
pub tl_endtime: Option<DateTime<Utc>>,
pub record_cnt: u128,
pub recover_record_cnt: u128,
pub detected_record_idset: HashSet<CompactString>,
pub total_detect_counts_by_level: Vec<u128>,
pub unique_detect_counts_by_level: Vec<u128>,
pub detect_counts_by_date_and_level: HashMap<CompactString, HashMap<CompactString, i128>>,
pub detect_counts_by_computer_and_level: HashMap<CompactString, HashMap<CompactString, i128>>,
pub detect_counts_by_rule_and_level: HashMap<CompactString, HashMap<CompactString, i128>>,
pub detect_rule_authors: HashMap<CompactString, CompactString>,
pub rule_title_path_map: HashMap<CompactString, CompactString>,
pub rule_author_counter: HashMap<CompactString, i128>,
pub timestamps: Vec<i64>,
pub has_displayed_header: bool,
pub detected_rule_files: HashSet<CompactString>,
pub detected_rule_ids: HashSet<CompactString>,
pub detected_computer_and_rule_names: HashSet<CompactString>,
pub author_list_cache: HashMap<CompactString, Nested<String>>,
pub prev_message: HashMap<CompactString, Profile>,
pub prev_details_convert_map: HashMap<CompactString, Vec<CompactString>>,
}
struct InitLevelMapResult(
HashMap<CompactString, HashMap<CompactString, i128>>,
HashMap<CompactString, HashMap<CompactString, i128>>,
HashMap<CompactString, HashMap<CompactString, i128>>,
);
impl Default for AfterfactInfo {
fn default() -> Self {
let InitLevelMapResult(
detect_counts_by_date_and_level,
detect_counts_by_computer_and_level,
detect_counts_by_rule_and_level,
) = {
let levels = ["crit", "high", "med ", "low ", "info", "undefined"];
let mut detect_counts_by_date_and_level: HashMap<
CompactString,
HashMap<CompactString, i128>,
> = HashMap::new();
let mut detect_counts_by_computer_and_level: HashMap<
CompactString,
HashMap<CompactString, i128>,
> = HashMap::new();
let mut detect_counts_by_rule_and_level: HashMap<
CompactString,
HashMap<CompactString, i128>,
> = HashMap::new();
// レベル別、日ごとの集計用変数の初期化
for level_init in levels {
detect_counts_by_date_and_level
.insert(CompactString::from(level_init), HashMap::new());
detect_counts_by_computer_and_level
.insert(CompactString::from(level_init), HashMap::new());
detect_counts_by_rule_and_level
.insert(CompactString::from(level_init), HashMap::new());
}
InitLevelMapResult(
detect_counts_by_date_and_level,
detect_counts_by_computer_and_level,
detect_counts_by_rule_and_level,
)
};
AfterfactInfo {
tl_starttime: Option::None,
tl_endtime: Option::None,
record_cnt: 0,
recover_record_cnt: 0,
detected_record_idset: HashSet::new(),
total_detect_counts_by_level: vec![0; 6],
unique_detect_counts_by_level: vec![0; 6],
detect_counts_by_date_and_level,
detect_counts_by_computer_and_level,
detect_counts_by_rule_and_level,
detect_rule_authors: HashMap::new(),
rule_title_path_map: HashMap::new(),
rule_author_counter: HashMap::new(),
timestamps: vec![],
has_displayed_header: false,
detected_rule_files: HashSet::new(),
detected_rule_ids: HashSet::new(),
detected_computer_and_rule_names: HashSet::new(),
author_list_cache: HashMap::new(),
prev_message: HashMap::new(),
prev_details_convert_map: HashMap::new(),
}
}
}
pub struct AfterfactWriter {
disp_wtr: BufferWriter,
disp_wtr_buf: Buffer,
csv_writer: Writer<Box<dyn io::Write>>,
pub display_flag: bool,
}
pub fn init_writer(stored_static: &StoredStatic) -> AfterfactWriter {
let disp_wtr = BufferWriter::stdout(ColorChoice::Always);
let mut disp_wtr_buf = disp_wtr.buffer();
disp_wtr_buf.set_color(ColorSpec::new().set_fg(None)).ok();
let mut display_flag = false;
let target: Box<dyn io::Write> = if let Some(path) = &stored_static.output_path {
// output to file
match File::create(path) {
Ok(file) => Box::new(BufWriter::new(file)),
Err(err) => {
AlertMessage::alert(&format!("Failed to open file. {err}")).ok();
process::exit(1);
}
}
} else {
display_flag = true;
// stdoutput (termcolor crate color output is not csv writer)
Box::new(BufWriter::new(io::stdout()))
};
let writer = match &stored_static.config.action.as_ref().unwrap() {
Action::JsonTimeline(_) => WriterBuilder::new()
.delimiter(b'\n')
.double_quote(false)
.quote_style(QuoteStyle::Never)
.from_writer(target),
Action::CsvTimeline(_) => WriterBuilder::new()
.quote_style(QuoteStyle::NonNumeric)
.from_writer(target),
_ => WriterBuilder::new().from_writer(target),
};
// emit csv
AfterfactWriter {
disp_wtr,
disp_wtr_buf,
csv_writer: writer,
display_flag,
}
}
pub fn output_afterfact(
detect_infos: &mut [DetectInfo],
afterfact_writer: &mut AfterfactWriter,
stored_static: &StoredStatic,
afterfact_info: &mut AfterfactInfo,
) {
let ret = output_afterfact_inner(
detect_infos,
afterfact_writer,
stored_static,
afterfact_info,
);
if ret.is_err() {
output_afterfact_err(Box::new(ret.err().unwrap()));
}
}
pub fn emit_csv(
detect_infos: &[DetectInfo],
duplicate_idxes: &HashSet<usize>,
stored_static: &StoredStatic,
afterfact_writer: &mut AfterfactWriter,
afterfact_info: &mut AfterfactInfo,
) {
if detect_infos.is_empty() {
return;
}
let result = emit_csv_inner(
detect_infos,
duplicate_idxes,
stored_static,
afterfact_writer,
afterfact_info,
);
if result.is_err() {
output_afterfact_err(Box::new(result.err().unwrap()));
}
calc_statistic_info(detect_infos, duplicate_idxes, afterfact_info, stored_static);
}
fn output_afterfact_err(err: Box<dyn Error>) {
AlertMessage::alert(&format!("Failed to write CSV. {err}")).ok();
process::exit(1);
}
fn output_afterfact_inner(
detect_infos: &mut [DetectInfo],
afterfact_writer: &mut AfterfactWriter,
stored_static: &StoredStatic,
afterfact_info: &mut AfterfactInfo,
) -> io::Result<()> {
if afterfact_writer.display_flag {
println!();
}
// sort and filter detect infos
sort_detect_info(detect_infos);
let duplicate_idxes = if stored_static
.output_option
.as_ref()
.unwrap()
.remove_duplicate_detections
{
get_duplicate_idxes(detect_infos)
} else {
HashSet::new()
};
emit_csv_inner(
detect_infos,
&duplicate_idxes,
stored_static,
afterfact_writer,
afterfact_info,
)?;
// calculate statistic information
calc_statistic_info(
detect_infos,
&duplicate_idxes,
afterfact_info,
stored_static,
);
afterfact_writer.disp_wtr_buf.clear();
output_additional_afterfact(stored_static, afterfact_writer, afterfact_info);
Ok(())
}
fn emit_csv_inner(
detect_infos: &[DetectInfo],
duplicate_idxes: &HashSet<usize>,
stored_static: &StoredStatic,
afterfact_writer: &mut AfterfactWriter,
afterfact_info: &mut AfterfactInfo,
) -> io::Result<()> {
let output_replaced_maps: HashMap<&str, &str> =
HashMap::from_iter(vec![("🛂r", "\r"), ("🛂n", "\n"), ("🛂t", "\t")]);
let mut removed_replaced_maps: HashMap<&str, &str> =
HashMap::from_iter(vec![("\n", " "), ("\r", " "), ("\t", " ")]);
if stored_static.multiline_flag {
removed_replaced_maps.insert("🛂🛂", "\r\n");
removed_replaced_maps.insert(" ¦ ", "\r\n");
}
let output_replacer = AhoCorasickBuilder::new()
.match_kind(MatchKind::LeftmostLongest)
.build(output_replaced_maps.keys())
.unwrap();
let output_remover = AhoCorasickBuilder::new()
.match_kind(MatchKind::LeftmostLongest)
.build(removed_replaced_maps.keys())
.unwrap();
// remove duplicate dataのための前レコード分の情報を保持する変数
let color_map = create_output_color_map(stored_static.common_options.no_color);
let (json_output_flag, jsonl_output_flag, remove_duplicate_data) =
match &stored_static.config.action.as_ref().unwrap() {
Action::JsonTimeline(option) => (
true,
option.jsonl_timeline,
option.output_options.remove_duplicate_data,
),
Action::CsvTimeline(option) => {
(false, false, option.output_options.remove_duplicate_data)
}
_ => (false, false, false),
};
let profile = stored_static.profiles.as_ref().unwrap();
for (i, detect_info) in detect_infos.iter().enumerate() {
if duplicate_idxes.contains(&i) {
continue;
}
if afterfact_writer.display_flag && !(json_output_flag || jsonl_output_flag) {
// 標準出力の場合
if !afterfact_info.has_displayed_header {
// ヘッダーのみを出力
_get_serialized_disp_output(
&afterfact_writer.disp_wtr,
profile,
true,
(&output_replacer, &output_replaced_maps),
(&output_remover, &removed_replaced_maps),
stored_static.common_options.no_color,
get_writable_color(
_get_output_color(
&color_map,
LEVEL_FULL.get(detect_info.level.as_str()).unwrap_or(&""),
),
stored_static.common_options.no_color,
),
);
afterfact_info.has_displayed_header = true;
}
_get_serialized_disp_output(
&afterfact_writer.disp_wtr,
&detect_info.ext_field,
false,
(&output_replacer, &output_replaced_maps),
(&output_remover, &removed_replaced_maps),
stored_static.common_options.no_color,
get_writable_color(
_get_output_color(
&color_map,
LEVEL_FULL.get(detect_info.level.as_str()).unwrap_or(&""),
),
stored_static.common_options.no_color,
),
);
} else if jsonl_output_flag {
// JSONL output format
let result = output_json_str(
detect_info,
afterfact_info,
jsonl_output_flag,
GEOIP_DB_PARSER.read().unwrap().is_some(),
remove_duplicate_data,
);
afterfact_info.prev_message = result.1;
afterfact_info.prev_details_convert_map = detect_info.details_convert_map.clone();
if afterfact_writer.display_flag {
write_color_buffer(
&afterfact_writer.disp_wtr,
None,
&format!("{{ {} }}", &result.0),
true,
)
.ok();
} else {
afterfact_writer
.csv_writer
.write_field(format!("{{ {} }}", &result.0))?;
}
} else if json_output_flag {
// JSON output
let result = output_json_str(
detect_info,
afterfact_info,
jsonl_output_flag,
GEOIP_DB_PARSER.read().unwrap().is_some(),
remove_duplicate_data,
);
afterfact_info.prev_message = result.1;
afterfact_info.prev_details_convert_map = detect_info.details_convert_map.clone();
if afterfact_writer.display_flag {
write_color_buffer(
&afterfact_writer.disp_wtr,
None,
&format!("{{\n{}\n}}", &result.0),
true,
)
.ok();
} else {
afterfact_writer.csv_writer.write_field("{")?;
afterfact_writer.csv_writer.write_field(&result.0)?;
afterfact_writer.csv_writer.write_field("}")?;
}
} else {
// csv output format
if !afterfact_info.has_displayed_header {
afterfact_writer
.csv_writer
.write_record(detect_info.ext_field.iter().map(|x| x.0.trim()))?;
afterfact_info.has_displayed_header = true;
}
afterfact_writer
.csv_writer
.write_record(detect_info.ext_field.iter().map(|x| {
match x.1 {
Profile::Details(_)
| Profile::AllFieldInfo(_)
| Profile::ExtraFieldInfo(_) => {
let ret = if remove_duplicate_data
&& x.1.to_value()
== afterfact_info
.prev_message
.get(&x.0)
.unwrap_or(&Profile::Literal("-".into()))
.to_value()
{
"DUP".to_string()
} else {
output_remover.replace_all(
&output_replacer
.replace_all(
&x.1.to_value(),
&output_replaced_maps.values().collect_vec(),
)
.split_whitespace()
.join(" "),
&removed_replaced_maps.values().collect_vec(),
)
};
afterfact_info.prev_message.insert(x.0.clone(), x.1.clone());
ret
}
_ => output_remover.replace_all(
&output_replacer
.replace_all(
&x.1.to_value(),
&output_replaced_maps.values().collect_vec(),
)
.split_whitespace()
.join(" "),
&removed_replaced_maps.values().collect_vec(),
),
}
}))?;
}
}
if !afterfact_writer.display_flag {
afterfact_writer.csv_writer.flush()?;
}
Ok(())
}
fn calc_statistic_info(
detect_infos: &[DetectInfo],
duplicate_idxes: &HashSet<usize>,
afterfact_info: &mut AfterfactInfo,
stored_static: &StoredStatic,
) {
let output_option = stored_static.output_option.as_ref().unwrap();
for (i, detect_info) in detect_infos.iter().enumerate() {
if duplicate_idxes.contains(&i) {
continue;
}
if !detect_info.is_condition {
afterfact_info
.detected_record_idset
.insert(CompactString::from(format!(
"{}_{}",
detect_info.detected_time, detect_info.eventid
)));
}
if !output_option.no_summary {
let level_suffix = get_level_suffix(detect_info.level.as_str());
let author_list = afterfact_info
.author_list_cache
.entry(detect_info.rulepath.clone())
.or_insert_with(|| extract_author_name(&detect_info.rulepath))
.clone();
let author_str = author_list.iter().join(", ");
afterfact_info
.detect_rule_authors
.insert(detect_info.rulepath.to_owned(), author_str.into());
if !afterfact_info
.detected_rule_files
.contains(&detect_info.rulepath)
{
afterfact_info
.detected_rule_files
.insert(detect_info.rulepath.to_owned());
for author in author_list.iter() {
*afterfact_info
.rule_author_counter
.entry(CompactString::from(author))
.or_insert(0) += 1;
}
}
if !afterfact_info
.detected_rule_ids
.contains(&detect_info.ruleid)
{
afterfact_info
.detected_rule_ids
.insert(detect_info.ruleid.to_owned());
afterfact_info.unique_detect_counts_by_level[level_suffix] += 1;
}
let computer_rule_check_key = CompactString::from(format!(
"{}|{}",
&detect_info.computername, &detect_info.rulepath
));
if !afterfact_info
.detected_computer_and_rule_names
.contains(&computer_rule_check_key)
{
afterfact_info
.detected_computer_and_rule_names
.insert(computer_rule_check_key);
countup_aggregation(
&mut afterfact_info.detect_counts_by_computer_and_level,
&detect_info.level,
&detect_info.computername,
);
}
afterfact_info.rule_title_path_map.insert(
detect_info.ruletitle.to_owned(),
detect_info.rulepath.to_owned(),
);
countup_aggregation(
&mut afterfact_info.detect_counts_by_date_and_level,
&detect_info.level,
&format_time(&detect_info.detected_time, true, output_option),
);
countup_aggregation(
&mut afterfact_info.detect_counts_by_rule_and_level,
&detect_info.level,
&detect_info.ruletitle,
);
afterfact_info.total_detect_counts_by_level[level_suffix] += 1;
}
}
}
pub fn output_additional_afterfact(
stored_static: &StoredStatic,
afterfact_writer: &mut AfterfactWriter,
afterfact_info: &AfterfactInfo,
) {
if afterfact_writer.display_flag {
println!();
}
let terminal_width = match terminal_size() {
Some((Width(w), _)) => w as usize,
None => 100,
};
let level_abbr: Nested<Vec<CompactString>> = Nested::from_iter(
[
[CompactString::from("critical"), CompactString::from("crit")].to_vec(),
[CompactString::from("high"), CompactString::from("high")].to_vec(),
[CompactString::from("medium"), CompactString::from("med ")].to_vec(),
[CompactString::from("low"), CompactString::from("low ")].to_vec(),
[
CompactString::from("informational"),
CompactString::from("info"),
]
.to_vec(),
]
.iter(),
);
let output_option = stored_static.output_option.as_ref().unwrap();
if !output_option.no_summary && !afterfact_info.rule_author_counter.is_empty() {
write_color_buffer(
&afterfact_writer.disp_wtr,
get_writable_color(
Some(Color::Rgb(0, 255, 0)),
stored_static.common_options.no_color,
),
"Rule Authors:",
false,
)
.ok();
write_color_buffer(
&afterfact_writer.disp_wtr,
get_writable_color(None, stored_static.common_options.no_color),
" ",
true,
)
.ok();
println!();
let table_column_num = if terminal_width <= 105 {
2
} else if terminal_width < 140 {
3
} else if terminal_width < 175 {
4
} else if terminal_width <= 210 {
5
} else {
6
};
output_detected_rule_authors(&afterfact_info.rule_author_counter, table_column_num);
}
println!();
if output_option.visualize_timeline {
_print_timeline_hist(&afterfact_info.timestamps, terminal_width, 3);
println!();
}
let mut html_output_stock = Nested::<String>::new();
if !output_option.no_summary {
afterfact_writer.disp_wtr_buf.clear();
write_color_buffer(
&afterfact_writer.disp_wtr,
get_writable_color(
Some(Color::Rgb(0, 255, 0)),
stored_static.common_options.no_color,
),
"Results Summary:\n",
true,
)
.ok();
if afterfact_info.tl_starttime.is_some() {
output_and_data_stack_for_html(
&format!(
"First Timestamp: {}",
utils::format_time(
&afterfact_info.tl_starttime.unwrap(),
false,
stored_static.output_option.as_ref().unwrap()
)
),
"Results Summary {#results_summary}",
&stored_static.html_report_flag,
);
}
if afterfact_info.tl_endtime.is_some() {
output_and_data_stack_for_html(
&format!(
"Last Timestamp: {}",
utils::format_time(
&afterfact_info.tl_endtime.unwrap(),
false,
stored_static.output_option.as_ref().unwrap()
)
),
"Results Summary {#results_summary}",
&stored_static.html_report_flag,
);
println!();
}
let reducted_record_cnt: u128 =
afterfact_info.record_cnt - afterfact_info.detected_record_idset.len() as u128;
let reducted_percent = if afterfact_info.record_cnt == 0 {
0 as f64
} else {
(reducted_record_cnt as f64) / (afterfact_info.record_cnt as f64) * 100.0
};
write_color_buffer(
&afterfact_writer.disp_wtr,
get_writable_color(
Some(Color::Rgb(255, 255, 0)),
stored_static.common_options.no_color,
),
"Events with hits",
false,
)
.ok();
write_color_buffer(
&afterfact_writer.disp_wtr,
get_writable_color(None, stored_static.common_options.no_color),
" / ",
false,
)
.ok();
write_color_buffer(
&afterfact_writer.disp_wtr,
get_writable_color(
Some(Color::Rgb(0, 255, 255)),
stored_static.common_options.no_color,
),
"Total events",
false,
)
.ok();
write_color_buffer(
&afterfact_writer.disp_wtr,
get_writable_color(None, stored_static.common_options.no_color),
": ",
false,
)
.ok();
let saved_alerts_output =
(afterfact_info.record_cnt - reducted_record_cnt).to_formatted_string(&Locale::en);
write_color_buffer(
&afterfact_writer.disp_wtr,
get_writable_color(
Some(Color::Rgb(255, 255, 0)),
stored_static.common_options.no_color,
),
&saved_alerts_output,
false,
)
.ok();
write_color_buffer(
&afterfact_writer.disp_wtr,
get_writable_color(None, stored_static.common_options.no_color),
" / ",
false,
)
.ok();
let all_record_output = afterfact_info.record_cnt.to_formatted_string(&Locale::en);
write_color_buffer(
&afterfact_writer.disp_wtr,
get_writable_color(
Some(Color::Rgb(0, 255, 255)),
stored_static.common_options.no_color,
),
&all_record_output,
false,
)
.ok();
write_color_buffer(
&afterfact_writer.disp_wtr,
get_writable_color(None, stored_static.common_options.no_color),
" (",
false,
)
.ok();
let reduction_output = format!(
"Data reduction: {} events ({:.2}%)",
reducted_record_cnt.to_formatted_string(&Locale::en),
reducted_percent
);
write_color_buffer(
&afterfact_writer.disp_wtr,
get_writable_color(
Some(Color::Rgb(0, 255, 0)),
stored_static.common_options.no_color,
),
&reduction_output,
false,
)
.ok();
write_color_buffer(
&afterfact_writer.disp_wtr,
get_writable_color(None, stored_static.common_options.no_color),
")",
true,
)
.ok();
if stored_static.enable_recover_records {
write_color_buffer(
&afterfact_writer.disp_wtr,
get_writable_color(
Some(Color::Rgb(0, 255, 255)),
stored_static.common_options.no_color,
),
"Recovered records",
false,
)
.ok();
write_color_buffer(
&afterfact_writer.disp_wtr,
get_writable_color(None, stored_static.common_options.no_color),
": ",
false,
)
.ok();
let recovered_record_output = afterfact_info
.recover_record_cnt
.to_formatted_string(&Locale::en);
write_color_buffer(
&afterfact_writer.disp_wtr,
get_writable_color(
Some(Color::Rgb(0, 255, 255)),
stored_static.common_options.no_color,
),
&recovered_record_output,
true,
)
.ok();
}
println!();
if stored_static.html_report_flag {
html_output_stock.push(format!("- Events with hits: {}", &saved_alerts_output));
html_output_stock.push(format!("- Total events analyzed: {}", &all_record_output));
html_output_stock.push(format!("- {reduction_output}"));
html_output_stock.push(format!(
"- Recovered events analyzed: {}",
&afterfact_info
.recover_record_cnt
.to_formatted_string(&Locale::en)
));
}
let color_map = create_output_color_map(stored_static.common_options.no_color);
_print_unique_results(
&afterfact_info.total_detect_counts_by_level,
&afterfact_info.unique_detect_counts_by_level,
(
CompactString::from("Total | Unique"),
CompactString::from("detections"),
),
&color_map,
&level_abbr,
&mut html_output_stock,
stored_static.html_report_flag,
);
println!();
_print_detection_summary_by_date(
&afterfact_info.detect_counts_by_date_and_level,
&color_map,
&level_abbr,
&mut html_output_stock,
stored_static,
);
println!();
println!();
if stored_static.html_report_flag {
html_output_stock.push("");
}
_print_detection_summary_by_computer(
&afterfact_info.detect_counts_by_computer_and_level,
&color_map,
&level_abbr,
&mut html_output_stock,
stored_static,
);
println!();
if stored_static.html_report_flag {
html_output_stock.push("");
}
_print_detection_summary_tables(
&afterfact_info.detect_counts_by_rule_and_level,
&color_map,
(
&afterfact_info.rule_title_path_map,
&afterfact_info.detect_rule_authors,
),
&level_abbr,
&mut html_output_stock,
stored_static,
cmp::min((terminal_width / 2) - 15, 200),
);
println!();
if stored_static.html_report_flag {
html_output_stock.push("");
}
}
if stored_static.html_report_flag {
_output_html_computer_by_mitre_attck(&mut html_output_stock);
htmlreport::add_md_data("Results Summary {#results_summary}", html_output_stock);
}
}
pub fn sort_detect_info(detect_infos: &mut [DetectInfo]) {
detect_infos.sort_unstable_by(|a, b| {
let cmp_time = a.detected_time.cmp(&b.detected_time);
if cmp_time != Ordering::Equal {
return cmp_time;
}
let a_level = get_level_suffix(a.level.as_str());
let b_level = get_level_suffix(b.level.as_str());
let level_cmp = a_level.cmp(&b_level);
if level_cmp != Ordering::Equal {
return level_cmp;
}
let event_id_cmp = a.eventid.cmp(&b.eventid);
if event_id_cmp != Ordering::Equal {
return event_id_cmp;
}
let rulepath_cmp = a.rulepath.cmp(&b.rulepath);
if rulepath_cmp != Ordering::Equal {
return rulepath_cmp;
}
a.computername.cmp(&b.computername)
});
}
fn get_level_suffix(level_str: &str) -> usize {
*LEVEL_MAP
.get(
LEVEL_FULL
.get(level_str)
.unwrap_or(&"undefined")
.to_uppercase()
.as_str(),
)
.unwrap_or(&0) as usize
}
pub fn get_duplicate_idxes(detect_infos: &mut [DetectInfo]) -> HashSet<usize> {
// filtet duplicate event
let mut filtered_detect_infos = HashSet::new();
let mut prev_detect_infos = HashSet::new();
for (i, detect_info) in detect_infos.iter().enumerate() {
if i == 0 {
continue;
}
let prev_detect_info = &detect_infos[i - 1];
if prev_detect_info
.detected_time
.cmp(&detect_info.detected_time)
!= Ordering::Equal
{
prev_detect_infos.clear();
continue;
}
let fields: Vec<&(CompactString, Profile)> = detect_info
.ext_field
.iter()
.filter(|(_, profile)| !matches!(profile, Profile::EvtxFile(_)))
.collect();
if prev_detect_infos.get(&fields).is_some() {
filtered_detect_infos.insert(i);
continue;
}
prev_detect_infos.insert(fields);
}
filtered_detect_infos
}
/// level_color.txtファイルを読み込み対応する文字色のマッピングを返却する関数
pub fn create_output_color_map(no_color_flag: bool) -> HashMap<CompactString, Colors> {
let read_result = utils::read_csv(
utils::check_setting_path(
&CURRENT_EXE_PATH.to_path_buf(),
"config/level_color.txt",
true,
)
.unwrap()
.to_str()
.unwrap(),
);
let mut color_map: HashMap<CompactString, Colors> = HashMap::new();
if no_color_flag {
return color_map;
}
let color_map_contents = match read_result {
Ok(c) => c,
Err(e) => {
// color情報がない場合は通常の白色の出力が出てくるのみで動作への影響を与えない為warnとして処理する
AlertMessage::warn(&e).ok();
return color_map;
}
};
color_map_contents.iter().for_each(|line| {
if line.len() != 2 {
return;
}
let empty = &"".to_string();