forked from WithSecureLabs/chainsaw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.rs
1049 lines (1006 loc) · 38.6 KB
/
main.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
#[macro_use]
extern crate chainsaw;
use std::fs::{self, File};
use std::io::BufRead;
use std::path::PathBuf;
use std::{collections::HashSet, io::BufReader};
use anyhow::{Context, Result};
use bytesize::ByteSize;
use chrono::NaiveDateTime;
use chrono_tz::Tz;
use clap::{Parser, Subcommand};
use chainsaw::{
cli, get_files, lint as lint_rule, load as load_rule, set_writer, Document, Filter, Format,
Hunter, Reader, RuleKind, RuleLevel, RuleStatus, Searcher, ShimcacheAnalyser, SrumAnalyser,
Writer,
};
#[derive(Parser)]
#[clap(
name = "chainsaw",
about = "Rapidly work with Forensic Artefacts",
after_help = r"Examples:
Hunt with Sigma and Chainsaw Rules:
./chainsaw hunt evtx_attack_samples/ -s sigma/ --mapping mappings/sigma-event-logs-all.yml -r rules/
Hunt with Sigma rules and output in JSON:
./chainsaw hunt evtx_attack_samples/ -s sigma/ --mapping mappings/sigma-event-logs-all.yml --json
Search for the case-insensitive word 'mimikatz':
./chainsaw search mimikatz -i evtx_attack_samples/
Search for Powershell Script Block Events (EventID 4014):
./chainsaw search -t 'Event.System.EventID: =4104' evtx_attack_samples/
",
version
)]
struct Args {
/// Hide Chainsaw's banner.
#[arg(long)]
no_banner: bool,
/// Limit the thread number (default: num of CPUs)
#[arg(long)]
num_threads: Option<usize>,
#[command(subcommand)]
cmd: Command,
}
#[derive(Subcommand)]
enum Command {
/// Dump an artefact into a different format.
Dump {
/// The path to an artefact to dump.
path: PathBuf,
/// Dump in json format.
#[arg(group = "format", short = 'j', long = "json")]
json: bool,
/// Print the output in jsonl format.
#[arg(group = "format", long = "jsonl")]
jsonl: bool,
/// Allow chainsaw to try and load files it cannot identify.
#[arg(long = "load-unknown")]
load_unknown: bool,
/// A path to output results to.
#[arg(short = 'o', long = "output")]
output: Option<PathBuf>,
/// Suppress informational output.
#[arg(short = 'q')]
quiet: bool,
/// Continue to hunt when an error is encountered.
#[arg(long = "skip-errors")]
skip_errors: bool,
},
/// Hunt through artefacts using detection rules for threat detection.
Hunt {
/// The path to a collection of rules to use for hunting.
rules: Option<PathBuf>,
/// The paths containing files to load and hunt through.
path: Vec<PathBuf>,
/// A mapping file to tell Chainsaw how to use third-party rules.
#[arg(short = 'm', long = "mapping", number_of_values = 1)]
mapping: Option<Vec<PathBuf>>,
/// A path containing additional rules to hunt with.
#[arg(short = 'r', long = "rule", number_of_values = 1)]
rule: Option<Vec<PathBuf>>,
/// Cache results to disk to reduce memory usage at the cost of performance.
#[arg(
short = 'c',
long = "cache-to-disk",
requires = "jsonl",
conflicts_with = "json"
)]
cache: bool,
/// Set the column width for the tabular output.
#[arg(long = "column-width", conflicts_with = "json")]
column_width: Option<u32>,
/// Print the output in csv format.
#[arg(group = "format", long = "csv", requires = "output")]
csv: bool,
/// Only hunt through files with the provided extension.
#[arg(long = "extension", number_of_values = 1)]
extension: Option<Vec<String>>,
/// The timestamp to hunt from. Drops any documents older than the value provided.
/// (YYYY-MM-ddTHH:mm:SS)
#[arg(long = "from")]
from: Option<NaiveDateTime>,
/// Print the full values for the tabular output.
#[arg(long = "full", conflicts_with = "json")]
full: bool,
/// Print the output in json format.
#[arg(group = "format", short = 'j', long = "json")]
json: bool,
/// Print the output in jsonl format.
#[arg(group = "format", long = "jsonl")]
jsonl: bool,
/// Restrict loaded rules to specified kinds.
#[arg(long = "kind", number_of_values = 1)]
kind: Vec<RuleKind>,
/// Restrict loaded rules to specified levels.
#[arg(long = "level", number_of_values = 1)]
level: Vec<RuleLevel>,
/// Allow chainsaw to try and load files it cannot identify.
#[arg(long = "load-unknown")]
load_unknown: bool,
/// Output the timestamp using the local machine's timestamp.
#[arg(long = "local", group = "tz")]
local: bool,
/// Display additional metadata in the tablar output.
#[arg(long = "metadata", conflicts_with = "json")]
metadata: bool,
/// A path to output results to.
#[arg(short = 'o', long = "output")]
output: Option<PathBuf>,
/// Print the output in log like format.
#[arg(group = "format", long = "log")]
log: bool,
/// (BETA) Enable preprocessing, which can result in increased performance.
#[arg(long = "preprocess")]
preprocess: bool,
/// Suppress informational output.
#[arg(short = 'q')]
quiet: bool,
/// A path containing Sigma rules to hunt with.
#[arg(
short = 's',
long = "sigma",
number_of_values = 1,
requires = "mapping"
)]
sigma: Option<Vec<PathBuf>>,
/// Continue to hunt when an error is encountered.
#[arg(long = "skip-errors")]
skip_errors: bool,
/// Restrict loaded rules to specified statuses.
#[arg(long = "status", number_of_values = 1)]
status: Vec<RuleStatus>,
/// Output the timestamp using the timezone provided.
#[arg(long = "timezone", group = "tz")]
timezone: Option<Tz>,
/// The timestamp to hunt up to. Drops any documents newer than the value provided.
/// (YYYY-MM-ddTHH:mm:SS)
#[arg(long = "to")]
to: Option<NaiveDateTime>,
},
/// Lint provided rules to ensure that they load correctly
Lint {
/// The path to a collection of rules.
path: PathBuf,
/// The kind of rule to lint: chainsaw, sigma or stalker
#[arg(long = "kind")]
kind: RuleKind,
/// Output tau logic.
#[arg(short = 't', long = "tau")]
tau: bool,
},
/// Search through forensic artefacts for keywords.
Search {
/// A string or regular expression pattern to search for.
/// Not used when -e or -t is specified.
#[arg(required_unless_present_any=&["additional_pattern", "tau"])]
pattern: Option<String>,
/// The paths containing files to load and hunt through.
path: Vec<PathBuf>,
/// A string or regular expression pattern to search for.
#[arg(
short = 'e',
long = "regex",
value_name = "pattern",
number_of_values = 1
)]
additional_pattern: Option<Vec<String>>,
/// Only search through files with the provided extension.
#[arg(long = "extension", number_of_values = 1)]
extension: Option<Vec<String>>,
/// The timestamp to search from. Drops any documents older than the value provided.
/// (YYYY-MM-ddTHH:mm:SS)
#[arg(long = "from", requires = "timestamp")]
from: Option<NaiveDateTime>,
/// Ignore the case when searching patterns
#[arg(short = 'i', long = "ignore-case")]
ignore_case: bool,
/// Print the output in json format.
#[arg(short = 'j', long = "json")]
json: bool,
/// Print the output in jsonl format.
#[arg(group = "format", long = "jsonl")]
jsonl: bool,
/// Allow chainsaw to try and load files it cannot identify.
#[arg(long = "load-unknown")]
load_unknown: bool,
/// Output the timestamp using the local machine's timestamp.
#[arg(long = "local", group = "tz")]
local: bool,
/// The path to output results to.
#[arg(short = 'o', long = "output")]
output: Option<PathBuf>,
/// Suppress informational output.
#[arg(short = 'q')]
quiet: bool,
/// Continue to search when an error is encountered.
#[arg(long = "skip-errors")]
skip_errors: bool,
/// Tau expressions to search with. e.g. 'Event.System.EventID: =4104'
#[arg(short = 't', long = "tau", number_of_values = 1)]
tau: Option<Vec<String>>,
/// The field that contains the timestamp.
#[arg(long = "timestamp")]
timestamp: Option<String>,
/// Output the timestamp using the timezone provided.
#[arg(long = "timezone", group = "tz")]
timezone: Option<Tz>,
/// The timestamp to search up to. Drops any documents newer than the value provided.
/// (YYYY-MM-ddTHH:mm:SS)
#[arg(long = "to", requires = "timestamp")]
to: Option<NaiveDateTime>,
},
/// Perform various analyses on artefacts
Analyse {
#[command(subcommand)]
cmd: AnalyseCommand,
},
}
#[derive(Subcommand)]
enum AnalyseCommand {
/// Create an execution timeline from the shimcache with optional amcache enrichments
Shimcache {
/// The path to the shimcache artefact (SYSTEM registry file)
shimcache: PathBuf,
/// A string or regular expression for detecting shimcache entries whose timestamp matches their insertion time
#[arg(
short = 'e',
long = "regex",
value_name = "pattern",
number_of_values = 1
)]
additional_pattern: Option<Vec<String>>,
/// The path to a newline delimited file containing regex patterns for detecting shimcache entries whose timestamp matches their insertion time
#[arg(short = 'r', long = "regexfile")]
regex_file: Option<PathBuf>,
/// The path to output the result csv file
#[arg(short = 'o', long = "output")]
output: Option<PathBuf>,
/// The path to the amcache artefact (Amcache.hve) for timeline enrichment
#[arg(short = 'a', long = "amcache")]
amcache: Option<PathBuf>,
/// Enable near timestamp pair detection between shimcache and amcache for finding additional insertion timestamps for shimcache entries
#[arg(short = 'p', long = "tspair", requires = "amcache")]
ts_near_pair_matching: bool,
},
/// Analyse the SRUM database
Srum {
/// The path to the SRUM database
srum_path: PathBuf,
/// The path to the SOFTWARE hive
#[arg(short = 's', long = "software")]
software_hive_path: PathBuf,
/// Only output details about the SRUM database
#[arg(long = "stats-only")]
stats_only: bool,
/// Suppress informational output.
#[arg(short = 'q')]
quiet: bool,
/// Save the output to a file
#[arg(short = 'o', long = "output")]
output: Option<PathBuf>,
},
}
fn print_title() {
cs_eprintln!(
"
██████╗██╗ ██╗ █████╗ ██╗███╗ ██╗███████╗ █████╗ ██╗ ██╗
██╔════╝██║ ██║██╔══██╗██║████╗ ██║██╔════╝██╔══██╗██║ ██║
██║ ███████║███████║██║██╔██╗ ██║███████╗███████║██║ █╗ ██║
██║ ██╔══██║██╔══██║██║██║╚██╗██║╚════██║██╔══██║██║███╗██║
╚██████╗██║ ██║██║ ██║██║██║ ╚████║███████║██║ ██║╚███╔███╔╝
╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚══╝╚══╝
By WithSecure Countercept (@FranticTyping, @AlexKornitzer)
"
);
}
fn resolve_col_width() -> Option<u32> {
use terminal_size::{terminal_size, Width};
if let Some((Width(w), _)) = terminal_size() {
match w {
50..=120 => Some(20),
121..=239 => Some(30),
240..=340 => Some(50),
341..=430 => Some(90),
431..=550 => Some(130),
551.. => Some(160),
_ => None,
}
} else {
None
}
}
fn init_writer(output: Option<PathBuf>, csv: bool, json: bool, quiet: bool) -> crate::Result<()> {
let (path, output) = match &output {
Some(path) => {
if csv {
(Some(path.to_path_buf()), None)
} else {
let file = match File::create(path) {
Ok(f) => f,
Err(e) => {
return Err(anyhow::anyhow!(
"Unable to write to specified output file - {} - {}",
path.display(),
e
));
}
};
(None, Some(file))
}
}
None => (None, None),
};
let format = if csv {
Format::Csv
} else if json {
Format::Json
} else {
Format::Std
};
let writer = Writer {
format,
output,
path,
quiet,
};
set_writer(writer).expect("could not set writer");
Ok(())
}
fn run() -> Result<()> {
let args = Args::parse();
if let Some(num_threads) = args.num_threads {
rayon::ThreadPoolBuilder::new()
.num_threads(num_threads)
.build_global()?;
}
match args.cmd {
Command::Dump {
path,
json,
jsonl,
load_unknown,
output,
quiet,
skip_errors,
} => {
init_writer(output, false, json, quiet)?;
if !args.no_banner {
print_title();
}
let mut reader = Reader::load(&path, load_unknown, skip_errors)?;
cs_eprintln!(
"[+] Dumping the contents of forensic artefact - {}...",
path.display()
);
if json {
cs_print!("[");
}
let mut first = true;
for result in reader.documents() {
let document = match result {
Ok(document) => document,
Err(e) => {
if skip_errors {
cs_eyellowln!(
"[!] failed to parse document '{}' - {}\n",
path.display(),
e
);
continue;
}
return Err(e);
}
};
let value = match document {
Document::Evtx(evtx) => evtx.data,
Document::Hve(json)
| Document::Json(json)
| Document::Xml(json)
| Document::Mft(json)
| Document::Esedb(json) => json,
};
if json {
if first {
first = false;
} else {
cs_println!(",");
}
cs_print_json_pretty!(&value)?;
} else if jsonl {
cs_print_json!(&value)?;
cs_println!();
} else {
cs_println!("---");
cs_print_yaml!(&value)?;
}
}
if json {
cs_println!("]");
}
cs_eprintln!("[+] Done");
}
Command::Hunt {
rules,
mut path,
mapping,
rule,
load_unknown,
cache,
mut column_width,
csv,
extension,
from,
full,
json,
jsonl,
kind,
level,
local,
metadata,
output,
log,
preprocess,
quiet,
sigma,
skip_errors,
status,
timezone,
to,
} => {
if column_width.is_none() {
column_width = resolve_col_width();
}
// CSV must be a folder when hunting due to the complexity of the output
if csv {
if let Some(path) = &output {
if path.is_file() {
let writer = Writer {
quiet,
..Default::default()
};
set_writer(writer).expect("could not set writer");
if !args.no_banner {
print_title();
}
anyhow::bail!("Unable to create output directory");
}
}
}
init_writer(output.clone(), csv, json, quiet)?;
if !args.no_banner {
print_title();
}
let mut rs = vec![];
if rule.is_some() || sigma.is_some() {
if let Some(rules) = rules {
let mut paths = vec![rules];
paths.extend(path);
path = paths;
}
} else if let Some(rules) = rules {
rs = vec![rules];
}
let mut rules = rs;
if let Some(rule) = rule {
rules.extend(rule)
};
let sigma = sigma.unwrap_or_default();
cs_eprintln!(
"[+] Loading detection rules from: {}",
rules
.iter()
.chain(sigma.iter())
.map(|r| r.display().to_string())
.collect::<Vec<_>>()
.join(", ")
);
let kinds: Option<HashSet<RuleKind>> = if kind.is_empty() {
None
} else {
Some(HashSet::from_iter(kind))
};
let levels: Option<HashSet<RuleLevel>> = if level.is_empty() {
None
} else {
Some(HashSet::from_iter(level))
};
let statuses: Option<HashSet<RuleStatus>> = if status.is_empty() {
None
} else {
Some(HashSet::from_iter(status))
};
let mut failed = 0;
let mut count = 0;
let mut rs = vec![];
for path in &rules {
for file in get_files(path, &None, skip_errors)? {
match load_rule(RuleKind::Chainsaw, &file, &kinds, &levels, &statuses) {
Ok(r) => {
if !r.is_empty() {
count += 1;
rs.extend(r)
}
}
Err(_) => {
failed += 1;
}
}
}
}
for path in &sigma {
for file in get_files(path, &None, skip_errors)? {
match load_rule(RuleKind::Sigma, &file, &kinds, &levels, &statuses) {
Ok(r) => {
if !r.is_empty() {
count += 1;
rs.extend(r)
}
}
Err(_) => {
failed += 1;
}
}
}
}
if failed > 500 && sigma.is_empty() {
cs_eyellowln!("[!] {} rules failed to load, ensure Sigma rule paths are specified with the '-s' flag", failed);
}
if count == 0 {
return Err(anyhow::anyhow!(
"No valid detection rules were found in the provided paths",
));
}
if failed > 0 {
cs_eyellowln!(
"[!] Loaded {} detection rules ({} not loaded)",
count,
failed
);
} else {
cs_eprintln!("[+] Loaded {} detection rules", count);
}
let rules = rs;
let mut hunter = Hunter::builder()
.rules(rules)
.mappings(mapping.unwrap_or_default())
.load_unknown(load_unknown)
.local(local)
.preprocess(preprocess)
.skip_errors(skip_errors);
if let Some(from) = from {
hunter = hunter.from(from);
}
if let Some(timezone) = timezone {
hunter = hunter.timezone(timezone);
}
if let Some(to) = to {
hunter = hunter.to(to);
}
let hunter = hunter.build()?;
/* if no user-defined extensions are specified, then we parse rules and
mappings to build a list of file extensions that should be loaded */
let mut scratch = HashSet::new();
let message;
let exts = if load_unknown {
message = "*".to_string();
None
} else {
scratch.extend(hunter.extensions());
if scratch.is_empty() {
return Err(anyhow::anyhow!(
"No valid file extensions for the 'kind' specified in the mapping or rules files"
));
}
if let Some(e) = extension {
// User has provided specific extensions
scratch = scratch
.intersection(&HashSet::from_iter(e.iter().cloned()))
.cloned()
.collect();
if scratch.is_empty() {
return Err(anyhow::anyhow!(
"The specified file extension is not supported. Use --load-unknown to force loading",
));
}
};
message = scratch
.iter()
.map(|x| format!(".{}", x))
.collect::<Vec<_>>()
.join(", ");
Some(scratch)
};
cs_eprintln!(
"[+] Loading forensic artefacts from: {} (extensions: {})",
path.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", "),
message
);
let mut files = vec![];
let mut size = ByteSize::mb(0);
for path in &path {
let res = get_files(path, &exts, skip_errors)?;
for i in &res {
size += i.metadata()?.len();
}
files.extend(res);
}
if files.is_empty() {
return Err(anyhow::anyhow!(
"No compatible files were found in the provided paths",
));
} else {
cs_eprintln!("[+] Loaded {} forensic artefacts ({})", files.len(), size);
}
let mut hits = 0;
let mut documents = 0;
let mut detections = vec![];
let pb = cli::init_progress_bar(files.len() as u64, "Hunting".to_string());
for file in &files {
pb.tick();
let cache = if cache {
match tempfile::tempfile() {
Ok(f) => Some(f),
Err(e) => {
anyhow::bail!("Failed to create cache on disk - {}", e);
}
}
} else {
None
};
let scratch = hunter.hunt(file, &cache).with_context(|| {
format!("Failed to hunt through file '{}'", file.to_string_lossy())
})?;
hits += scratch.iter().map(|d| d.hits.len()).sum::<usize>();
documents += scratch.len();
if jsonl {
cli::print_jsonl(
&scratch,
hunter.hunts(),
hunter.rules(),
local,
timezone,
cache,
)?;
} else {
detections.extend(scratch);
}
pb.inc(1);
}
pb.finish();
if csv {
cli::print_csv(&detections, hunter.hunts(), hunter.rules(), local, timezone)?;
} else if json {
if output.is_some() {
cs_eprintln!("[+] Writing results to output file...");
}
cli::print_json(&detections, hunter.hunts(), hunter.rules(), local, timezone)?;
} else if jsonl {
// Work already done
} else if log {
cli::print_log(&detections, hunter.hunts(), hunter.rules(), local, timezone)?;
} else {
cli::print_detections(
&detections,
hunter.hunts(),
hunter.rules(),
column_width.unwrap_or(40),
full,
local,
metadata,
timezone,
);
}
cs_eprintln!("\n[+] {} Detections found on {} documents", hits, documents,);
}
Command::Lint { path, kind, tau } => {
init_writer(None, false, false, false)?;
if !args.no_banner {
print_title();
}
cs_eprintln!("[+] Validating as {} for supplied detection rules...", kind);
let mut count = 0;
let mut failed = 0;
for file in get_files(&path, &None, false)? {
match lint_rule(&kind, &file) {
Ok(filters) => {
if tau {
cs_eprintln!("[+] Rule {}:", file.to_string_lossy());
for filter in filters {
let yaml = match filter {
Filter::Detection(mut d) => {
d.expression = tau_engine::core::optimiser::coalesce(
d.expression,
&d.identifiers,
);
d.identifiers.clear();
d.expression =
tau_engine::core::optimiser::shake(d.expression);
d.expression =
tau_engine::core::optimiser::rewrite(d.expression);
d.expression =
tau_engine::core::optimiser::matrix(d.expression);
serde_yaml::to_string(&d)?
}
Filter::Expression(_) => {
cs_eyellowln!("[!] Tau does not support visual representation of expressions");
continue;
}
};
cs_println!("{}", yaml);
}
}
}
Err(e) => {
failed += 1;
let file_name = match file
.display()
.to_string()
.strip_prefix(&path.display().to_string())
{
Some(e) => e.to_string(),
None => file.display().to_string(),
};
cs_eprintln!("[!] {}: {}", file_name, e);
continue;
}
}
count += 1;
}
cs_eprintln!(
"[+] Validated {} detection rules out of {}",
count,
count + failed
);
}
Command::Search {
path,
mut pattern,
additional_pattern,
extension,
from,
ignore_case,
json,
jsonl,
load_unknown,
local,
output,
quiet,
skip_errors,
tau,
timestamp,
timezone,
to,
} => {
init_writer(output, false, json, quiet)?;
if !args.no_banner {
print_title();
}
let mut paths = if additional_pattern.is_some() || tau.is_some() {
let mut scratch = pattern
.take()
.map(|p| vec![PathBuf::from(p)])
.unwrap_or_default();
scratch.extend(path);
scratch
} else {
path
};
if paths.is_empty() {
paths.push(
std::env::current_dir().expect("could not get current working directory"),
);
}
let types = extension.as_ref().map(|e| HashSet::from_iter(e.clone()));
let mut files = vec![];
let mut size = ByteSize::mb(0);
for path in &paths {
let res = get_files(path, &types, skip_errors)?;
for i in &res {
size += i.metadata()?.len();
}
files.extend(res);
}
if let Some(ext) = &extension {
cs_eprintln!(
"[+] Loading forensic artefacts from: {} (extensions: {})",
paths
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", "),
ext.iter()
.map(|x| format!(".{}", x))
.collect::<Vec<_>>()
.join(", ")
)
} else {
cs_eprintln!(
"[+] Loading forensic artefacts from: {}",
paths
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", "),
)
};
if files.is_empty() {
return Err(anyhow::anyhow!(
"No forensic artefacts were found in the provided paths",
));
} else {
cs_eprintln!("[+] Loaded {} forensic files ({})", files.len(), size);
}
let mut searcher = Searcher::builder()
.ignore_case(ignore_case)
.load_unknown(load_unknown)
.local(local)
.skip_errors(skip_errors);
if let Some(patterns) = additional_pattern {
searcher = searcher.patterns(patterns);
} else if let Some(pattern) = pattern {
searcher = searcher.patterns(vec![pattern]);
}
if let Some(from) = from {
searcher = searcher.from(from);
}
if let Some(tau) = tau {
searcher = searcher.tau(tau);
}
if let Some(timestamp) = timestamp {
searcher = searcher.timestamp(timestamp);
}
if let Some(timezone) = timezone {
searcher = searcher.timezone(timezone);
}
if let Some(to) = to {
searcher = searcher.to(to);
}
let searcher = searcher.build()?;
cs_eprintln!("[+] Searching forensic artefacts...");
if json {
cs_print!("[");
}
let mut hits = 0;
for file in &files {
for res in searcher.search(file)?.iter() {
let hit = match res {
Ok(hit) => hit,
Err(e) => {
if skip_errors {
continue;
}
anyhow::bail!("Failed to search file... - {}", e);
}
};
if json {
if hits != 0 {
cs_print!(",");
}
cs_print_json!(&hit)?;
} else if jsonl {
cs_print_json!(&hit)?;
cs_println!();
} else {
cs_println!("---");
cs_print_yaml!(&hit)?;
}
hits += 1;
}
}
if json {
cs_println!("]");
}
cs_eprintln!("[+] Found {} hits", hits);
}
Command::Analyse { cmd } => {
match cmd {
AnalyseCommand::Shimcache {
additional_pattern,
amcache,
output,
regex_file,
shimcache,
ts_near_pair_matching,
} => {
if !args.no_banner {
print_title();
}
init_writer(output.clone(), true, false, false)?;
let shimcache_analyser = ShimcacheAnalyser::new(shimcache, amcache);
// Load regex
let mut regex_patterns: Vec<String> = Vec::new();
if let Some(regex_file) = regex_file {
let mut file_regex_patterns = BufReader::new(File::open(®ex_file)?)
.lines()
.collect::<Result<Vec<_>, _>>()?;
cs_eprintln!(
"[+] Regex file with {} pattern(s) loaded from {:?}",
file_regex_patterns.len(),
fs::canonicalize(®ex_file).expect("could not get absolute path")
);
regex_patterns.append(&mut file_regex_patterns);
}
if let Some(mut additional_patterns) = additional_pattern {
regex_patterns.append(&mut additional_patterns);
}
// Do analysis
let timeline = shimcache_analyser
.amcache_shimcache_timeline(®ex_patterns, ts_near_pair_matching)?;
cli::print_shimcache_analysis_csv(&timeline)?;
if let Some(output_path) = output {
cs_eprintln!(
"[+] Saved output to {:?}",
std::fs::canonicalize(output_path)
.expect("could not get absolute path")
);
}
}
AnalyseCommand::Srum {
srum_path,
software_hive_path,
stats_only,
quiet,
output,
} => {
init_writer(output.clone(), false, true, quiet)?;
if !args.no_banner {
print_title();
}
let srum_analyser = SrumAnalyser::new(srum_path, software_hive_path);
match srum_analyser.parse_srum_database() {
Ok(srum_db_info) => {
if stats_only {
cs_eprintln!(
"[+] Details about the tables related to the SRUM extensions:"
);
cs_println!(
"{}",