forked from Sysinternals/SysmonCommon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rules.c
1973 lines (1556 loc) · 44.7 KB
/
rules.c
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.
*/
//====================================================================
//
// Rules.c
//
// Rule engine for user-mode and kernel-mode
//
//====================================================================
#include "rules.h"
#if defined _WIN64 || defined _WIN32
#ifndef SYSMON_DRIVER
#include "windows.h"
#endif
#elif defined __linux__
#include <stdarg.h>
#include <pthread.h>
#include "linuxTypes.h"
#include "linuxHelpers.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if defined _WIN64 || defined _WIN32
#ifndef ALIGN_DOWN_BY
#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))
#endif // ALIGN_DOWN_BY
#elif defined __linux__
#define MAX_FIELD_VALUE_LEN 512
#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
//
// Current rule set
//
PRULE_SET g_blob = NULL;
#define SYSMON_MAX_ULONG 0xffffffffUL
//
// Critical section to access g_blog
//
#ifdef SYSMON_DRIVER
#define D_ASSERT(_x)
#define DBG_MODE(...)
#define _tprintf(...)
ERESOURCE g_Lock;
#define INIT_CRIT() ExInitializeResourceLite( &g_Lock )
#define ENTER_CRIT_READ() { KeEnterCriticalRegion(); ExAcquireResourceSharedLite( &g_Lock, TRUE ); }
#define LEAVE_CRIT_READ() { ExReleaseResourceLite( &g_Lock ); KeLeaveCriticalRegion(); }
#define ENTER_CRIT_WRITE() { KeEnterCriticalRegion(); ExAcquireResourceExclusiveLite( &g_Lock, TRUE ); }
#define LEAVE_CRIT_WRITE() { ExReleaseResourceLite( &g_Lock ); KeLeaveCriticalRegion(); }
extern PVOID
SysmonAllocate(
POOL_TYPE PoolType,
ULONG Size,
ULONG Tag
);
#define ALLOC(_x) SysmonAllocate( PagedPool, (ULONG) _x, 'R' )
#define FREE(_x) ExFreePool( _x )
// The driver doesn't need to print errors, replacing by a noop.
#define PrintErrorEx(...)
#else
CRITICAL_SECTION g_crit;
#if defined _WIN64 || defined _WIN32
BOOLEAN g_readWrite = FALSE;
SRWLOCK g_rwLock;
#define RW_PROTO(_r, _n, _p) \
typedef _r (WINAPI * t ## _n)## _p ##; \
t ## _n l_ ## _n = NULL
#define PROTO_RESOLVE( _h, _n ) \
l_ ## _n = (t ## _n) GetProcAddress( _h, #_n );
RW_PROTO( VOID, InitializeSRWLock, ( PSRWLOCK SRWLock ) );
RW_PROTO( VOID, AcquireSRWLockExclusive, ( PSRWLOCK SRWLock ) );
RW_PROTO( VOID, AcquireSRWLockShared, ( PSRWLOCK SRWLock ) );
RW_PROTO( VOID, ReleaseSRWLockExclusive, ( PSRWLOCK SRWLock ) );
RW_PROTO( VOID, ReleaseSRWLockShared, ( PSRWLOCK SRWLock ) );
//--------------------------------------------------------------------
//
// InitializeLock
//
// Try to use RW lock for better performance, default to critical
// sections
//
//--------------------------------------------------------------------
VOID
InitializeLock(
VOID
)
{
HMODULE hKernel = GetModuleHandle( _T("kernel32.dll") );
if( hKernel != NULL ) {
PROTO_RESOLVE( hKernel, InitializeSRWLock );
PROTO_RESOLVE( hKernel, AcquireSRWLockExclusive );
PROTO_RESOLVE( hKernel, AcquireSRWLockShared );
PROTO_RESOLVE( hKernel, ReleaseSRWLockExclusive );
PROTO_RESOLVE( hKernel, ReleaseSRWLockShared );
}
if( l_InitializeSRWLock != NULL &&
l_AcquireSRWLockExclusive != NULL &&
l_AcquireSRWLockShared != NULL &&
l_ReleaseSRWLockExclusive != NULL &&
l_ReleaseSRWLockShared != NULL ) {
g_readWrite = TRUE;
l_InitializeSRWLock( &g_rwLock );
} else {
InitializeCriticalSection( &g_crit );
}
}
#define INIT_CRIT() InitializeLock()
#define ENTER_CRIT_READ() { if( g_readWrite ) { l_AcquireSRWLockShared( &g_rwLock ); } else { EnterCriticalSection( &g_crit ); } }
#define LEAVE_CRIT_READ() { if( g_readWrite ) { l_ReleaseSRWLockShared( &g_rwLock ); } else { LeaveCriticalSection( &g_crit ); } }
#define ENTER_CRIT_WRITE() { if( g_readWrite ) { l_AcquireSRWLockExclusive( &g_rwLock ); } else { EnterCriticalSection( &g_crit ); } }
#define LEAVE_CRIT_WRITE() { if( g_readWrite ) { l_ReleaseSRWLockExclusive( &g_rwLock ); } else { LeaveCriticalSection( &g_crit ); } }
#elif defined __linux__
VOID
InitializeLock(
VOID
)
{
InitializeCriticalSection( &g_crit );
}
#define INIT_CRIT() InitializeLock()
#define ENTER_CRIT_READ() { EnterCriticalSection( &g_crit ); }
#define LEAVE_CRIT_READ() { LeaveCriticalSection( &g_crit ); }
#define ENTER_CRIT_WRITE() { EnterCriticalSection( &g_crit ); }
#define LEAVE_CRIT_WRITE() { LeaveCriticalSection( &g_crit ); }
LONG
InterlockedIncrement(
LONG volatile *Addend
)
{
(*Addend)++;
return *Addend;
}
LONG
InterlockedDecrement(
LONG volatile *Addend
)
{
(*Addend)--;
return *Addend;
}
void PrintErrorEx( PTCHAR ID, DWORD ErrorCode, PTCHAR Format, ... )
{
va_list args;
va_start( args, Format );
fprintf(stderr, "Sysmon error. ID:'%s', ERROR:%d\n", ID, ErrorCode);
vfprintf(stderr, Format, args);
}
#define min(a,b) (((a) < (b)) ? (a) : (b))
#endif
#define ALLOC(_x) malloc( _x )
#define FREE(_x) free( _x )
#endif
// WIDECHAR simplifies using a WCHAR character between Windows and Linux.
#if defined _WIN64 || defined _WIN32
#define WIDECHAR(x) L##x
#elif defined __linux__
#define WIDECHAR(x) (WCHAR)x
#endif
//----------------------------------------------------------------------
//
// NextItem
//
// An helper function to iterate a string list using Delim.
//
// Context tracks the next item in the list.
// Delim is the delimiter WCHAR between elements in the list.
// Token is the current item tracked.
// TokenCchSize is the SIZE in character of the current position.
//
// Returns TRUE if an entry is available, false if done.
//
//----------------------------------------------------------------------
BOOLEAN NextItem( _Inout_ PCWSTR *Context, _In_ WCHAR Delim, _Out_ PCWSTR *Token, _Out_ PSIZE_T TokenCchSize ) {
PCWSTR start, end;
start = *Context;
end = start;
// Indicates the end of the iteration.
if( start == NULL ) {
return FALSE;
}
// Iterate to the next entry or the end.
while( *end && *end != Delim ) {
end++;
}
// Fill information.
*TokenCchSize = end - start;
*Token = start;
// If the end was not \0 WCHAR, put context on the next WCHAR.
// Else set it to NULL to end during the next iteratior.
if( *end ) {
*Context = end + 1;
} else {
*Context = NULL;
}
return TRUE;
}
//----------------------------------------------------------------------
//
// FindSubString
//
// str is the string which is checked.
// sub is the string being looked for in str. It was lowered when loading
// the rule data.
//
//----------------------------------------------------------------------
PCWSTR FindSubString( _In_ PCWSTR str, _In_ PCWSTR sub, _In_ SIZE_T subCchMax )
{
PCWSTR str1, str2, subMax = NULL;
PCWSTR pos = str;
WCHAR c1, c2;
if( subCchMax != 0 ) {
subMax = sub + subCchMax;
}
while( *pos ) {
str1 = pos;
str2 = sub;
while( TRUE ) {
c1 = *str1;
c2 = *str2;
// Matched the whole sub string.
if( !c2 ) {
return pos;
}
// Ended iteration on str without a full match.
if( !c1 ) {
return NULL;
}
if( TOWLOWER( c1 ) != c2 ) {
break;
}
++str1;
++str2;
// Matched the whole string at that point.
if( str2 == subMax ) {
return pos;
}
}
++pos;
}
return NULL;
}
//--------------------------------------------------------------------
//
// IsVersionGreater
//
// Simple version comparison without using floating point for the kernel
//
//--------------------------------------------------------------------
BOOLEAN
IsVersionGreater(
ULONG Version,
ULONG Major,
ULONG Minor
)
{
if( V_MAJOR( Version ) < Major ) {
return FALSE;
}
if( V_MAJOR(Version) == Major &&
V_MINOR(Version) <= Minor ) {
return FALSE;
}
return TRUE;
}
//--------------------------------------------------------------------
//
// IsVersionGreaterFromContext
//
// Similar to IsVersionGreater but take RULE_CONTEXT as input.
//
//--------------------------------------------------------------------
BOOLEAN
IsVersionGreaterFromContext(
_In_ PRULE_CONTEXT Context,
_In_ ULONG Major,
_In_ ULONG Minor
)
{
PRULE_REG ruleBase = (PRULE_REG)Context->Current->Rules;
return IsVersionGreater( ruleBase->Version, Major, Minor );
}
//--------------------------------------------------------------------
//
// InitializeRules
//
// Initialize the rule engine
//
//--------------------------------------------------------------------
BOOLEAN
InitializeRules(
VOID
)
{
static BOOLEAN wasInitialized = FALSE;
if( !wasInitialized ) {
INIT_CRIT();
wasInitialized = TRUE;
}
return TRUE;
}
//--------------------------------------------------------------------
//
// GetBlobReference
//
// Get a refrence to the current ruleset, increase the reference count
//
//--------------------------------------------------------------------
PRULE_SET
GetBlobReference(
VOID
)
{
PRULE_SET ret = NULL;
LONG value;
ENTER_CRIT_READ();
if( g_blob != NULL ) {
ret = g_blob;
value = InterlockedIncrement( &ret->ReferenceCount );
//
// Unlikely to happen
//
if( value < 0 ) {
InterlockedDecrement( &ret->ReferenceCount );
ret = NULL;
D_ASSERT( !"Reference count bug in the rule engine" );
}
}
LEAVE_CRIT_READ();
return ret;
}
//--------------------------------------------------------------------
//
// CleanupQuickAccessTable
//
// Clean-up a fully or half-initialized table.
//
//--------------------------------------------------------------------
VOID
CleanupQuickAccessTable(
_In_ PRULE_INDEX_TABLE IndexingTable
)
{
ULONG i;
if( IndexingTable == NULL ) {
return;
}
for( i = 0; i < _countof( IndexingTable->Entries ); i++ ) {
FREE( IndexingTable->Entries[i].Events );
}
FREE( IndexingTable );
}
//--------------------------------------------------------------------
//
// ReleaseBlobReference
//
// Release reference to a rule set, free it if needed
//
//--------------------------------------------------------------------
VOID
ReleaseBlobReference(
_In_ PRULE_SET RuleSet
)
{
BOOLEAN release = FALSE;
LONG decr;
if (NULL != RuleSet) {
ENTER_CRIT_READ();
decr = InterlockedDecrement( &RuleSet->ReferenceCount );
if( decr == 0 ) {
release = TRUE;
}
LEAVE_CRIT_READ();
D_ASSERT( decr >= 0 );
//
// Free the rule set as needed
//
if( release ) {
CleanupQuickAccessTable( RuleSet->IndexingTable );
#if !defined(SYSMON_PUBLIC)
CleanupQuickAccessTable( RuleSet->ShadowIndexingTable );
#endif
FREE( RuleSet->Rules );
FREE( RuleSet );
}
}
}
//--------------------------------------------------------------------
//
// GetIndexFromEventId
//
// Transform the event id to an index on the quick access table.
// Returns -1 if the event id is not meant for the target table.
//
//--------------------------------------------------------------------
LONG
GetIndexFromEventId(
_In_ ULONG EventId,
_In_ BOOLEAN Internal
)
{
LONG ret = -1;
ULONG highestMatchingId;
//
// For rule types like Registry and Pipe, we need to find highest matching rule
//
highestMatchingId = EventId;
while( highestMatchingId+1 < AllEventsCount &&
AllEvents[highestMatchingId+1]->RuleName != NULL &&
!_tcsicmp( AllEvents[EventId]->RuleName, AllEvents[highestMatchingId+1]->RuleName ) ) {
highestMatchingId++;
}
EventId = highestMatchingId;
#if !defined(SYSMON_PUBLIC)
BOOLEAN isInternal;
isInternal = ( ( EventId & INTERNAL_EVENT_MASK ) != 0 );
if( isInternal != Internal ) {
ret = -1;
} else {
ret = (LONG)( EventId & ~INTERNAL_EVENT_MASK );
}
#else
//
// Public version does not need any change
//
D_ASSERT( Internal == FALSE );
Internal;
ret = (LONG)EventId;
#endif
if( ret == 255 ) {
ret = 0;
}
D_ASSERT( ret < 255 );
return ret;
}
//--------------------------------------------------------------------
//
// GetIndexAndTableFromEventId
//
// Transform the event id to an index on the quick access table.
// Returns -1 if the event id is not meant for the target table.
//
// This function also set the target indexing table
//
//--------------------------------------------------------------------
LONG
GetIndexAndTableFromEventId(
_In_ PRULE_CONTEXT Context,
_In_ ULONG EventId,
_Out_ PRULE_INDEX_TABLE* IndexingTable
)
{
LONG curId;
*IndexingTable = NULL;
curId = GetIndexFromEventId( EventId, FALSE );
if( curId >= 0 ) {
*IndexingTable = Context->Current->IndexingTable;
}
#if !defined(SYSMON_PUBLIC)
else {
curId = GetIndexFromEventId( EventId, TRUE );
if( curId >= 0 ) {
*IndexingTable = Context->Current->ShadowIndexingTable;
}
}
#endif
return curId;
}
//--------------------------------------------------------------------
// LowerRuleFilter
//
// All rule filters are case insensitive, lower the rule data by default
// to make matching faster in many conditions.
//
//--------------------------------------------------------------------
VOID LowerRuleFilter(_In_ PRULE_FILTER ruleFilter)
{
PWCHAR pos;
ULONG i;
for( i = 0; i < ruleFilter->DataSize; i += sizeof(WCHAR) ) {
pos = &((PWCHAR)ruleFilter->Data)[i/sizeof(WCHAR)];
*pos = TOWLOWER(*pos);
}
}
//--------------------------------------------------------------------
//
// BackwardFillEventList
//
// Add entries at the back of the event list based on the event count.
// Simplifies the logic on filling the event rule filter list.
//
//--------------------------------------------------------------------
BOOLEAN
BackwardFillEventList(
_In_ PRULE_CONTEXT Context,
_In_ PRULE_INDEX_TABLE Table,
_In_ BOOLEAN Internal,
_In_ PUSHORT EventCount,
_In_ RuleDefaultType DefaultFilter
)
{
LONG curId;
USHORT pos;
PRULE_EVENT ruleEvent;
for( ruleEvent = NextRuleEvent( Context, NULL );
ruleEvent != NULL;
ruleEvent = NextRuleEvent( Context, ruleEvent ) ) {
curId = GetIndexFromEventId( ruleEvent->EventId, Internal );
if( curId < 0 || ruleEvent->RuleDefault != DefaultFilter ) {
continue;
}
// The counter should never underflow, still check for it.
if( EventCount[curId] == 0 ) {
PrintErrorEx( _T("RuleEngine"), ERROR_INVALID_DATA, _T("Invalid data in rules") );
return FALSE;
}
pos = --EventCount[curId];
Table->Entries[curId].Events[pos] = ruleEvent;
}
return TRUE;
}
//--------------------------------------------------------------------
//
// ComputeQuickAccessTables
//
// Compute a quick access table from the blob so rules can be processed
// as fast as possible without going through all entries.
//
//--------------------------------------------------------------------
BOOLEAN
ComputeQuickAccessTables(
_In_ PRULE_SET RuleSet,
_In_ BOOLEAN Internal,
_Out_ PRULE_INDEX_TABLE* IndexingTable,
_In_ BOOLEAN Transform
)
{
RULE_CONTEXT customContext;
PRULE_EVENT ruleEvent;
PRULE_FILTER ruleFilter;
LONG curId;
ULONG i, allocSize;
PRULE_INDEX_TABLE table;
PRULE_EVENT* events;
RULE_REG ruleReg;
RULE_REG_EXT ruleRegExt;
USHORT eventCount[SYSMON_MAX_EVENT_ID + 1] = {0,};
*IndexingTable = NULL;
customContext.Current = RuleSet;
//
// Check version is correct
//
if( !GetRuleRegInformation( &customContext, &ruleReg ) ||
ruleReg.RuleCount == 0 ) {
PrintErrorEx( _T("RuleEngine"), ERROR_INVALID_DATA, _T("Invalid configuration") );
return FALSE;
}
if( !IsCompatibleBinaryVersion( ruleReg.Version ) ) {
if( IsVersionGreater( ruleReg.Version, 1, 0 ) && GetRuleRegExtInformation( &customContext, &ruleRegExt ) ) {
PrintErrorEx( _T("RuleEngine"), 0, _T("Registry rule version %.2f (binary %.2f) is incompatible with Sysmon rule")
_T(" version %.2f (binary %.2f). ")
_T("Please rebuild your manifest with Sysmon schema %.2f."),
TO_DOUBLE( ruleRegExt.SchemaVersion ),
TO_DOUBLE( ruleReg.Version ),
TO_DOUBLE( ConfigurationVersion ),
TO_DOUBLE( BinaryVersion ),
TO_DOUBLE( ConfigurationVersion ) );
} else {
PrintErrorEx( _T("RuleEngine"), 0, _T("Registry rule version %.2f is incompatible with Sysmon rule version %.2f. ")
_T("Please rebuild your manifest with Sysmon schema %.2f."),
TO_DOUBLE( ruleReg.Version ),
TO_DOUBLE( BinaryVersion ),
TO_DOUBLE( ConfigurationVersion ) );
}
return FALSE;
}
table = ALLOC( sizeof( *table ) );
if( table == NULL ) {
PrintErrorEx( _T("RuleEngine"), ERROR_OUTOFMEMORY, _T("Failed to allocate memory") );
return FALSE;
}
memset( table, 0, sizeof( *table ) );
// Check rules are valid, count number of events per type and apply transformation if needed.
for( ruleEvent = NextRuleEvent( &customContext, NULL );
ruleEvent != NULL;
ruleEvent = NextRuleEvent( &customContext, ruleEvent ) ) {
curId = GetIndexFromEventId( ruleEvent->EventId, Internal );
if( curId < 0 ) {
continue;
}
// Check rules default are valid too
if( curId > SYSMON_MAX_EVENT_ID ) {
PrintErrorEx( _T("RuleEngine"), ERROR_INVALID_DATA, _T("Invalid event id in rules") );
goto failed;
}
if( ruleEvent->RuleDefault != Rule_include && ruleEvent->RuleDefault != Rule_exclude ) {
PrintErrorEx( _T("RuleEngine"), ERROR_INVALID_DATA, _T("Invalid data in rules") );
goto failed;
}
// Check if the value will overflow now or on allocation next.
if( eventCount[curId] >= 0xFFFE ) {
PrintErrorEx( _T("RuleEngine"), ERROR_INVALID_DATA, _T("Invalid event count in rules") );
goto failed;
}
eventCount[curId]++;
if( !Transform ) {
continue;
}
for( ruleFilter = NextRuleFilter( &customContext, ruleEvent, NULL );
ruleFilter != NULL;
ruleFilter = NextRuleFilter( &customContext, ruleEvent, ruleFilter ) ) {
LowerRuleFilter( ruleFilter );
#if defined _WIN64 || defined _WIN32
// Add the Filter_Environment tag so expansion is done only if needed.
if( wcschr( (PWCHAR)ruleFilter->Data, WIDECHAR( '%' ) ) != NULL ) {
ruleFilter->FilterType |= Filter_Environment;
}
#endif
}
}
// Allocate the list for each event id.
for( i = 0; i < _countof( eventCount ); i++ ) {
// All events needed and a NULL pointer at the end.
allocSize = ( eventCount[i] + 1 ) * sizeof( PVOID );
if( allocSize == 0 ) {
continue;
}
events = ALLOC( allocSize );
if( events == NULL ) {
PrintErrorEx( _T("RuleEngine"), ERROR_OUTOFMEMORY, _T("Failed to allocate memory") );
goto failed;
}
memset( events, 0, allocSize );
table->Entries[i].Events = events;
}
// Add default exclude to the back first, then include.
if( !BackwardFillEventList( &customContext, table, Internal, eventCount, Rule_exclude ) ||
!BackwardFillEventList( &customContext, table, Internal, eventCount, Rule_include ) ) {
goto failed;
}
// All events should have been added, check in debug mode that eventCount is zero.
for( i = 0; i < _countof( eventCount ); i++ ) {
D_ASSERT( eventCount[i] == 0 );
}
*IndexingTable = table;
return TRUE;
failed:
CleanupQuickAccessTable( table );
return FALSE;
}
//--------------------------------------------------------------------
//
// SetRuleBlob
//
// Set the current rules to apply and compute the quick access tables.
//
// The Transform parameter indicates if the rule data should be
// modified for quick matching. It is expected to be TRUE when rules
// are loaded in the service or driver.
//
//--------------------------------------------------------------------
BOOLEAN
SetRuleBlob(
_In_ PVOID Rules,
_In_ ULONG RulesSize,
_In_ BOOLEAN Transform
)
{
PRULE_SET newSet = NULL, oldSet;
// The Sysmon driver should always do transformation.
#if defined( SYSMON_DRIVER )
D_ASSERT( Transform == TRUE );
#endif
if( Rules != NULL && RulesSize != 0 ) {
newSet = (PRULE_SET) ALLOC( sizeof(*newSet) );
if( newSet == NULL ) {
PrintErrorEx( _T("RuleEngine"), ERROR_OUTOFMEMORY, _T("Failed to allocate memory") );
return FALSE;
}
newSet->Version = 1;
newSet->Rules = Rules;
newSet->RulesSize = RulesSize;
newSet->ReferenceCount = 1;
if( !ComputeQuickAccessTables( newSet, FALSE, &newSet->IndexingTable, Transform ) ) {
FREE( newSet );
return FALSE;
}
#if !defined(SYSMON_PUBLIC)
if( !ComputeQuickAccessTables( newSet, TRUE, &newSet->ShadowIndexingTable, Transform ) ) {
CleanupQuickAccessTable( newSet->IndexingTable );
FREE( newSet );
return FALSE;
}
#endif
}
ENTER_CRIT_WRITE();
oldSet = g_blob;
g_blob = newSet;
if( oldSet != NULL && newSet != NULL ) {
newSet->Version = oldSet->Version + 1;
}
LEAVE_CRIT_WRITE();
//
// Decrease reference count on the old set
//
if( oldSet != NULL ) {
ReleaseBlobReference( oldSet );
}
return TRUE;
}
//--------------------------------------------------------------------
//
// InitializeRuleContext
//
// Initialize the context used to keep state
//
//--------------------------------------------------------------------
BOOLEAN
InitializeRuleContext(
_Out_ PRULE_CONTEXT Context
)
{
PRULE_SET ruleSet;
memset( Context, 0, sizeof( *Context ) );
ruleSet = GetBlobReference();
if( ruleSet == NULL ) {
return FALSE;
}
Context->Current = ruleSet;
return TRUE;
}
//--------------------------------------------------------------------
//
// ReleaseRuleContext
//
// Released an initialized context
//
//--------------------------------------------------------------------
VOID
ReleaseRuleContext(
_In_ PRULE_CONTEXT Context
)
{
ReleaseBlobReference( Context->Current );
Context->Current = NULL;
}
//--------------------------------------------------------------------
//
// GetRuleVersion
//
// Get the current rule version
//
//--------------------------------------------------------------------
ULONG
GetRuleVersion(
VOID
)
{
ULONG ret = 0;
RULE_CONTEXT ctx;
if( InitializeRuleContext( &ctx ) ) {
ret = GET_RULECTX_VERSION( &ctx );
ReleaseRuleContext( &ctx );
}
return ret;
}
//--------------------------------------------------------------------
//
// IsValidPointer
//
// Verify a pointer is within the rule bounds
//
//--------------------------------------------------------------------
BOOLEAN
IsValidPointer(
_In_ PRULE_CONTEXT Context,
_In_ PVOID ptr
)
{
PUCHAR start = (PUCHAR)Context->Current->Rules;
PUCHAR end = start + Context->Current->RulesSize;
if( (PUCHAR)ptr < start || (PUCHAR)ptr >= end ) {
return FALSE;