forked from Sysinternals/SysmonCommon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xml.cpp
2192 lines (1731 loc) · 55.1 KB
/
xml.cpp
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
/*
SysmonCommon
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//====================================================================
//
// Xml.cpp
//
// Handle XML parsing, validation and registry writing for
// configuration files
//
//====================================================================
#include "stdafx.h"
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>
#if defined _WIN64 || defined _WIN32
#include <atlbase.h>
#endif
#include <string>
#include "sysmonevents.h"
#include "xml.h"
#include "rules.h"
#if defined _WIN64 || defined _WIN32
#define ALIGN_DOWN_BY(length, alignment) \
((ULONG_PTR)(length) & ~(alignment - 1))
#define ALIGN_UP_BY(length, alignment) \
(ALIGN_DOWN_BY(((ULONG_PTR)(length) + alignment - 1), alignment))
#elif defined __linux__
#define ALIGN_DOWN_BY(length, alignment) \
((uint64_t)(length) & ~((uint64_t)alignment - 1))
#define ALIGN_UP_BY(length, alignment) \
(ALIGN_DOWN_BY(((uint64_t)(length) + alignment - 1), (uint64_t)alignment))
#endif
//--------------------------------------------------------------------
//
// ParseVersionString
//
// Parse the version string to a ULONG
//
//--------------------------------------------------------------------
ULONG
ParseVersionString(
_In_ PCHAR version
)
{
double dblVersion;
char tmp[40];
ULONG acc, cur, ret;
PCHAR pos;
//
// Normalize the version number
//
dblVersion = std::stod( version );
snprintf( tmp, _countof( tmp ), "%.2f", dblVersion );
acc = ret = 0;
for( pos = tmp; *pos != 0; pos++ ) {
if( *pos == '.' ) {
if( ret != 0 ) {
return (ULONG)-1;
}
ret = (acc << 16);
acc = 0;
// Starts at 1.0
if( ret == 0 ) {
break;
}
} else {
if( *pos < '0' || *pos > '9' ) {
return (ULONG)-1;
}
cur = (ULONG)(*pos - '0');
if( cur == 0 && acc == 0 && ret == 0 ) {
return (ULONG)-1;
}
acc = (acc * 10) + cur;
if( acc > 0xFFFF ) {
return (ULONG)-1;
}
}
}
ret |= acc;
//
// No seperation
//
if( ret < 0xFFFF ) {
ret <<= 16;
}
if( ret == 0 ) {
return (ULONG)-1;
}
return ret;
}
//
// Class to build the rule blob while ensuring offsets are correctly updated.
//
class RuleBuilder
{
private:
PVOID blob;
ULONG blobSize;
ULONG blobAllocated;
ULONG blobVersion;
ULONG schemaVersion;
const ULONG steps = 0x1000;
ULONG lastEventOffset; // Used to chain events
ULONG lastFilterOffset; // Used to chain filters
ULONG prevBlobSize;
ULONG prevLastEventOffset;
ULONG prevLastFilterOffset;
ULONG aggregationOffset; // Used to track the current aggregation when adding filters..
//
// Grow the blob buffer
//
HRESULT
Grow(
_In_ ULONG Bytes
)
{
ULONG remain = (blobAllocated - blobSize);
if( Bytes == 0 || Bytes <= remain ) {
return S_OK;
}
ULONG toAlloc = Bytes > steps ? Bytes : steps;
toAlloc += blobAllocated;
if( toAlloc < blobAllocated ) {
return E_OUTOFMEMORY;
}
PVOID newAlloc = NULL;
if( blob == NULL ) {
newAlloc = malloc( toAlloc );
} else {
newAlloc = realloc( blob, toAlloc );
}
if( newAlloc == NULL ) {
return E_OUTOFMEMORY;
}
if( blob == NULL ) {
ZeroMemory( newAlloc, toAlloc );
} else {
ZeroMemory( (PBYTE)newAlloc + blobSize, toAlloc - blobSize );
}
blob = newAlloc;
blobAllocated = toAlloc;
return S_OK;
}
//
// Append data to the blob
//
HRESULT
AddData(
_In_ PVOID Ptr,
_In_ ULONG Size
)
{
ULONG alignSize = ALIGN_UP_BY( Size, sizeof(ULONG64) );
if( alignSize < Size ) {
return E_OUTOFMEMORY;
}
HRESULT hr = Grow( alignSize );
if( FAILED( hr ) ) {
return hr;
}
memcpy( (PBYTE)blob + blobSize, Ptr, Size );
blobSize += alignSize;
return S_OK;
}
public:
RuleBuilder(
VOID
)
{
blob = NULL;
blobSize = 0;
blobAllocated = 0;
blobVersion = BinaryVersion;
schemaVersion = ConfigurationVersion;
lastEventOffset = 0;
lastFilterOffset = 0;
prevBlobSize = 0;
prevLastEventOffset = UINT_MAX;
prevLastFilterOffset = UINT_MAX;
aggregationOffset = 0;
}
VOID
SetVersion(
_In_ ULONG Version
)
{
schemaVersion = Version;
}
~RuleBuilder(
VOID
)
{
if( blob != NULL ) {
free( blob );
}
}
//
// Get the blob data and size
//
VOID
Detach(
_Out_ PVOID* Rules,
_Out_ PULONG RulesSize
)
{
*Rules = blob;
*RulesSize = blobSize;
blob = NULL;
blobSize = 0;
blobAllocated = 0;
}
//
// Add a base event entry
//
HRESULT
AddEventEntry(
_In_ PRULE_EVENT RuleEvent
)
{
HRESULT hr;
prevBlobSize = blobSize;
//
// Update previous entry
//
if( lastEventOffset != 0 ) {
PRULE_EVENT prev = (PRULE_EVENT) ((PBYTE)blob + lastEventOffset);
prev->NextOffset = blobSize;
} else {
//
// No entry so the blob is not set
//
D_ASSERT( blob == NULL );
RULE_REG_EXT baseRule = {0,};
baseRule.header.Version = blobVersion;
baseRule.RuleRegSize = sizeof(baseRule);
baseRule.SchemaVersion = schemaVersion;
baseRule.FirstEventOffset = sizeof(baseRule);
hr = AddData( &baseRule, sizeof(baseRule) );
if( FAILED( hr ) ) {
return hr;
}
// Now that we have added the header update the offset of the first event to reflect the current location
// We do this because AddData rounds up the location for the next write to be ptr aligned
PRULE_REG_EXT header = (PRULE_REG_EXT)blob;
header->FirstEventOffset = blobSize;
}
prevLastEventOffset = lastEventOffset;
lastEventOffset = blobSize;
hr = AddData( RuleEvent, sizeof(*RuleEvent) );
if( FAILED( hr ) ) {
return hr;
}
//
// Update the rule count
//
PRULE_REG pRule = (PRULE_REG)blob;
pRule->RuleCount++;
prevLastFilterOffset = lastFilterOffset;
lastFilterOffset = 0;
return S_OK;
}
HRESULT UndoEventAdd()
{
if( lastEventOffset == 0 || prevLastEventOffset == ULONG_MAX ) {
// Can't undo more than the very last event (no undo history).
return E_OUTOFMEMORY;
}
PRULE_REG pRule = (PRULE_REG)blob;
pRule->RuleCount--;
lastEventOffset = prevLastEventOffset;
prevLastEventOffset = UINT_MAX;
lastFilterOffset = prevLastFilterOffset;
prevLastFilterOffset = UINT_MAX;
blobSize = prevBlobSize;
if( lastEventOffset == 0 ) {
free( blob );
blob = NULL;
blobSize = 0;
blobAllocated = 0;
}
return S_OK;
}
//
// Add a filter entry for this current event
//
HRESULT
AddFilterEntry(
_In_ PRULE_FILTER RuleFilter
)
{
HRESULT hr;
D_ASSERT( lastEventOffset != 0 );
PRULE_EVENT currentEvent = (PRULE_EVENT)((PBYTE)blob + lastEventOffset);
//
// Update the previous entry
//
if( lastFilterOffset != 0 ) {
PRULE_FILTER prev = (PRULE_FILTER)((PBYTE)blob + lastFilterOffset);
prev->NextOffset = blobSize;
}
lastFilterOffset = blobSize;
// If this is part of an aggregation, set the backpointer to the aggregation object
if (RuleFilter->AggregationId) {
PRULE_AGGREGATION currentAggregation = (PRULE_AGGREGATION)((PBYTE)blob + aggregationOffset);
D_ASSERT(NULL != currentAggregation && currentAggregation->aggregationId == RuleFilter->AggregationId);
// If this is the first entry in the aggregation, update the root node
if (0 == currentAggregation->rootRuleOffset) {
currentAggregation->rootRuleOffset = blobSize;
}
++currentAggregation->ruleCount;
RuleFilter->AggregationOffset = aggregationOffset;
}
// Because we can now include aggregation objects we can no longer assume that the start of the rule chain
// is at a fixed offset from the start so we need to make a note of that too
if (0 == currentEvent->FirstFilterOffset) {
currentEvent->FirstFilterOffset = blobSize;
}
hr = AddData( RuleFilter, sizeof(*RuleFilter) + RuleFilter->DataSize );
// It's possible that this caused a realloc and invalidated the event pointer so recalculate before we dereference it again
currentEvent = (PRULE_EVENT)((PBYTE)blob + lastEventOffset);
if( FAILED( hr ) ) {
return hr;
}
//
// Update the rule event count
//
currentEvent->FilterCount++;
return S_OK;
}
//
// Add a rule aggregation entry
//
HRESULT AddAggregationEntry(_In_ PRULE_AGGREGATION pAggregation)
{
HRESULT hr;
D_ASSERT(lastEventOffset != 0);
// If we already have an aggregation object then set the next pointer to the new one
if (aggregationOffset != 0) {
PRULE_AGGREGATION prev = (PRULE_AGGREGATION)((PBYTE)blob + aggregationOffset);
prev->nextOffset = blobSize;
}
else {
// Record the address of the first record in the header
PRULE_REG_EXT header = (PRULE_REG_EXT)blob;
D_ASSERT(0 == header->FirstAggregationOffset);
header->FirstAggregationOffset = blobSize;
}
// Record the position of the node we are about to add. The rule filters will use this to record
// which aggregation they belong to. It is also used for chaining aggregation nodes.
aggregationOffset = blobSize;
hr = AddData(pAggregation, sizeof(RULE_AGGREGATION));
if (FAILED(hr)) {
return hr;
}
return S_OK;
}
};
//--------------------------------------------------------------------
//
// OpenXmlFile
//
// Open the XML File
//
//--------------------------------------------------------------------
FILE *
OpenXmlFile(
PCTCH FileName
)
{
FILE* stream = NULL;
if (NULL == FileName)
return NULL;
#if defined _WIN64 || defined _WIN32
TCHAR Buffer[2048];
errno_t err;
err = _tfopen_s(&stream, FileName, _T("r, ccs=UTF-16LE"));
if (err != 0) {
SetLastError(err);
_tprintf(_T("Error: Failed to open configuration file %s: %s\n"), FileName,
GetLastErrorText(Buffer, _countof(Buffer)));
stream = NULL;
}
#elif defined __linux__
stream = fopen(FileName, "rb");
if (stream == NULL) {
printf("Error: Failed to open configuration file %s\n", FileName);
}
#endif
return stream;
}
//--------------------------------------------------------------------
//
// GetFileContentWithDtd
//
// Fetch the content of the configuration file and add dtd info
//
//--------------------------------------------------------------------
#if defined _WIN64 || defined _WIN32
std::wstring
#elif defined __linux__
std::string
#endif
GetFileContentWithDtd(
_In_ PCTCH FileName,
_In_ ULONG version
)
{
FILE* stream;
#if defined _WIN64 || defined _WIN32
std::wstring ret;
const TCHAR xmlTag[] = _T("<?xml");
const TCHAR endTag[] = _T("?>");
#elif defined __linux__
std::string ret;
WCHAR xmlTag[] = {'<', '?', 'x', 'm', 'l', 0};
WCHAR endTag[] = {'?', '>', 0};
#endif
TCHAR Buffer[2048];
PTCHAR dtdContent, startPos, endPos;
BOOLEAN firstRead = TRUE;
size_t numRead = 0;
stream = OpenXmlFile( FileName );
if( NULL == stream ) {
return ret;
}
//
// Add the dtd rule to identify bad configuration
//
dtdContent = GetDtdFormat(version);
if (dtdContent == NULL) {
fclose( stream );
return ret;
}
#if defined _WIN64 || defined _WIN32
std::wstring dtdAndConfig( dtdContent );
#elif defined __linux__
unsigned int len = _tcslen( dtdContent );
//
// dtdAndConfig contains WCHAR data, so is twice the length of dtdContent,
// minus the terminating NULL.
// UTF8toUTF16() writes the NULL, so write it to tmp and then
// copy up to the NULL into dtdAndConfig
//
std::string dtdAndConfig( len * sizeof(WCHAR), 0 );
std::string tmp( ( len + 1) * sizeof(WCHAR), 0 );
if ( 0 == UTF8toUTF16( (PWCHAR)&tmp[0], dtdContent, len + 1 ) ) {
printf("Error: Failed to convert the DTD to UTF-16LE\n");
fclose( stream );
return ret;
}
memcpy( &dtdAndConfig[0], &tmp[0], len * sizeof( WCHAR ) );
#endif
// _countof() macro states number of entries (sizeof(X) / sizeof(*X))
// fread() reports number of bytes read. Divide this by the character size for number
// of characters.
while( (numRead = fread( Buffer, 1, _countof( Buffer ), stream ) / sizeof( TCHAR ) ) > 0 ) {
//
// Discard <?xml tag if it was added in the front.
//
if (firstRead == TRUE) {
startPos = Buffer;
while ( startPos[0] != '<' && numRead > 0 ) { // skip white space and BOM
startPos++;
numRead--;
}
if ( numRead == 0 ) {
printf( "Error: Too much white space\n" );
fclose( stream );
return ret;
}
firstRead = FALSE;
if (!WCSNICMP( (PWCHAR)startPos, xmlTag, WCSLEN( xmlTag ) - 1 ) ) {
endPos = (PTCHAR) WCSSTR( (PWCHAR)(startPos + WCSLEN( xmlTag ) - 1), endTag );
if ( endPos != NULL ) {
#if defined _WIN64 || defined _WIN32
endPos += WCSLEN( endTag );
#elif defined __linux__
endPos += ( WCSLEN( endTag ) * sizeof( WCHAR ) );
#endif
dtdAndConfig.append( endPos, numRead - (endPos - startPos) );
continue;
}
}
dtdAndConfig.append( startPos, numRead );
continue;
}
dtdAndConfig.append( Buffer, numRead );
}
fclose(stream);
return dtdAndConfig;
}
//--------------------------------------------------------------------
//
// GetFileContentWithDtd8
//
// Fetch the 8-bit content of the configuration file and add dtd info
//
//--------------------------------------------------------------------
std::string
GetFileContentWithDtd8(
_In_ PCCH FileName,
_In_ ULONG version
)
{
FILE* stream;
std::string ret;
CHAR Buffer[2048];
PTCHAR dtdContent;
PCHAR startPos;
PCHAR endPos;
BOOLEAN firstRead = TRUE;
const CHAR xmlTag[] = "<?xml";
const CHAR endTag[] = "?>";
size_t numRead = 0;
if( NULL == FileName ) {
return ret;
}
stream = fopen( FileName, "rb" );
if( stream == NULL ) {
printf( "Error: Failed to open configuration file: %s\n", FileName);
return ret;
}
//
// Add the dtd rule to identify bad configuration
//
dtdContent = GetDtdFormat( version );
if( dtdContent == NULL ) {
fclose( stream );
return ret;
}
#if defined _WIN64 || defined _WIN32
size_t convertedChars = WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, dtdContent, (int)_tcslen( dtdContent ), NULL, 0, NULL, NULL );
std::string dtdAndConfig( convertedChars, 0 );
convertedChars = WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, dtdContent, (int)_tcslen( dtdContent ), &dtdAndConfig[0], (int)convertedChars, NULL, NULL );
#elif defined __linux__
std::string dtdAndConfig( dtdContent );
#endif
while( (numRead = fread( Buffer, 1, sizeof( Buffer ), stream ) ) > 0 ) {
//
// Discard <?xml tag if it was added in the front.
//
if( firstRead == TRUE ) {
startPos = Buffer;
while( startPos[0] != '<' && numRead > 0 ) { // skip white space and BOM
startPos++;
numRead--;
}
if( numRead == 0 ) {
printf( "Error: Too much white space\n" );
fclose( stream );
return ret;
}
firstRead = FALSE;
if( !xmlStrncasecmp( (xmlChar*)startPos, (xmlChar*)xmlTag, (int)strlen( xmlTag ) ) ) {
endPos = strstr( startPos + strlen( xmlTag ), endTag );
if( endPos != NULL ) {
endPos += strlen( endTag );
dtdAndConfig.append( endPos, numRead - (endPos - startPos) );
continue;
}
}
dtdAndConfig.append( startPos, numRead );
continue;
}
dtdAndConfig.append( Buffer, numRead );
}
fclose( stream );
return dtdAndConfig;
}
//--------------------------------------------------------------------
//
// FetchConfigurationVersion
//
// Get the configuration file version
//
//--------------------------------------------------------------------
BOOLEAN
FetchConfigurationVersion(
_In_ PCTCH FileName,
_In_ ULONG* Version,
_Out_ char** XMLEncoding,
_Out_ BOOLEAN* Is16Bit,
_Out_ BOOLEAN* HasBOM
)
{
xmlDoc* doc = NULL;
xmlNode* sysmonNode = NULL;
xmlXPathContextPtr xpathCtx;
xmlChar xmlSysmonQuery[] = "/Sysmon[1]";
xmlXPathObjectPtr xpathObj;
xmlChar* versionString = NULL;
ULONG version = 0;
PCHAR fileEncoding = NULL;
UCHAR sniff[1024];
FILE* sniff_f = NULL;
size_t sniff_read = 0;
CHAR utf16le_str[] = "UTF-16LE";
*XMLEncoding = NULL;
*Is16Bit = false;
*HasBOM = false;
#if defined _WIN64 || defined _WIN32
char fileName[MAX_PATH];
size_t fileNameConv;
fileNameConv = WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, FileName, -1, fileName, sizeof( fileName ), NULL, NULL );
if( fileNameConv == 0 ) {
_tprintf( _T( "Error: Failed to load xml configuration: %s (could not convert to char array)\n" ),
FileName );
return FALSE;
}
fileName[MAX_PATH-1] = 0x00;
#elif defined __linux__
const char* fileName = FileName;
#endif
sniff_f = fopen( fileName, "rb" );
if( !sniff_f ) {
_tprintf( _T( "Error: Failed to open xml configuration: %s "), FileName );
printf( "(%s)\n", strerror( errno ) );
return FALSE;
}
sniff_read = fread( sniff, sizeof(unsigned char), sizeof( sniff ), sniff_f );
if( sniff_read < 2 ) {
_tprintf( _T( "Error: Failed to read xml configuration bytes: %s" ), FileName );
printf( "(%s)\n", strerror( errno ) );
fclose( sniff_f );
return FALSE;
}
fclose( sniff_f );
//
// Configuration files can be encoded in an ASCII-like format (one byte per character)
// or in a 16-bit format (two bytes per character). We need to identify whether the
// file is 8 bit or 16 bit so that later when we attach it to a DTD, we can encode the
// DTD in the same way (if the file is 8 bit, the DTD must be 8 bit; if the file is 16
// bit, the DTD must be 16 bit).
//
// If a Byte Order Mark (BOM) is present (first byte of file isn't white space or the
// '<' character), then we can work out if it specifies a 16 bit encoding (first byte
// is 0xFF) or an 8 bit encoding (any other byte).
//
// If no BOM, then we can work out manually if the file is 8 bit or 16 bit by examining
// the second byte and checking if it is 0x00. The only valid first characters are
// '<' or a whitespace character, all of which will have 0x00 as the second byte if
// the file is 16 bit encoded (as '<', ' ', tab, line feed, carriage return, etc, are
// all in the ASCII range 0x0000 to 0x007F).
//
if( !std::isspace( sniff[0] ) && sniff[0] != '<' ) {
*HasBOM = true;
if( sniff[0] == 0xff ) {
*Is16Bit = true;
}
} else {
if( sniff[1] == 0x00 ) {
fileEncoding = utf16le_str;
*Is16Bit = true;
} else {
*Is16Bit = false;
}
}
//
// read file with detected file encoding if there was no BOM
//
doc = xmlReadFile( fileName, fileEncoding, 0 );
if( !doc ) {
_tprintf( _T( "Error: Failed to load xml configuration: %s (could not read file)\n" ),
FileName );
return FALSE;
}
xpathCtx = xmlXPathNewContext( doc );
if( !xpathCtx ) {
_tprintf( _T( "Error: Failed to find Sysmon tag in configuration: %s\n" ), FileName );
xmlFreeDoc( doc );
return FALSE;
}
xpathObj = xmlXPathEvalExpression( xmlSysmonQuery, xpathCtx );
if( !xpathObj || !xpathObj->nodesetval || xpathObj->nodesetval->nodeNr < 1 ) {
_tprintf( _T( "Error: Failed to find Sysmon tag in configuration: %s\n" ), FileName );
if (xpathObj != NULL) {
xmlXPathFreeObject( xpathObj );
}
xmlXPathFreeContext( xpathCtx );
xmlFreeDoc( doc );
return FALSE;
}
xmlXPathFreeContext( xpathCtx );
sysmonNode = xpathObj->nodesetval->nodeTab[0];
versionString = xmlGetProp( sysmonNode, (xmlChar *)"schemaversion" );
//
// If an <?xml> tag is present and specifies an encoding, then store this to use when reading
// the file with the DTD.
//
if( doc->encoding ) {
*XMLEncoding = _strdup( (PCHAR)doc->encoding );
} else {
*XMLEncoding = NULL;
}
xmlFreeDoc( doc );
xmlXPathFreeObject ( xpathObj );
version = ParseVersionString( (PCHAR)versionString );
if( version == (ULONG)-1 ) {
printf( "Error: Invalid schema version number (%s) ", versionString );
_tprintf( _T(" for configuration: %s\n"), FileName );
xmlFree ( versionString );
return FALSE;
}
*Version = version;
xmlFree ( versionString );
return TRUE;
}
//--------------------------------------------------------------------
//
// GetAdditionalRules
//
// Get additional rules based on configuration.
//
//--------------------------------------------------------------------
BOOLEAN
GetAdditionalRules(
_Out_ PADD_RULES AddRules,
_In_ ULONG MaxSize
)
{
ULONG i;
D_ASSERT( MaxSize > 2 );
i = 0;
ZeroMemory( AddRules, MaxSize * sizeof(*AddRules) );
if( (i + 1) > MaxSize ) {
return FALSE;
}
if( OPT_VALUE(ImageLoad) ) {
AddRules[i].eventType = &SYSMONEVENT_IMAGE_LOAD_Type;
AddRules[i].fieldId = F_IL_Image;
AddRules[i].filterOption = Filter_image;
AddRules[i].dataMultiSz = StringListDup( (PTCHAR)OPT_VALUE(ImageLoad), NULL );
D_ASSERT( AddRules[i].dataMultiSz != NULL && AddRules[i].dataMultiSz[0] != 0 );
i++;
}
if( (i + 1) > MaxSize ) {
return FALSE;
}
if( OPT_VALUE(NetworkConnect) ) {
AddRules[i].eventType = &SYSMONEVENT_NETWORK_CONNECT_Type;
AddRules[i].fieldId = F_NC_Image;
AddRules[i].filterOption = Filter_image;
AddRules[i].dataMultiSz = StringListDup( (PTCHAR)OPT_VALUE(NetworkConnect), NULL );
D_ASSERT( AddRules[i].dataMultiSz != NULL && AddRules[i].dataMultiSz[0] != 0 );
i++;
}
if( (i + 1) > MaxSize ) {
return FALSE;
}
return TRUE;
}
//--------------------------------------------------------------------
//
// FindConfigurationOption
//
// Identify the configuration option matched with the node name
//
//--------------------------------------------------------------------
PCONFIGURATION_OPTION_TYPE
FindConfigurationOption(
_In_ PTCHAR ConfigurationNode
)
{
SIZE_T index;
const TCHAR configName[] = _T("Config");
SIZE_T len;
len = _tcslen( ConfigurationNode );
//
// Handle special configuration options
//
if( len > ARRAYSIZE(configName) &&
!_tcscmp( ConfigurationNode + len - ARRAYSIZE(configName) + 1,
configName ) ) {
len -= ARRAYSIZE(configName) - 1;
}
for( index = 0; index < ConfigOptionTypeCount; index++ ) {
if( ConfigOptionType[index].CommandLineOnly ||