-
Notifications
You must be signed in to change notification settings - Fork 17
/
evtx.go
1060 lines (858 loc) · 24.7 KB
/
evtx.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 2018 Velocidex Innovations
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 evtx
import (
"bytes"
"encoding/binary"
"strings"
"time"
"fmt"
"io"
"os"
"unicode/utf16"
"github.com/Velocidex/ordereddict"
errors "github.com/pkg/errors"
)
const (
EVTX_HEADER_MAGIC = "ElfFile\x00"
EVTX_CHUNK_HEADER_MAGIC = "ElfChnk\x00"
EVTX_CHUNK_HEADER_SIZE = 0x200
EVTX_CHUNK_SIZE = 0x10000
EVTX_EVENT_RECORD_MAGIC = "\x2a\x2a\x00\x00"
EVTX_EVENT_RECORD_SIZE = 24
TemplateContext = true
)
type EvtxGUID struct {
D uint32
W1 uint16
W2 uint16
B [8]uint8
}
func (self *EvtxGUID) ToString() string {
return fmt.Sprintf(
"%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
self.D, self.W1, self.W2,
self.B[0], self.B[1], self.B[2], self.B[3],
self.B[4], self.B[5], self.B[6], self.B[7])
}
type EVTXHeader struct {
Magic [8]byte
Firstchunk uint64
LastChunk uint64
NextRecordID uint64
HeaderSize uint32
MinorVersion uint16
MajorVersion uint16
HeaderBlockSize uint16
_ [76]byte
FileFlags uint32
CheckSum uint32
}
type EventRecordHeader struct {
Magic [4]byte
Size uint32
RecordID uint64
FileTime uint64
}
type EventRecord struct {
Header EventRecordHeader
Event interface{}
}
func (self *EventRecord) Parse(ctx *ParseContext) {
template := ctx.NewTemplate(0)
ParseBinXML(ctx, !TemplateContext)
self.Event = template.Expand(nil)
}
func NewEventRecord(ctx *ParseContext, chunk *Chunk) (*EventRecord, error) {
self := &EventRecord{}
record_header := bytes.NewBuffer(ctx.ConsumeBytes(EVTX_EVENT_RECORD_SIZE))
err := binary.Read(record_header, binary.LittleEndian, &self.Header)
if err != nil {
return nil, errors.Wrap(err, "Read failed")
}
if string(self.Header.Magic[:]) != EVTX_EVENT_RECORD_MAGIC {
return nil, errors.New("Record does not have the right magic")
}
return self, nil
}
type ChunkHeader struct {
Magic [8]byte
FirstEventRecNumber uint64
LastEventRecNumber uint64
FirstEventRecID uint64
LastEventRecID uint64
HeaderSize uint32
}
type Chunk struct {
Header ChunkHeader
Offset int64
Fd io.ReadSeeker
}
func (self *Chunk) Parse(start_record_id int) ([]*EventRecord, error) {
result := []*EventRecord{}
buf := make([]byte, EVTX_CHUNK_SIZE)
_, err := self.Fd.Seek(self.Offset, os.SEEK_SET)
if err != nil {
return nil, errors.Wrap(err, "Seek")
}
_, err = io.ReadAtLeast(self.Fd, buf, EVTX_CHUNK_SIZE)
if err != nil {
return nil, errors.Wrap(err, "ReadAtLeast")
}
// The entire chunk is captured in this context.
ctx := NewParseContext(self)
ctx.buff = buf
ctx.offset = EVTX_CHUNK_HEADER_SIZE
for i := self.Header.FirstEventRecNumber; i <= self.Header.LastEventRecNumber; i++ {
start_of_record := ctx.Offset()
record, err := NewEventRecord(ctx, self)
if err != nil {
return result, nil
}
// We have to parse all the records in case they
// define templates we need.
record.Parse(ctx)
if int(record.Header.RecordID) >= start_record_id {
result = append(result, record)
}
if len(result) > 1024*10 {
return result, errors.New("Too many records in chunk")
}
ctx.SetOffset(start_of_record + int(record.Header.Size))
}
return result, nil
}
func NewChunk(fd io.ReadSeeker, offset int64) (*Chunk, error) {
self := &Chunk{Offset: offset, Fd: fd}
_, err := fd.Seek(offset, os.SEEK_SET)
if err != nil {
return nil, errors.Wrap(err, "Seek")
}
err = binary.Read(fd, binary.LittleEndian, &self.Header)
return self, errors.WithStack(err)
}
type TemplateNode struct {
Id uint32
Type uint32
Literal interface{}
NestedArray []*TemplateNode
NestedDict *ordereddict.Dict //map[string]*TemplateNode
CurrentKey string
}
func (self *TemplateNode) Expand(args map[int]interface{}) interface{} {
if self.NestedDict != nil {
result := ordereddict.NewDict()
for _, k := range self.NestedDict.Keys() {
v, _ := self.NestedDict.Get(k)
expanded := v.(*TemplateNode).Expand(args)
if k == "" {
k = "Value"
if self.NestedDict.Len() == 1 {
return expanded
}
expanded_dict, ok := expanded.(*ordereddict.Dict)
if ok {
for _, k := range expanded_dict.Keys() {
v, _ := expanded_dict.Get(k)
if v != nil {
result.Set(k, v)
}
}
continue
}
}
if expanded != nil {
result.Set(k, expanded)
}
}
return result
} else if self.Literal != nil {
return self.Literal
} else if self.NestedArray != nil {
result := []interface{}{}
for _, i := range self.NestedArray {
result = append(result, i.Expand(args))
}
return result
} else if args != nil {
value, pres := args[int(self.Id)]
if !pres {
return nil
}
return value
}
return nil
}
func (self *TemplateNode) SetLiteral(key string, literal interface{}) {
if self.NestedDict == nil {
self.NestedDict = ordereddict.NewDict() //make(map[string]*TemplateNode)
}
// Ignore useless xmlsn attributes.
if key != "xmlns" {
self.NestedDict.Set(key, &TemplateNode{Literal: literal})
}
}
func (self *TemplateNode) SetExpansion(key string, id, type_id uint32) {
if self.NestedDict == nil {
self.NestedDict = ordereddict.NewDict() //make(map[string]*TemplateNode)
}
self.NestedDict.Set(key, &TemplateNode{Id: id, Type: type_id})
}
func (self *TemplateNode) SetNested(key string, nested *TemplateNode) {
if self.NestedDict == nil {
self.NestedDict = ordereddict.NewDict() //make(map[string]*TemplateNode)
}
existing_any, pres := self.NestedDict.Get(key)
if pres {
existing := existing_any.(*TemplateNode)
// If there is already a nested value we append it.
if existing.NestedArray != nil {
if len(existing.NestedArray) < 1024*10 {
existing.NestedArray = append(existing.NestedArray, nested)
}
return
}
// Otherwise we convert the existing value to an array
// and append the new value on it.
nested = &TemplateNode{
NestedArray: []*TemplateNode{existing, nested},
}
}
self.NestedDict.Set(key, nested)
}
func NewTemplate(id int) *TemplateNode {
result := TemplateNode{}
return &result
}
type ParseContext struct {
buff []byte
offset int
root *TemplateNode
// XML Attributes are written to this template.
stack []*TemplateNode
// Remember the attribute we are currently parsing.
current_keys []string
attribute_mode bool
// A
chunk *Chunk
// A lookup table of templates we already saw in this
// chunk. Further events in the chunk will reuse the same
// templates by id.
knownIDs map[int]*TemplateNode
}
func (self *ParseContext) CurrentKey() string {
if !self.attribute_mode {
return ""
}
return self.CurrentTemplate().CurrentKey
}
func (self *ParseContext) Offset() int {
return self.offset
}
func (self *ParseContext) SetOffset(offset int) {
self.offset = offset
}
func (self *ParseContext) PushTemplate(key string, template *TemplateNode) {
debug("PushTemplate: %x -> %x\n", len(self.stack), len(self.stack)+1)
current := self.CurrentTemplate()
current.SetNested(key, template)
if len(self.stack) < 1024*10 {
self.stack = append(self.stack, template)
}
}
func (self *ParseContext) CurrentTemplate() *TemplateNode {
if len(self.stack) > 0 {
return self.stack[len(self.stack)-1]
}
return NewTemplate(0)
}
func (self *ParseContext) PopTemplate() {
if len(self.stack) > 0 {
debug("PopTemplate: %x -> %x\n", len(self.stack), len(self.stack)-1)
self.stack = self.stack[:len(self.stack)-1]
}
}
func NewParseContext(chunk *Chunk) *ParseContext {
template := NewTemplate(0)
result := ParseContext{
root: template,
stack: []*TemplateNode{template},
chunk: chunk,
knownIDs: make(map[int]*TemplateNode),
}
return &result
}
func (self *ParseContext) ConsumeUint8() uint8 {
if len(self.buff) < self.offset+1 {
return 0
}
result := self.buff[self.offset]
self.offset++
return result
}
func (self *ParseContext) ConsumeUint16() uint16 {
if len(self.buff) < self.offset+2 {
return 0
}
result := binary.LittleEndian.Uint16(self.buff[self.offset:])
self.offset += 2
return result
}
func (self *ParseContext) ConsumeUint32() uint32 {
if len(self.buff) < self.offset+4 {
return 0
}
result := binary.LittleEndian.Uint32(self.buff[self.offset:])
self.offset += 4
return result
}
func (self *ParseContext) ConsumeUint64() uint64 {
if len(self.buff) < self.offset+8 {
return 0
}
result := binary.LittleEndian.Uint64(self.buff[self.offset:])
self.offset += 8
return result
}
func (self *ParseContext) ConsumeBytes(size int) []byte {
if self.offset+size > len(self.buff) {
return make([]byte, size)
}
result := self.buff[self.offset : self.offset+size]
self.offset += size
return result
}
func (self *ParseContext) ConsumeInt64() (ret int64) {
if len(self.buff) < self.offset+8 {
return 0
}
buf := bytes.NewReader(self.buff[self.offset:])
err := binary.Read(buf, binary.LittleEndian, &ret)
if err != nil {
return 0
}
self.offset += 8
return
}
func (self *ParseContext) ConsumeInt32() (ret int32) {
if len(self.buff) < self.offset+4 {
return 0
}
buf := bytes.NewReader(self.buff[self.offset:])
err := binary.Read(buf, binary.LittleEndian, &ret)
if err != nil {
return 0
}
self.offset += 4
return
}
func (self *ParseContext) ConsumeReal32() (ret float32) {
if len(self.buff) < self.offset+4 {
return 0
}
buf := bytes.NewReader(self.buff[self.offset:])
err := binary.Read(buf, binary.LittleEndian, &ret)
if err != nil {
return 0
}
self.offset += 4
return
}
func (self *ParseContext) ConsumeReal64() (ret float64) {
if len(self.buff) < self.offset+8 {
return 0
}
buf := bytes.NewReader(self.buff[self.offset:])
err := binary.Read(buf, binary.LittleEndian, &ret)
if err != nil {
return 0
}
self.offset += 8
return
}
func (self *ParseContext) ConsumeSysTime(size int) string {
if len(self.buff) < self.offset+16 {
return "SysTimeParsingError"
}
buffer := self.buff[self.offset : self.offset+size]
self.offset += size
year := binary.LittleEndian.Uint16(buffer[0:2])
month := binary.LittleEndian.Uint16(buffer[2:4])
day := binary.LittleEndian.Uint16(buffer[6:8])
hour := binary.LittleEndian.Uint16(buffer[8:10])
min := binary.LittleEndian.Uint16(buffer[10:12])
sec := binary.LittleEndian.Uint16(buffer[12:14])
msec := binary.LittleEndian.Uint16(buffer[14:16])
result := time.Date(int(year), time.Month(month), int(day), int(hour), int(min), int(sec), int(msec), time.UTC)
return result.String()
}
func (self *ParseContext) ConsumeUnit16Array(size int) []uint16 {
uint16array := []uint16{}
if self.offset+size >= len(self.buff) {
size = len(self.buff) - self.offset - 1
}
if self.offset > len(self.buff) {
return nil
}
buffer := self.buff[self.offset : self.offset+size]
self.offset += size
index := 0
for index < len(buffer) {
value := binary.LittleEndian.Uint16((buffer[index:]))
uint16array = append(uint16array, value)
index += 2
}
return uint16array
}
func (self *ParseContext) ConsumeUnit64Array(size int) []uint64 {
uint64array := []uint64{}
if self.offset+size >= len(self.buff) {
size = len(self.buff) - self.offset - 1
}
if self.offset > len(self.buff) {
return nil
}
buffer := self.buff[self.offset : self.offset+size]
self.offset += size
index := 0
for index < len(buffer) {
value := binary.LittleEndian.Uint64((buffer[index:]))
uint64array = append(uint64array, value)
index += 8
}
return uint64array
}
func (self *ParseContext) ConsumeInt64hexArray(size int) []string {
if self.offset+size >= len(self.buff) {
size = len(self.buff) - self.offset - 1
}
if self.offset > len(self.buff) {
return nil
}
buffer := self.buff[self.offset : self.offset+size]
self.offset += size
result := []string{}
for i := 0; i < len(buffer); i = i + 8 {
var ret int64
buf := bytes.NewReader(buffer[i : i+8])
err := binary.Read(buf, binary.LittleEndian, &ret)
if err != nil {
return result
}
result = append(result, "0x"+fmt.Sprintf("%x", ret))
}
return result
}
func (self *ParseContext) SkipBytes(count int) {
self.offset += count
}
// Make a copy of the context. This new copy can be used to continue
// parsing without disturbing the state of this parser context.
func (self ParseContext) Copy() *ParseContext {
result := NewParseContext(self.chunk)
result.buff = self.buff
result.offset = self.offset
result.knownIDs = self.knownIDs
return result
}
func (self *ParseContext) NewTemplate(id int) *TemplateNode {
self.root = NewTemplate(id)
self.stack = []*TemplateNode{self.root}
if id != 0 {
self.knownIDs[id] = self.root
}
return self.root
}
func (self *ParseContext) GetTemplateByID(id int) (*TemplateNode, bool) {
template, pres := self.knownIDs[id]
return template, pres
}
func UTF16LEToUTF8(data []byte) []byte {
if len(data) == 0 || len(data)%2 == 1 {
return data
}
buff := make([]uint16, len(data)/2)
for i := range buff {
buff[i] = uint16(data[i*2]) + (uint16(data[i*2+1]) << 8)
}
for len(buff) > 0 && buff[len(buff)-1] == 0 {
buff = buff[:len(buff)-1]
}
return []byte(string(utf16.Decode(buff)))
}
func ReadPrefixedUnicodeString(ctx *ParseContext, is_null_terminated bool) string {
debug("ReadPrefixedUnicodeString Enter: %x\n", ctx.Offset())
count := int(ctx.ConsumeUint16())
if is_null_terminated {
count += 1
}
debug("ReadPrefixedUnicodeString count: %d\n", count)
buffer := ctx.ConsumeBytes(count * 2)
result := UTF16LEToUTF8(buffer)
debug("ReadPrefixedUnicodeString exit: %x %s\n", ctx.Offset(), string(result))
return string(result)
}
func ReadName(ctx *ParseContext) string {
debug("ReadName Enter: %x\n", ctx.Offset())
chunkOffset := int(ctx.ConsumeUint32())
debug("chunkOffset %x ctx offset %x\n", chunkOffset, ctx.Offset())
// Strings may be interned by reusing the location of the
// string elsewhere in the chunk.
if chunkOffset != ctx.Offset() {
temp_ctx := ctx.Copy()
temp_ctx.SetOffset(chunkOffset)
temp_ctx.SkipBytes(4 + 2)
return ReadPrefixedUnicodeString(temp_ctx, true)
}
ctx.SkipBytes(4 + 2)
return ReadPrefixedUnicodeString(ctx, true)
}
// This is called when we open a new XML Tag. e.g. "<EventData".
func ParseOpenStartElement(ctx *ParseContext,
has_attr bool, template_instance bool) bool {
debug("ParseOpenStartElement Enter: %x\n", ctx.Offset())
/*
dependencyID := ctx.ConsumeUint16()
elementLength := ctx.ConsumeUint32()
*/
// ctx.SkipBytes(2 + 4)
if template_instance {
ctx.SkipBytes(2)
}
ctx.SkipBytes(4)
nameBuffer := ReadName(ctx)
attributeListLength := uint32(0)
if has_attr {
attributeListLength = ctx.ConsumeUint32()
}
debug("Start element %v with %v attributes\n", nameBuffer, attributeListLength)
debug("ParseOpenStartElement Exit: %x\n", ctx.Offset())
new_template := NewTemplate(0)
ctx.PushTemplate(nameBuffer, new_template)
return true
}
// Represents a close of the start element ('>' in <Element>)
func ParseCloseStartElement(ctx *ParseContext) bool {
debug("ParseCloseStartElement %x\n", ctx.Offset())
ctx.attribute_mode = false
ctx.CurrentTemplate().CurrentKey = ""
return true
}
// Represents a closing element (i.e. </Element>)
func ParseCloseElement(ctx *ParseContext) bool {
debug("ParseCloseElement %x\n", ctx.Offset())
ctx.PopTemplate()
return true
}
func ParseValueText(ctx *ParseContext) bool {
debug("ParseValueText %x\n", ctx.Offset())
string_type := ctx.ConsumeUint8()
string_value := ReadPrefixedUnicodeString(ctx, false)
debug("ParseValueText Value is %v (type %v)\n",
string_value, string_type)
debug("Current Key %v\n", ctx.CurrentKey())
key := ctx.CurrentKey()
ctx.CurrentTemplate().SetLiteral(key, string_value)
ctx.attribute_mode = false
return true
}
func ParseAttributes(ctx *ParseContext) bool {
debug("ParseAttributes %x\n", ctx.Offset())
attribute := ReadName(ctx)
debug("Attribute is %v\n", attribute)
ctx.CurrentTemplate().CurrentKey = attribute
ctx.attribute_mode = true
return true
}
func ParseTemplateInstance(ctx *ParseContext) bool {
debug("ParseTemplateInstance Enter %x\n", ctx.Offset())
if ctx.ConsumeUint8() != 0x01 {
return false
}
short_id := int(ctx.ConsumeUint32())
if short_id == 0 {
return false
}
/*
tempResLen := ctx.ConsumeUint32()
*/
ctx.SkipBytes(4)
// Template arguments should not be unreasonable here. Just cap
// them at a reasonable size.
numArguments := ctx.ConsumeUint32()
if numArguments > 1024*10 {
numArguments = 10 * 1024
}
debug("template id %x\n", short_id)
template, pres := ctx.GetTemplateByID(short_id)
if !pres {
// longID := ctx.ConsumeBytes(16)
ctx.SkipBytes(16)
templateBodyLen := int(ctx.ConsumeUint32())
tmp_ctx := ctx.Copy()
template = tmp_ctx.NewTemplate(short_id)
ParseBinXML(tmp_ctx, TemplateContext)
ctx.SkipBytes(templateBodyLen)
numArguments = ctx.ConsumeUint32()
}
debug("ParseTemplateInstance Parse %x args @ %x\n", numArguments, ctx.Offset())
type arg_detail struct {
argLen int
argType uint16
}
args := []arg_detail{}
for i := 0; i < int(numArguments); i++ {
argLen := ctx.ConsumeUint16()
argType := ctx.ConsumeUint16()
args = append(args, arg_detail{int(argLen), argType})
}
arg_values := make(map[int]interface{})
for idx, arg := range args {
switch arg.argType {
case 0x00:
ctx.SkipBytes(arg.argLen)
case 0x01: // String
arg_values[idx] = string(UTF16LEToUTF8(ctx.ConsumeBytes(arg.argLen)))
case 0x04: // uint8_t
arg_values[idx] = ctx.ConsumeUint8()
case 0x06: // uint16_t
arg_values[idx] = ctx.ConsumeUint16()
case 0x07: //int32_t
arg_values[idx] = ctx.ConsumeInt32()
case 0x08: // uint32_t
arg_values[idx] = ctx.ConsumeUint32()
case 0x09:
arg_values[idx] = ctx.ConsumeInt64()
case 0x0A: // uint64_t
arg_values[idx] = ctx.ConsumeUint64()
case 0x0b: // real32_t
arg_values[idx] = ctx.ConsumeReal32()
case 0xc: //real64_t
arg_values[idx] = ctx.ConsumeReal64()
case 0x0d: // bool
value := false
switch arg.argLen {
case 8:
value = ctx.ConsumeUint64() > 0
case 4:
value = ctx.ConsumeUint32() > 0
case 2:
value = ctx.ConsumeUint16() > 0
case 1:
value = ctx.ConsumeUint8() > 0
}
arg_values[idx] = value
case 0xe: // binary
arg_values[idx] = ctx.ConsumeBytes(arg.argLen)
case 0x0f: // GUID
guid := EvtxGUID{}
readStructFromFile(
bytes.NewReader(ctx.ConsumeBytes(arg.argLen)), 0,
&guid)
arg_values[idx] = guid.ToString()
// We can always format this into hex if we
// need to. It is better to keep it as an int.
case 0x14: // HexInt32
// arg_values[idx] = fmt.Sprintf("%x", ctx.ConsumeUint32())
arg_values[idx] = ctx.ConsumeUint32()
case 0x15: // HexInt64
// arg_values[idx] = fmt.Sprintf("%x", ctx.ConsumeUint64())
arg_values[idx] = ctx.ConsumeUint64()
case 0x11: // FileTime - format as seconds since epoch.
arg_values[idx] = filetimeToUnixtime(ctx.ConsumeUint64())
case 0x12: //systime
arg_values[idx] = ctx.ConsumeSysTime(arg.argLen)
case 0x13: // SID
str := "S"
str += fmt.Sprintf("-%d", ctx.ConsumeUint8())
ctx.ConsumeUint8()
v_q := uint64(0)
for _, b := range ctx.ConsumeBytes(6) {
v_q = (v_q << 8) | uint64(b)
}
str += fmt.Sprintf("-%d", v_q)
for idx := 0; idx < arg.argLen-8; idx += 4 {
str += fmt.Sprintf("-%d", ctx.ConsumeUint32())
}
arg_values[idx] = str
case 0x21: // BinXml
new_ctx := ctx.Copy()
ParseBinXML(new_ctx, TemplateContext)
ctx.SkipBytes(arg.argLen)
arg_values[idx] = new_ctx.CurrentTemplate().Expand(nil)
case 0x27, 0x28:
arg_values[idx] = string(ctx.ConsumeBytes(arg.argLen))
case 0x81: // List of UTF16 String
arg_values[idx] = strings.Split(
string(UTF16LEToUTF8(ctx.ConsumeBytes(arg.argLen))),
"\x00")
case 0x86: // Array Of Uint16
arg_values[idx] = ctx.ConsumeUnit16Array(arg.argLen)
case 0x8a: // Array of Uint64
arg_values[idx] = ctx.ConsumeUnit64Array(arg.argLen)
case 0x95: // Array of 64-bit Integer Hex
arg_values[idx] = ctx.ConsumeInt64hexArray(arg.argLen)
default:
unknown := ctx.ConsumeBytes(arg.argLen)
debug("I dont know how to handle %v (%v)\n", arg, unknown)
arg_values[idx] = strings.TrimRight(string(unknown), "\x00")
}
debug("%v Arg type %x len %x - %v\n",
idx, arg.argType, arg.argLen, arg_values[idx])
}
debug("ParseTemplateInstance Exit %x\n", ctx.offset)
expanded := template.Expand(arg_values)
NormalizeEventData(expanded)
ctx.CurrentTemplate().SetLiteral(ctx.CurrentKey(), expanded)
return true
}
func ParseOptionalSubstitution(ctx *ParseContext) bool {
debug("ParseOptionalSubstitution Enter %x\n", ctx.Offset())
substitutionID := ctx.ConsumeUint16()
valueType := ctx.ConsumeUint8()
if valueType == 0 {
valueType = ctx.ConsumeUint8()
}
debug("CurrentKey %v\n", ctx.CurrentKey())
debug("ParseOptionalSubstitution Exit @%x %x (%x)\n",
ctx.Offset(), substitutionID, valueType)
key := ctx.CurrentKey()
ctx.CurrentTemplate().SetExpansion(key,
uint32(substitutionID), uint32(valueType))
return true
}
// When parsing the XML inside a template the elements has a slightly
// different structure.
// https://github.com/libyal/libevtx/blob/main/documentation/Windows%20XML%20Event%20Log%20(EVTX).asciidoc#414-element-start
func ParseBinXML(ctx *ParseContext, template_context bool) {
debug("ParseBinXML\n")
keep_going := true
for keep_going {
tag := ctx.ConsumeUint8()
debug("Tag %x @ %x\n", tag, ctx.Offset())
switch tag {
case 0x00 /* EOF */ :
keep_going = false
case 0x01 /* OpenStartElementToken */ :
keep_going = ParseOpenStartElement(ctx, false, template_context)
case 0x41:
keep_going = ParseOpenStartElement(ctx, true, template_context)
case 0x02: /* CloseStartElementToken */
keep_going = ParseCloseStartElement(ctx)
case 0x03 /* CloseEmptyElementToken */, 0x04: /* CloseElementToken */
keep_going = ParseCloseElement(ctx)
case 0x05 /* ValueTextToken */, 0x45:
keep_going = ParseValueText(ctx)
case 0x06 /* AttributeToken */, 0x46:
keep_going = ParseAttributes(ctx)
case 0x07 /* CDATASectionToken */, 0x47:
case 0x08 /* CharRefToken */, 0x48:
case 0x09 /* EntityRefToken */, 0x49:
case 0x0A /* PITargetToken */ :
case 0x0B /* PIDataToken */ :
case 0x0C /* TemplateInstanceToken */ :
keep_going = ParseTemplateInstance(ctx)
case 0x0D /* NormalSubstitutionToken */, 0x0E: /* OptionalSubstitutionToken */
keep_going = ParseOptionalSubstitution(ctx)
case 0x0F /* FragmentHeaderToken */ :
ctx.SkipBytes(3)
default:
keep_going = false
}
}
}
func is_supported(minor, major uint16) bool {
switch major {
case 3:
switch minor {
case 0, 1, 2:
return true
}
}
return false
}
// Get all the chunks in the file.
func GetChunks(fd io.ReadSeeker) ([]*Chunk, error) {
result := []*Chunk{}
header := EVTXHeader{}
err := readStructFromFile(fd, 0, &header)
if err != nil {
return nil, err
}
if string(header.Magic[:]) != EVTX_HEADER_MAGIC {
return nil, errors.New("File is not an EVTX file (wrong magic).")
}
if !is_supported(header.MinorVersion, header.MajorVersion) {
return nil, errors.New("Unsupported EVTX version.")
}
for offset := int64(header.HeaderBlockSize); true; offset += EVTX_CHUNK_SIZE {
chunk, err := NewChunk(fd, offset)
if err != nil {
if errors.Cause(err) == io.EOF {
break
}
continue
}
if string(chunk.Header.Magic[:]) != EVTX_CHUNK_HEADER_MAGIC ||
chunk.Header.LastEventRecID == 0xffffffffffffffff {
continue
}
result = append(result, chunk)
}