This repository was archived by the owner on Aug 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathmisc.go
2416 lines (2337 loc) · 81.9 KB
/
misc.go
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
// ==============================================================
// Copyright 2020 FireEye, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
// ==============================================================
package goauditparser
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"os/user"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"time"
)
func GetASCIIArt() string {
return `
______ ___ ___ __ ____
--111<xml>10____/___ / | __ ______/ (_) /_/ __ \____ ______________ _____
--10011<audit>1_/ __ \/ /| |/ / / / __ / / __/ /_/ / __ '/ ___/ ___/ _ \/ ___/
--110</audit>0/ / /_/ / ___ / /_/ / /_/ / / /_/ ____/ /_/ / / \__ / __/ /
--01101</xml>1011\____/_/ |_\____/\____/_/\__/_/ \__._/_/ \____/\___/_/
+------------------------------------------------------------------------------+
| A utility designed for FireEye Endpoint Security analysts to extract, parse, |
| and timeline XML audit data to CSV format quickly and efficiently. |
+------------------------------------------------------------------------------+
- Version ` + version + ` -
Copyright (C) 2020, FireEye, Inc.
`
}
func GetHelpExamples() string {
return `+=================================================================================+
| Example GoAuditParser Syntax |
+===================+=============================================================+
| Basic Parse | goauditparser -i <in_dir> -o <csv_dir> |
| Parse & Timeline | goauditparser -i <in_dir> -o <csv_dir> -tl |
| Extract Audits | goauditparser -i <in_dir> -eo <out_dir> |
| Extract File Acqs | goauditparser -i <in_dir> -efo <out_dir> -ep <password> |
| Raw Parse | goauditparser -i <in_dir> -o <csv_dir> -raw |
+-------------------+-------------------------------------------------------------+
`
}
func GetHelpMenu() string {
return `
===== [BASICS] =======================================================================================================
# GoAuditParser can perform multiple tasks, sometimes independent of other steps, but it usually follows this order:
# Name Description Automatic?
-- --------- -------------------------------------------------------- ---------------
1) EXTRACT Extract XML audits and other files from FireEye archives YES
2) SPLIT Split XML files that are too big into smaller files YES
3) PARSE Parse XML data to CSV YES
4) TIMELINE Timeline CSV data into an output file NO, needs '-tl'
===== [REQUIRED] ================================= ===== [NOTES] ====================================================
-i <str> Directory Input ! REQUIRED - (except when '-tlo' used)
Can provide multiple comma delimited paths:
Ex: -i "dir/xmldir1,xmldir2"
Works with .xml, .zip, or .mans files in the directory.
===== [EXTRACTING] =============================== ==================================================================
# Extract and rename files from triages packages (.mans), bulk data collections (.zip), and file acquisitions (.zip).
# The standardized naming scheme for XML files is as follows:
# <hostname>-<agentid>-<EXTRADATA>-<audittype>.xml
-o <str> CSV Directory Output ! ONE REQUIRED (1/2) - Parse XML to CSV. Defaults to "./parsed".
-eo <str> Extract Output Directory (Only) ! ONE REQUIRED (2/2) - Only extract and do not parse audits.
Archive files are automatically extracted to input directory
if this flag is not used.
-ep <str> Archive Password Provide a password for encrypted archives.
Required to extract from file acquisition archives.
-efo Extract File Acquisitions Only Extract acquired files from archives only, no XML audits.
Defaults '-eo' flag to "files" if not specified.
Does not parse audits if used.
-eff <int> Extract File Acquisition Format Change how filenames for acquired files are formatted.
1: <hostname>-<agentid>-<payloadid>-<fullfilepath>_ (default)
2: <hostname>-<agentid>-<payloadid>-<fullfilepath>
3: <fullfilepath>_
4: <fullfilepath>
5: <basefilename>_
6: <basefilename>
-exf <int> Extract XML Format Change how filenames for acquired files are formatted.
1: <hostname>-<agentid>-<payloadid>-<audittype>.xml (default)
2: <hostname>-<agentid>-0-<audittype>.xml
===== [SPLITTING] ================================ ==================================================================
# Split XML files. This step is automatically included if parsing.
-xso <str> XML Split Output Directory Only Split XML audits into chunks. Use with '-xsb <int>' if desired.
XML files are automatically split to "<inputdir>/xmlsplit/".
Does not parse audits if a different path is specified.
Appends "_spxml#" to payload of filename.
-xsb <int> XML Split Byte Size Default value is "300000000" (300 MB). Not required for '-xso'.
-ebs <str> Event Buffer Split Output Directory Split "eventbuffer" and "stateagentinspector" XML by event types.
Provide an output directory.
Does not parse audits if used.
===== [PARSING] ================================== ==================================================================
# Parse XML audit data to CSV format.
-o <str> CSV Directory Output -REQUIRED- Parse XML to CSV. Defaults to "./parsed".
-r Recursive Input Recursively dive into directories for parsing files.
-f Force Force any previously extracted, parsed, or timelined
files to be reprocessed.
-rn Replace New-Line Chars with '|' Useful when grepping through audits like event log messages.
-wo Wipe Output Directory Delete all files in output directory before parsing.
Also enables "-f" flag for parsing/timelining only.
-c <str> Configuration File Contains a static order of headers for parsed CSV files.
Defaults to "~/.MandiantTools/GoAuditParser/config.json".
-pcf <int> Parsed CSV Format Change how filenames for acquired files are formatted.
1: <hostname>-<agentid>-<EXTRADATA>-<audittype>.csv (default)
2: <hostname>-<agentid>-0-<audittype>.csv
-pah <str> Alternate Hostname Overwrite Hostname to provided string.
-paa <str> Alternate AgentID Overwrite AgentID to provided string.
===== [TIMELINING] =============================== ==================================================================
# Convert parsed CSV audit data in the output directory into a timeline.
# A static timeline configuration file ('-tlcf <str>') is required to tell GoAuditParser how to format the timeline.
-o <str> CSV Directory Output -REQUIRED- Parse XML to CSV. Defaults to "./parsed"
-tl Timeline -REQUIRED- Timeline files after parsed from XML to CSV.
-tlo Timeline Only (don't parse) Only perform timelining with specified CSV directory.
Needs output CSV directory specified with "-o <csv_dir>".
Does NOT need an input XML directory specified.
-tld Timeline Deduplicate Deduplicate timeline lines by entire row.
-tlout <str> Timeline Output Filepath Defaults to "<csv_dir>/_Timeline_<DATE>_<TIME>.csv".
-tlf <str> Timeline Filter Include only events which match the provided filter(s).
Time Filter formats:
"YYYY-MM-DD HH:MM:SS - YYYY-MM-DD HH:MM:SS"
"YYYY-MM-DD HH:MM:SS +-5m"
"YYYY-MM-DD - YYYY-MM-DD"
"YYYY-MM-DD +-5m"
Can provide multiple comma delimited filters:
Ex: -tlf "2019-01-01 - 2020-01-01,2015-01-01 +-3d"
-tlsod Output IIMS/SOD format Overwrites default timeline config to match IIMS/SOD format.
-tlcf <str> Timeline Config Filepath Defaults to "~/.MandiantTools/GoAuditParser/timeline.json".
===== [OTHER] ==================================== =================================================================
-c <str> Configuration File Defaults to "~/.MandiantTools/GoAuditParser/config.json".
-raw Disable Excel-Friendly Features Using this flag will disable the following Excel-Friendly features:
1. Truncating cells to 32k chars
2. Split CSV files by 1mil rows
Appends "_spcsv#" to payload of filename.
-t <int> Thread Count Defaults to number of existing CPUs.
-v[vvv] Verbose
-min Minimized Output Mode
--help Show this Help Menu
`
}
type Options struct {
InputPath string
ConfigPath string
Config Main_Config_JSON
OutputPath string
ReplaceNewLineFeeds bool
ForceReparse bool
ParseAltHostname string
ParseAltAgentID string
ExcelFriendly bool
MinimizedOutput bool
Threads int
Timeline bool
TimelineOutputFile string
TimelineOnly bool
TimelineSOD bool
TimelineFilter string
TimelineFilters [][]time.Time
TimelineFilterEmpty bool
TimelineConfigFile string
TimelineDeduplicate bool
EventBufferSplitDir string
WipeOutput bool
Help bool
AlternateParse bool
XMLSplitOutputDir string
XMLSplitByteSize int
RemoveNewlines string
ExtractionPassword string
ExtractionOutputDir string
ExtractFilesOnly bool
ExtractFileFormat int
ExtractXMLFormat int
ParseCSVFormat int
SubTaskFiles []os.FileInfo
Recursive bool
Verbose int
Box string
Warnbox string
ErrorDuringSetup bool
}
func Setup() Options {
flag.Usage = func() {
fmt.Println(GetASCIIArt())
fmt.Println(GetHelpExamples())
fmt.Println(GetHelpMenu())
}
var v1 bool
var v2 bool
var v3 bool
var v4 bool
var raw bool
options := Options{}
flag.StringVar(&options.InputPath, "i", "", "")
flag.StringVar(&options.ConfigPath, "c", "", "")
flag.StringVar(&options.OutputPath, "o", "parsed", "")
flag.BoolVar(&options.ReplaceNewLineFeeds, "rn", false, "")
flag.BoolVar(&options.ForceReparse, "f", false, "")
flag.BoolVar(&raw, "raw", false, "")
flag.BoolVar(&options.MinimizedOutput, "min", false, "")
flag.IntVar(&options.Threads, "t", -1, "")
flag.BoolVar(&options.Timeline, "tl", false, "")
flag.BoolVar(&options.TimelineDeduplicate, "tld", false, "")
flag.BoolVar(&options.TimelineSOD, "tlsod", false, "")
flag.BoolVar(&options.TimelineOnly, "tlo", false, "")
flag.StringVar(&options.TimelineOutputFile, "tlout", "", "")
flag.StringVar(&options.TimelineFilter, "tlf", "", "")
flag.StringVar(&options.TimelineConfigFile, "tlcf", "", "")
flag.StringVar(&options.EventBufferSplitDir, "ebs", "", "")
flag.BoolVar(&options.WipeOutput, "wo", false, "")
flag.StringVar(&options.XMLSplitOutputDir, "xso", "", "")
flag.StringVar(&options.ExtractionOutputDir, "eo", "", "")
flag.BoolVar(&options.ExtractFilesOnly, "efo", false, "")
flag.StringVar(&options.ExtractionPassword, "ep", "", "")
flag.IntVar(&options.ExtractFileFormat, "eff", 1, "")
flag.IntVar(&options.ExtractXMLFormat, "exf", 1, "")
flag.IntVar(&options.ParseCSVFormat, "pcf", 1, "")
flag.IntVar(&options.XMLSplitByteSize, "xsb", 300000000, "")
flag.StringVar(&options.ParseAltHostname, "pah", "", "")
flag.StringVar(&options.ParseAltAgentID, "paa", "", "")
flag.BoolVar(&options.Recursive, "r", false, "")
flag.BoolVar(&v1, "v", false, "")
flag.BoolVar(&v2, "vv", false, "")
flag.BoolVar(&v3, "vvv", false, "")
flag.BoolVar(&v4, "vvvv", false, "")
flag.Parse()
//Update some flags based on other flags
options.Verbose = 0
if v1 {
options.Verbose = 1
}
if v2 {
options.Verbose = 2
}
if v3 {
options.Verbose = 3
}
if v4 {
options.Verbose = 4
}
options.ExcelFriendly = !raw
if options.ExtractFilesOnly && options.ExtractionOutputDir == "" {
options.ExtractionOutputDir = "files"
}
if options.ExtractFileFormat <= 0 || options.ExtractFileFormat >= 7 {
options.ExtractFileFormat = 1
}
if options.ExtractXMLFormat <= 0 || options.ExtractXMLFormat >= 3 {
options.ExtractXMLFormat = 1
}
if options.ParseCSVFormat <= 0 || options.ParseCSVFormat >= 3 {
options.ParseCSVFormat = 1
}
if options.TimelineSOD {
options.Timeline = true
}
options.Box = "[+] "
options.Warnbox = "[!] "
if options.MinimizedOutput {
options.Box = "[#] "
}
if !options.MinimizedOutput {
fmt.Println(GetASCIIArt())
} else {
fmt.Println(options.Box + "- GoAuditParser v" + version + " -")
fmt.Println(options.Box + "Copyright (C) 2020, FireEye, Inc.")
}
//Parse time filter
options.TimelineFilterEmpty = false
//options.TimelineFilters = [][]time.Time{}
timeParse1 := regexp.MustCompile(`^ *(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d) *- *(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d) *$`)
timeParse2 := regexp.MustCompile(`^ *(\d\d\d\d-\d\d-\d\d) *- *(\d\d\d\d-\d\d-\d\d) *$`)
timeParse3 := regexp.MustCompile(`^ *(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d) *(\+-|\+|\-) *(\d+) *([smhdy]) *$`)
timeParse4 := regexp.MustCompile(`^ *(\d\d\d\d-\d\d-\d\d) *(\+-|\+|\-) *(\d+) *([smhdy]) *$`)
if options.TimelineFilter == "" {
options.TimelineFilterEmpty = true
} else {
timeStart := time.Time{}
timeEnd := time.Time{}
for _, timelineFilter := range strings.Split(options.TimelineFilter, ",") {
// "DATE1 - DATE2"
if timeParse1.MatchString(timelineFilter) || timeParse2.MatchString(timelineFilter) {
if timeParse1.MatchString(timelineFilter) {
matches := timeParse1.FindStringSubmatch(timelineFilter)
t1, err_t1 := time.Parse("2006-01-02 15:04:05", matches[1])
if err_t1 != nil {
fmt.Println(options.Warnbox + "Could not parse '" + matches[1] + "' in format 'yyyy-mm-dd hh:mm:ss'.")
log.Fatal(err_t1)
}
t2, err_t2 := time.Parse("2006-01-02 15:04:05", matches[2])
if err_t2 != nil {
fmt.Println(options.Warnbox + "Could not parse '" + matches[2] + "' in format 'yyyy-mm-dd hh:mm:ss'.")
log.Fatal(err_t2)
}
timeStart = t1
timeEnd = t2
} else {
matches := timeParse2.FindStringSubmatch(timelineFilter)
t1, err_t1 := time.Parse("2006-01-02", matches[1])
if err_t1 != nil {
fmt.Println(options.Warnbox + "Could not parse '" + matches[1] + "' in format 'yyyy-mm-dd'.")
log.Fatal(err_t1)
}
t2, err_t2 := time.Parse("2006-01-02", matches[2])
t2 = t2.Add(time.Hour*23 + time.Minute*59 + time.Minute*59)
if err_t2 != nil {
fmt.Println(options.Warnbox + "Could not parse '" + matches[2] + "' in format 'yyyy-mm-dd'.")
log.Fatal(err_t2)
}
timeStart = t1
timeEnd = t2
}
// "DATE +-5m"
} else if timeParse3.MatchString(timelineFilter) || timeParse4.MatchString(timelineFilter) {
var t time.Time
var matches []string
if timeParse3.MatchString(timelineFilter) {
matches = timeParse3.FindStringSubmatch(timelineFilter)
t1, err_t1 := time.Parse("2006-01-02 15:04:05", matches[1])
if err_t1 != nil {
fmt.Println(options.Warnbox + "Could not parse '" + matches[1] + "' in format 'yyyy-mm-dd hh:mm:ss'.")
log.Fatal(err_t1)
}
t = t1
} else {
matches = timeParse4.FindStringSubmatch(timelineFilter)
t1, err_t1 := time.Parse("2006-01-02", matches[1])
if err_t1 != nil {
fmt.Println(options.Warnbox + "Could not parse '" + matches[1] + "' in format 'yyyy-mm-dd'.")
log.Fatal(err_t1)
}
t = t1
}
durNum, err_i := strconv.Atoi(matches[3])
if err_i != nil {
fmt.Println(options.Warnbox + "Could not convert '" + matches[3] + "' to an integer.")
log.Fatal(err_i)
}
durName := matches[4]
durVal := time.Second * 0
if durName == "s" {
durVal = time.Duration(durNum) * time.Second
} else if durName == "m" {
durVal = time.Duration(durNum) * time.Minute
} else if durName == "h" {
durVal = time.Duration(durNum) * time.Hour
} else if durName == "d" {
durVal = time.Duration(durNum*24) * time.Hour
}
operation := matches[2]
if operation == "+-" {
timeStart = t.Add(-durVal)
timeEnd = t.Add(durVal)
} else if operation == "+" {
timeStart = t
timeEnd = t.Add(durVal)
} else if operation == "-" {
timeStart = t.Add(-durVal)
timeEnd = t
}
} else {
fmt.Println(options.Warnbox + "ERROR - Could not parse provided timeline filter '" + timelineFilter + "'.")
fmt.Println(options.Warnbox + "Formats: 'YYYY-MM-DD HH:MM:SS - YYYY-MM-DD HH:MM:SS' OR 'YYYY-MM-DD HH:MM:SS +-5m'")
options.ErrorDuringSetup = true
return options
}
options.TimelineFilters = append(options.TimelineFilters, []time.Time{timeStart, timeEnd})
}
}
//Create config directory
dataDir := GetDataDir(options)
if options.TimelineConfigFile == "" {
options.TimelineConfigFile = filepath.Join(dataDir, "timeline.json")
}
//Check for JSON Config File
if options.ConfigPath == "" {
options.ConfigPath = filepath.Join(dataDir, "config.json")
}
if options.Verbose > 0 {
fmt.Println(options.Box + "Reading main config file '" + options.ConfigPath + "'...")
}
_, err_s := os.Stat(options.ConfigPath)
//If config file exists, create the file
if os.IsNotExist(err_s) {
//Create config file
fmt.Println(options.Warnbox + "NOTICE - Main config file '" + options.ConfigPath + "' does not exist. Creating...")
file, err_c := os.Create(options.ConfigPath)
if err_c != nil {
fmt.Println(options.Box + "ERROR - Could not create main config file '" + options.ConfigPath + "'.")
log.Fatal(err_c)
}
var newconfig Main_Config_JSON
err_j := json.Unmarshal([]byte(GetMainConfigTemplate(options)), &newconfig)
if err_j != nil {
if options.Verbose > 2 {
fmt.Println(GetMainConfigTemplate(options))
}
fmt.Println(options.Warnbox + "ERROR - Could not parse pre-made JSON for main config file. Please contact the developer.")
log.Fatal(err_j)
}
file.WriteString(GetMainConfigTemplate(options))
file.Close()
}
//Read JSON from config file
file, err_o := os.Open(options.ConfigPath)
if err_o != nil {
fmt.Println(options.Warnbox + "ERROR - Could not open main config file '" + options.ConfigPath + "'.")
log.Fatal(err_o)
}
b, err_i := ioutil.ReadAll(file)
if err_i != nil {
fmt.Println(options.Warnbox + "ERROR - Could not read contents from main config '" + options.ConfigPath + "'.")
log.Fatal(err_i)
}
var config Main_Config_JSON
err_j := json.Unmarshal(b, &config)
file.Close()
if err_j != nil {
fmt.Println(options.Warnbox + "ERROR - Could not parse JSON from main config file '" + options.ConfigPath + "': " + err_j.Error())
reader := bufio.NewReader(os.Stdin)
fmt.Println(options.Box + "Would you like to overwrite the previous main config file with a new one? [Y/N]")
fmt.Print("> ")
text, _ := reader.ReadString('\n')
if strings.HasPrefix(strings.TrimSpace(strings.ToLower(text)), "y") {
file, err_c := os.Create(options.ConfigPath)
if err_c != nil {
fmt.Println(options.Box + "ERROR - Could not create main config file '" + options.ConfigPath + "'.")
log.Fatal(err_c)
}
var newconfig Main_Config_JSON
err_j := json.Unmarshal([]byte(GetMainConfigTemplate(options)), &newconfig)
if err_j != nil {
if options.Verbose > 2 {
fmt.Println(GetMainConfigTemplate(options))
}
fmt.Println(options.Warnbox + "ERROR - Could not parse pre-made JSON for main config file. Please contact the developer.")
log.Fatal(err_j)
}
file.WriteString(GetMainConfigTemplate(options))
file.Close()
} else {
fmt.Println(options.Warnbox + "Please fix the main config file manually.")
options.ErrorDuringSetup = true
return options
}
}
//Check for new version
updateConig := false
if config.Version != version {
if !config.DontOverwrite {
fmt.Println(options.Box + "Updating old config v" + config.Version + " to v" + version + "...")
//Update config
updateConig = true
var newconfig Main_Config_JSON
err_j := json.Unmarshal([]byte(GetMainConfigTemplate(options)), &newconfig)
if err_j != nil {
fmt.Println(options.Warnbox + "ERROR - Could not parse pre-made JSON for main config file. Please contact the developer.")
log.Fatal(err_j)
}
//Keep some old settings
newconfig.OmitUnlisted = config.OmitUnlisted
if !strings.HasPrefix(config.Version, "0.") {
newconfig.AutoSplitFiles = config.AutoSplitFiles
newconfig.AutoExtract = config.AutoExtract
}
config = newconfig
} else {
fmt.Println(options.Warnbox + "NOTICE - New main config file version is available, but the JSON property 'Dont_Overwrite_With_New_Update' is set to 'true'.")
time.Sleep(time.Second * 1)
}
}
//Update the main config file
if updateConig {
fmt.Println(options.Box + "Updating config file...")
//Write new JSON to timeline file
newFile, err_c := os.Create(options.ConfigPath)
config.Version = version
if err_c != nil {
fmt.Println(options.Warnbox + "ERROR - Could not create new version of main config file '" + options.ConfigPath + "'")
log.Fatal(err_c)
}
b, _ := json.MarshalIndent(config, "", " ")
newFile.Write(b)
newFile.Close()
}
options.Config = config
//Set thread count
if options.Threads <= 0 {
options.Threads = runtime.NumCPU()
}
if options.Verbose > 2 {
fmt.Println(options.Warnbox + "NOTICE - Verbosity set to DEBUG state. Multi-threading is disabled.")
options.Threads = 1
}
return options
}
func GetDataDir(options Options) string {
var dirName = filepath.Join(".MandiantTools", "GoAuditParser")
var dataPath = ""
usr, u_err := user.Current()
if u_err != nil {
log.Fatal(options.Box + "ERROR - Could not identify user.")
}
dataPath = filepath.Join(usr.HomeDir, dirName)
//Create directory if necessary
if _, s_err := os.Stat(dataPath); os.IsNotExist(s_err) {
d_err := os.MkdirAll(dataPath, os.ModePerm)
if d_err != nil {
log.Fatal(options.Box + "ERROR - Could not create data directory '" + dataPath + "'.")
}
}
return dataPath
}
type Main_Config_JSON struct {
Version string `json:"Version"`
DontOverwrite bool `json:"Dont_Overwrite_With_New_Update"`
AutoSplitFiles bool `json:"Automatically_Split_Big_XML"`
AutoExtract bool `json:"Automatically_Extract_Archives"`
OmitUnlisted bool `json:"Omit_Nonordered_Headers"`
HeadersMandatory []string `json:"Mandatory_Headers"`
HeadersOptional []string `json:"Optional_Headers"`
AuditHeaderConfigs []struct {
Name string `json:"Name"`
ItemName string `json:"Item_Name"`
HeaderOrder []string `json:"Header_Order"`
HeadersOmitted []string `json:"Headers_Omitted"`
} `json:"Audit_Header_Configs"`
}
func GetMainConfigTemplate(options Options) string {
template_head := `{
"Version": "` + version + `",
"Dont_Overwrite_With_New_Update": false,
"Automatically_Split_Big_XML": true,
"Automatically_Extract_Archives": true,
"Omit_Nonordered_Headers": false,
"Mandatory_Headers": [
"Tag",
"Notes",
"Hostname",
"AgentID"
],
"Optional_Headers": [
"Audit UID",
"UID",
"Sequence Number",
"FireEyeGeneratedTime",
"EventBufferType"
],
"Audit_Header_Configs": [
`
template_audits := ` {
"Name": "AgentInfo",
"Item_Name": "AgentInfo",
"Header_Order": [],
"Headers_Omitted": []
},{
"Name": "ArpEntryItem",
"Item_Name": "ArpEntryItem",
"Header_Order": [
"Interface",
"InterfaceType",
"PhysicalAddress",
"IPv4Address",
"IPv6Address",
"IsRouter",
"LastReachable",
"LastUnreachable",
"CacheType",
"State"
],
"Headers_Omitted": []
},
{
"Name": "CookieHistoryItem",
"Item_Name": "CookieHistoryItem",
"Header_Order": [
"FileName",
"FilePath",
"CookiePath",
"CookieName",
"CookieValue",
"HostName",
"ExpirationDate",
"CreationDate",
"LastAccessedDate",
"LastModifiedDate",
"Username",
"Profile",
"BrowserName",
"BrowserVersion",
"IsSecure",
"IsHttpOnly"
],
"Headers_Omitted": []
},
{
"Name": "DiskItem",
"Item_Name": "DiskItem",
"Header_Order": [
"DiskName",
"DiskSize",
"PartitionList.Partition.PartitionNumber",
"PartitionList.Partition.PartitionOffset",
"PartitionList.Partition.PartitionLength",
"PartitionList.Partition.PartitionType"
],
"Headers_Omitted": []
},
{
"Name": "DnsEntryItem",
"Item_Name": "DnsEntryItem",
"Header_Order": [
"Host",
"RecordName",
"RecordType",
"TimeToLive",
"Flags",
"DataLength",
"RecordData"
],
"Headers_Omitted": []
},
{
"Name": "DriverItem",
"Item_Name": "DriverItem",
"Header_Order": [
"DriverName",
"DriverInit",
"DriverStartIo",
"DriverUnload",
"DeviceName",
"DriverObjectAddress",
"ImageBase",
"ImageSize",
"Md5sum",
"SignatureExists",
"SignatureVerified",
"SignatureDescription",
"CertificateIssuer"
],
"Headers_Omitted": []
},
{
"Name": "EventItem_DnsLookupEvent",
"Item_Name": "EventItem_DnsLookupEvent",
"Header_Order": [
"EventBufferTime_DnsLookupEvent",
"ProcessPath",
"Process",
"DNSHostname",
"Pid"
],
"Headers_Omitted": []
},
{
"Name": "EventItem_FileWriteEvent",
"Item_Name": "EventItem_FileWriteEvent",
"Header_Order": [
"EventBufferTime_FileWriteEvent",
"ProcessPath",
"Process",
"FullPath",
"DevicePath",
"Md5",
"Pid",
"Closed",
"Writes",
"Size",
"NumBytesSeenWritten",
"LowestFileOffsetSeen",
"TextAtLowestOffset"
],
"Headers_Omitted": []
},
{
"Name": "EventItem_ImageLoadEvent",
"Item_Name": "EventItem_ImageLoadEvent",
"Header_Order": [
"EventBufferTime_ImageLoadEvent",
"ProcessPath",
"Process",
"FullPath",
"DevicePath",
"Pid"
],
"Headers_Omitted": []
},
{
"Name": "EventItem_Ipv4NetworkEvent",
"Item_Name": "EventItem_Ipv4NetworkEvent",
"Header_Order": [
"EventBufferTime_Ipv4NetworkEvent",
"ProcessPath",
"Process",
"LocalIP",
"LocalPort",
"RemoteIP",
"RemotePort",
"Protocol",
"Pid"
],
"Headers_Omitted": []
},
{
"Name": "EventItem_ProcessEvent",
"Item_Name": "EventItem_ProcessEvent",
"Header_Order": [
"EventBufferTime_ProcessEvent",
"ProcessPath",
"Process",
"ProcessCmdLine",
"Md5",
"ParentProcessPath",
"ParentProcess",
"EventType",
"Pid",
"ParentPid",
"StartTime"
],
"Headers_Omitted": []
},
{
"Name": "EventItem_RegKeyEvent",
"Item_Name": "EventItem_RegKeyEvent",
"Header_Order": [
"EventBufferTime_RegKeyEvent",
"ProcessPath",
"Process",
"Path",
"ValueName",
"Text",
"ValueType",
"EventType",
"Pid"
],
"Headers_Omitted": []
},
{
"Name": "EventItem_UrlMonitorEvent",
"Item_Name": "EventItem_UrlMonitorEvent",
"Header_Order": [
"EventBufferTime_UrlMonitorEvent",
"ProcessPath",
"Process",
"DNSHostname",
"RequestUrl",
"RemoteIpAddress",
"Text",
"LocalPort",
"RemotePort",
"UrlMethod",
"UserAgent",
"Pid"
],
"Headers_Omitted": []
},
{
"Name": "EventLogItem",
"Item_Name": "EventLogItem",
"Header_Order": [
"genTime",
"writeTime",
"log",
"source",
"EID",
"type",
"message",
"user",
"index",
"machine",
"category",
"CorrelationActivityId",
"CorrelationRelatedActivityId",
"ExecutionProcessId",
"ExecutionThreadId"
],
"Headers_Omitted": []
},
{
"Name": "FileDownloadHistoryItem",
"Item_Name": "FileDownloadHistoryItem",
"Header_Order": [
"Profile",
"BrowserName",
"BrowserVersion",
"Username",
"DownloadType",
"SourceURL",
"TargetDirectory",
"StartDate",
"EndDate",
"LastCheckedDate",
"LastAccessedDate",
"LastModifiedDate",
"BytesDownloaded",
"MaxBytes"
],
"Headers_Omitted": []
},
{
"Name": "FileItem",
"Item_Name": "FileItem",
"Header_Order": [
"FullPath",
"Created",
"Modified",
"Accessed",
"Changed",
"FilenameCreated",
"FilenameModified",
"FilenameAccessed",
"FilenameChanged",
"SizeInBytes",
"Md5sum",
"Username",
"FileAttributes",
"INode",
"SecurityID",
"SecurityType",
"DevicePath",
"Drive",
"FilePath",
"FileName",
"FileExtension"
],
"Headers_Omitted": []
},
{
"Name": "FormHistoryItem",
"Item_Name": "FormHistoryItem",
"Header_Order": [
"Username",
"Profile",
"BrowserName",
"BrowserVersion",
"FormType",
"FormFieldName",
"FormFieldValue",
"TimesUsed",
"FirstUsedDate",
"LastUsedDate",
"Guid"
],
"Headers_Omitted": []
},
{
"Name": "GroupItem",
"Item_Name": "GroupItem",
"Header_Order": [
"GroupName",
"fullname",
"groupguid",
"userlist.username",
"gid"
],
"Headers_Omitted": []
},
{
"Name": "HiveItem",
"Item_Name": "HiveItem",
"Header_Order": [
"Name",
"Path"
],
"Headers_Omitted": []
},
{
"Name": "HookItem",
"Item_Name": "HookItem",
"Header_Order": [
"HookDescription",
"HookedFunction",
"HookedModule",
"HookingModule",
"HookingAddress",
"DigitalSignatureHooking",
"DigitalSignatureHooked"
],
"Headers_Omitted": []
},
{
"Name": "LoginHistoryItem",
"Item_Name": "LoginHistoryItem",
"Header_Order": [
"Path",
"StartTime",
"EndTime",
"SessionLength",
"Hostname",
"IsRemoteLogin",
"IPv4Address",
"IPv6Address",
"Username",
"RecordType",
"PID",
"Terminal",
"IsFailedLogin"
],
"Headers_Omitted": []
},
{
"Name": "ModuleItem",
"Item_Name": "ModuleItem",
"Header_Order": [
"ModuleAddress",
"ModuleInit",
"ModuleBase",
"ModuleSize",
"ModulePath",
"ModuleName"
],
"Headers_Omitted": []
},
{
"Name": "PersistenceItem",
"Item_Name": "PersistenceItem",
"Header_Order": [
"PersistenceType",
"status",
"serviceDLLCertificateIssuer",
"md5sum",
"TaskFileName",
"SignatureVerified",
"RegistryItem",
"pathSignatureDescription",
"mode",
"CertificateIssuer",
"serviceDLLCertificateSubject",
"RegOwner",
"MagicHeader",
"detectedAnomaly",
"Scheduled",
"FileModified",
"pathSignatureVerified",
"serviceDLL",
"FileCreated",
"arguments",
"ServiceItem",