forked from microsoft/SysmonCommon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
manifest.tt
1506 lines (1324 loc) · 37 KB
/
manifest.tt
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
<#@ template language="C#" hostspecific="true" #>
<#@ output encoding="utf-16" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Xml" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.IO" #>
<#
//
// This T4 template is able to generate .mc, .man and header files based on the target version (internal, shared, public)
// Data is pulled from manifest.xml and arguments from TextTransform allow to generate the right file.
//
string type = Host.ResolveParameterValue("", "", "type").ToLower();
XmlDocument doc = new XmlDocument();
doc.Load(Host.ResolvePath("manifest.xml"));
XmlNodeList manifests = doc.SelectNodes(@"//manifest");
var fieldHashDict = new Dictionary<string, int>();
var manDict = new Dictionary<double, XmlNode>();
double highest = 0;
double highestBinary = 0;
// Find the highest version manifest
foreach (XmlNode m in manifests) {
if (m.Attributes["schemaversion"] == null || m.Attributes["binaryversion"] == null) {
throw new Exception("One manifest entry misses a schemaversion or binaryversion number");
}
var v = double.Parse(m.Attributes["schemaversion"].Value);
var b = double.Parse(m.Attributes["binaryversion"].Value);
if (manDict.ContainsKey(v)) {
throw new Exception("Multiple manifest with same schemaversion number");
}
manDict[v] = m;
if (v > highest) {
highest = v;
}
if (b > highestBinary) {
highestBinary = b;
}
}
var highestBase = Math.Round(highest);
if (highestBase > highest) highestBase -= 1.0;
XmlNode man = manDict[highest];
XmlNodeList eventNodes = man.SelectNodes(@".//event");
if (type == "header") {
#>
//====================================================================
//
// Sysmonevents.h
//
// Copyright (C) 2014 Mark Russinovich and Thomas Garnier
//
// Sysmon events information header, generated by T4 template.
// DO NOT EDIT DIRECTLY. MAKE CHANGES TO MANIFEST.TT.
//
//====================================================================
#pragma once
#ifndef SYSMON_DRIVER
#ifndef SYSMON_EBPF
#if defined _WIN64 || defined _WIN32
#include "..\sysmonCommon\stdafx.h"
#else
#include "stdafx.h"
#endif
#endif
#if defined(SYSMON_SHARED)
#include "sysmonmsg_shared.h"
#include "sysmonmsgop_shared.h"
#elif defined(SYSMON_PUBLIC)
#include "sysmonmsg_public.h"
#include "sysmonmsgop_public.h"
#else
#include "sysmonmsg.h"
#include "sysmonmsgop.h"
#endif
#else
#include <fltkernel.h>
#define _T(_x) L ## _x
#if !defined(_countof)
#define _countof(_x) (sizeof(_x)/sizeof(*_x))
#endif
#define _tcsicmp _wcsicmp
#endif
#if defined _WIN64 || defined _WIN32
#define STRCASECMP(a,b) _stricmp(a,b)
#elif defined __linux__
#define STRCASECMP(a,b) strcasecmp(a,b)
#endif
//
// Types submitted to the engine
//
typedef enum {
N_Invalid = 0,
N_UnicodeString,
N_EscapeUnicodeString,
N_AnsiOrUnicodeString,
N_UnicodePath,
N_Ptr,
N_Ulong,
N_Ulong64,
N_LargeTime,
N_ProcessId,
N_LogonId,
N_Sid,
N_Hash,
N_GUID,
N_CallTrace,
N_RegistryPath,
N_LinuxCommandLine
} NativeTypes;
//
// Types expected by the Vista+ event manager
//
typedef enum {
I_UnicodeString,
I_GUID,
I_UInt64,
I_UInt32,
I_UInt16,
I_HexInt64,
I_HexInt32,
I_Boolean
} InTypes;
typedef enum {
Rule_include = 0,
Rule_exclude,
Rule_include_partial,
Rule_exclude_partial,
Rule_Unknown = -1
} RuleDefaultType;
typedef enum {
RuleCombineOR = 0,
RuleCombineAND = 1,
RuleCombineDefault = 0
} RuleCombineType, *PRuleCombineType;
//
// Describe an event structure
//
typedef struct {
USHORT FieldCount;
NTSTATUS EventLegacyId;
const EVENT_DESCRIPTOR* EventDescriptor;
ULONG EventId;
PTCHAR EventName;
PTCHAR EventDescription;
InTypes* EventOutputTypes;
PTCHAR* FieldNames;
ULONG EventTimeField;
PTCHAR RuleName;
RuleDefaultType Default;
PULONG FieldHashes;
} SYSMON_EVENT_TYPE_FMT, *PSYSMON_EVENT_TYPE_FMT;
#define NO_FIELD ((ULONG)-1)
//
// Describe entry awaiting processing
//
typedef struct {
NativeTypes Type;
PVOID Ptr;
ULONG Size;
BOOLEAN Allocated;
} SYSMON_DATA_DESCRIPTOR, *PSYSMON_DATA_DESCRIPTOR;
<#
int padding = 40;
int maxfields = 0;
int maxid = 0;
var eventIdTableDict = new Dictionary<int, string>();
foreach (XmlNode e in eventNodes)
{
var i = OutputIfDef(e);
// All identifiers should be integers, don't assume sequence.
// Ignore error ID that was 255 (first one).
var id = Int32.Parse(e.Attributes["value"].Value);
if (id > maxid && id != 255) {
maxid = id;
}
if (i != "") {
#>
#if <#= i #>
<#
} else {
#>
<#
}
var name = e.Attributes["name"].Value;
var accro = GetAcro(e);
if (eventIdTableDict.ContainsKey(id)) {
throw new Exception("Two entries have same identifier");
}
eventIdTableDict[id] = name;
#>
//
// <#= name #> event
//
<#
XmlNodeList sub = e.SelectNodes(@".//data");
int index = 0;
bool timeField = false;
foreach(XmlNode s in sub)
{
var s_name = s.Attributes["name"].Value;
if (s_name == "UtcTime") {
timeField = true;
}
#>
#define <#= String.Format("{0}_{1,-"+(padding - accro.Length).ToString()+"} {2,2} // Type: {3}", accro, s_name, index, GetInType(s)) #>
<#
index++;
}
if (index > maxfields)
maxfields = index;
#>
#define <#= String.Format("{0}_{1,-"+(padding - name.Length).ToString()+"} {2,2}", name, "Count", index) #>
#if !defined(SYSMON_EVENT_C)
extern SYSMON_EVENT_TYPE_FMT <#= name #>_Type;
#else
InTypes <#= name #>_type_list[] = {
<#
foreach(XmlNode s in sub) {
#>
I_<#= GetInType(s) #>,
<#
}
#>
};
PTCHAR <#= name #>_FieldNames[] = {
<#
foreach(XmlNode s in sub) {
#>
_T("<#= s.Attributes["name"].Value #>"),
<#
}
#>
};
ULONG <#= name #>_FieldHashes[] = {
<#
foreach(XmlNode s in sub) {
// GetHashCode is not documented, check that each value is unique per string.
// Aka no collision.
string k = s.Attributes["name"].Value;
int hashCode = k.GetHashCode();
if (fieldHashDict.ContainsKey(k) && fieldHashDict[k] != hashCode) {
throw new Exception("Two fields with same string and different hashCode");
}
fieldHashDict[k] = hashCode;
#>
0x<#= Convert.ToString(hashCode, 16) #>,
<#
}
#>
};
SYSMON_EVENT_TYPE_FMT <#= name #>_Type = {
<#= name #>_Count,
#if !defined(SYSMON_DRIVER)
<#= name #>,
&<#= name #>_EVENT,
#else
0,
NULL,
#endif
<#= id #>,
_T("<#= name #>"),
_T("<#= e.Attributes["template"].Value #>"),
<#= name #>_type_list,
<#= name #>_FieldNames,
<#
if (timeField) {
#>
<#= accro #>_UtcTime,
<#
} else {
#>
NO_FIELD,
<#
}
if (e.Attributes["rulename"] != null) {
#>
_T("<#= e.Attributes["rulename"].Value #>"),
<#
} else {
#>
NULL,
<#
}
if (e.Attributes["ruledefault"] != null) {
#>
Rule_<#= e.Attributes["ruledefault"].Value #>,
<#
} else {
#>
Rule_exclude,
<#
}
#>
<#= name #>_FieldHashes
};
#endif
<#
if (i != "") {
#>
#endif
<#
}
}
#>
#define SYSMON_MAX_EVENT_Fields <#= maxfields #>
#define SYSMON_MAX_EVENT_ID <#= maxid #>
#define V_MAJOR(_x) ((_x >> 16) & 0xFFFF)
#define V_MINOR(_x) (_x & 0xFFFF)
#define TO_DOUBLE(_x) ((double)(V_MAJOR(_x)*1.0)+(V_MINOR(_x)*0.01))
#if !defined(SYSMON_EVENT_C)
extern PTCHAR ConfigurationDtdRule;
extern SYSMON_EVENT_TYPE_FMT* AllEvents[];
extern SIZE_T AllEventsCount;
extern PSYSMON_EVENT_TYPE_FMT EventTypesById[];
extern SIZE_T EventTypesByIdCount;
extern const ULONG ConfigurationVersion;
extern const ULONG BinaryVersion;
PTCHAR GetDtdFormat( ULONG version );
#define IsCompatibleVersion(_x) \
(V_MAJOR(_x) == V_MAJOR(ConfigurationVersion))
#define IsCompatibleBinaryVersion(_x) \
(V_MAJOR(_x) == V_MAJOR(BinaryVersion))
#else
SYSMON_EVENT_TYPE_FMT* AllEvents[] = {
<#
foreach (XmlNode e in eventNodes)
{
var i = OutputIfDef(e);
if (i != "") {
#>
#if <#= i #>
<#
}
#>
&<#= e.Attributes["name"].Value #>_Type,
<#
if (i != "") {
#>
#endif
<#
}
}
#>
};
SIZE_T AllEventsCount = _countof(AllEvents);
PSYSMON_EVENT_TYPE_FMT EventTypesById[] = {
<#
for (int i = 0; i <= maxid; i++) {
string val = "NULL";
if (eventIdTableDict.ContainsKey(i)) {
val = "&" + eventIdTableDict[i] + "_Type";
}
#>
<#= val #>, // <#= i #>
<#
}
#>
};
SIZE_T EventTypesByIdCount = _countof(EventTypesById);
const ULONG ConfigurationVersion = <#= TransformVersion(highest) #>;
const ULONG BinaryVersion = <#= TransformVersion(highestBinary) #>;
PTCHAR
GetDtdFormat(
ULONG version
)
{
PTCHAR ConfigurationDtdRule = NULL;
<#
var items = from pair in manDict orderby pair.Key descending select pair;
var filterStrs = new List<string>();
var configurationOptions = new Dictionary<string,string>();
var configurationSwitches = new Dictionary<string,string>();
var configurationCmdLineOnly = new Dictionary<string,string>();
var configurationExclusive = new Dictionary<string,string>();
var configurationOnRule = new Dictionary<string,string>();
var configurationIfDef = new Dictionary<string,string>();
string defaultFilter = "";
var nodePerRuleName = new Dictionary<string,XmlNode>();
foreach (XmlNode en in eventNodes) {
if (en.Attributes["rulename"] == null) { continue; }
nodePerRuleName[en.Attributes["rulename"].Value] = en;
}
//
// Ensure that the filter options identifiers used in the
// rule binary format are consitent. To do that, create the
// the list of identifiers starting backward.
//
foreach (var manEntry in items.Reverse()) {
XmlNode m = manEntry.Value;
var fnode = m.SelectSingleNode(@".//filters");
// Ensure consistency from binary version from 14.0.
var b = double.Parse(m.Attributes["binaryversion"].Value);
if (b < 14.0) {
continue;
}
var l = fnode.InnerText.Split(',');
foreach(string t in l) {
if (filterStrs.Contains(t)) { continue; }
filterStrs.Add(t);
}
}
foreach (var manEntry in items) {
var ver = manEntry.Key;
XmlNode m = manEntry.Value;
if (ver < highest && ver < highestBase) {
continue;
}
eventNodes = m.SelectNodes(@".//event");
//
// Check if it is compatible with the base event nodes
//
foreach (XmlNode en in eventNodes) {
if (en.Attributes["rulename"] == null) { continue; }
string rn = en.Attributes["rulename"].Value;
if (!nodePerRuleName.ContainsKey(rn))
throw new Exception("Base does not contain rule named: "+rn);
XmlNode b = nodePerRuleName[rn];
if (((en.Attributes["ruledefault"] != null) != (b.Attributes["ruledefault"] != null)) ||
(en.Attributes["ruledefault"] != null && en.Attributes["ruledefault"].Value != b.Attributes["ruledefault"].Value))
throw new Exception("Different rule default for "+rn);
XmlNodeList b_sub = b.SelectNodes(@".//data");
XmlNodeList sub = en.SelectNodes(@".//data");
/*
if (sub.Count > b_sub.Count)
{
//throw new Exception("More fields in the older type for rule: "+rn);
Console.WriteLine("Warning skip checking "+rn+" due to less elements in new version");
continue;
}
*/
int diff = 0;
for(int index = 0; index < sub.Count; index++) {
var sub_item = sub.Item(index);
var b_sub_item = b_sub.Item(index-diff);
if (b_sub_item.Attributes["name"].Value != sub_item.Attributes["name"].Value)
{
Console.WriteLine("Warning skip check of "+sub_item.Attributes["name"].Value+" due to misalignment");
diff += 1;
continue;
}
if (sub_item.OuterXml != b_sub_item.OuterXml)
throw new Exception("Incompatible rule '"+rn+"' for field '"+sub_item.Attributes["name"].Value+"'");
}
}
string cmp = ">=";
string elseornot = "} else ";
if (ver == highest) {
cmp = "==";
elseornot = "";
}
#>
<#= elseornot #>if( version <#= cmp#> <#= TransformVersion(ver) #> ) {
<#
Dictionary<string, XmlNode> ruleOptions = new Dictionary<string, XmlNode>();
DElement root = new DElement("Sysmon");
root.children.Add(new DAttr("schemaversion", "CDATA #REQUIRED"));
DElement eventFilter = new DElement("EventFiltering");
root.children.Add(eventFilter);
DElement ruleGroup = new DElement("RuleGroup");
ruleGroup.children.Add(new DAttr("groupRelation", "(and|or) #REQUIRED"));
ruleGroup.children.Add(new DAttr("name", "CDATA #IMPLIED"));
eventFilter.children.Add(ruleGroup);
XmlNodeList optionNodes = m.SelectNodes(@".//option");
foreach (XmlNode o in optionNodes)
{
bool isRule = false;
var n = o.Attributes["name"].Value;
if (o.Attributes["rule"] != null && o.Attributes["rule"].Value.ToLower() == "true")
{
ruleOptions[n] = o;
isRule = true;
}
string val = "(#PCDATA)";
//
// Identify incompatibility across options
//
string co_value = "";
if (o.Attributes["argument"] == null || o.Attributes["argument"].Value == "none") {
val = "EMPTY";
co_value = "ConfigNoValue";
} else if (o.Attributes["argument"].Value == "optional") {
co_value = "ConfigValueOptional";
} else if (o.Attributes["argument"].Value == "required") {
co_value = "ConfigValueRequired";
} else {
throw new Exception("Unknown argument: "+o.Attributes["argument"].Value);
}
if (configurationOptions.ContainsKey(n)) {
if (configurationOptions[n] != co_value)
throw new Exception("(1) Invalid configuration change, not supported with current configuration design for: "+n + "option: "+configurationOptions[n] + " val: "+ co_value);
} else {
configurationOptions[n] = co_value;
}
string co_switch = "";
if (o.Attributes["switch"] == null || o.Attributes["switch"].Value == "") {
co_switch = "NULL";
} else if (o.Attributes["switch"].Value.Length != 0) {
co_switch = "_T(\""+o.Attributes["switch"].Value+"\")";
} else {
throw new Exception("Incorrect switch: "+o.Attributes["switch"].Value);
}
if (co_switch != "NULL" && configurationSwitches.ContainsKey(n)) {
if (configurationSwitches[n] != co_switch)
throw new Exception("(2) Invalid configuration change, not supported with current configuration design for: "+n +" switch:" + co_switch);
} else {
configurationSwitches[n] = co_switch;
}
string excl = "FALSE";
if (o.Attributes["exclusive"] != null && o.Attributes["exclusive"].Value == "true") {
excl = "TRUE";
}
if (configurationExclusive.ContainsKey(n)) {
if (configurationExclusive[n] != excl)
throw new Exception("(3) Invalid configuration change, not supported with current configuration design for: "+n);
} else {
configurationExclusive[n] = excl;
}
var onrule = "FALSE";
if (isRule) {
onrule = "TRUE";
}
if (configurationOnRule.ContainsKey(n)) {
if (configurationOnRule[n] != onrule)
throw new Exception("(4) Invalid configuration change, not supported with current configuration design for: "+n);
} else {
configurationOnRule[n] = onrule;
}
string cmdlineonly = "FALSE";
if (o.Attributes["noconfig"] != null && o.Attributes["noconfig"].Value == "true") {
cmdlineonly = "TRUE";
}
if (configurationCmdLineOnly.ContainsKey(n)) {
if (configurationCmdLineOnly[n] != cmdlineonly)
throw new Exception("(5) Invalid configuration change, not supported with current configuration design for: "+n);
} else {
configurationCmdLineOnly[n] = cmdlineonly;
}
var i = OutputIfDef(o);
if (configurationIfDef.ContainsKey(i)) {
if (configurationIfDef[n] != i)
throw new Exception("(6) Invalid configuration change, not supported with current configuration design for: "+n);
} else {
configurationIfDef[n] = i;
}
if (cmdlineonly != "TRUE")
{
if (!isRule)
{
root.children.Add(new DElement(n, val, o));
}
else if(o.Attributes["forceconfig"] != null && o.Attributes["forceconfig"].Value == "true")
{
root.children.Add(new DElement(n+"Config", val, o));
}
}
}
DElement ruleType = new DElement("Rule");
ruleType.children.Add(new DAttr("groupRelation", "CDATA #IMPLIED"));
ruleType.children.Add(new DAttr("name", "CDATA #IMPLIED"));
foreach (XmlNode e in eventNodes)
{
if (e.Attributes["rulename"] == null) { continue; }
DElement current;
if (eventFilter.children.Any(item => item.name == e.Attributes["rulename"].Value)) {
current = (DElement)eventFilter.children.First(item => item.name == e.Attributes["rulename"].Value);
} else {
current = new DElement(e.Attributes["rulename"].Value, e);
current.children.Add(new DAttr("onmatch", "(include|exclude) #IMPLIED"));
current.children.Add(new DAttr("default", "(include|exclude) #IMPLIED"));
current.children.Add(ruleType);
eventFilter.children.Add(current);
ruleGroup.children.Add(current);
}
XmlNodeList sub = e.SelectNodes(@".//data");
var fnode = m.SelectSingleNode(@".//filters");
var f_def = fnode.Attributes["default"].Value;
if (defaultFilter != "" && defaultFilter != f_def ) {
throw new Exception("Incorrect default filter, should upgrade major?");
}
defaultFilter = f_def;
foreach(XmlNode s in sub)
{
DElement dataElement = new DElement(s.Attributes["name"].Value);
dataElement.children.Add(new DAttr("condition", String.Format("CDATA \"{0}\"", f_def)));
dataElement.children.Add(new DAttr("name", "CDATA #IMPLIED"));
if (!current.children.Any(item => item.name == s.Attributes["name"].Value)) {
current.children.Add(dataElement);
ruleType.children.Add(dataElement);
}
}
}
string pad = " ";
string padComment = " // ";
foreach (string target in DObject.possibleTargets)
{
#>
#if <#= OutputIfDefFromTarget(target) #> && !defined(DTD_VER_<#= TransformVersion(ver) #>)
#define DTD_VER_<#= TransformVersion(ver) #>
// Comment for testing the dtd unprocessed (for <#=target#>):
// <!DOCTYPE Sysmon [
<#= FormatDtd(root, target, padComment, false) #>
// ]>
ConfigurationDtdRule = _T("<!DOCTYPE Sysmon [")
<#= FormatDtd(root, target, pad) #>
_T("]>\n");
#endif
<#
}
}
#>
} else {
#if !defined(SYSMON_DRIVER)
_tprintf( _T("Error: Incorrect or unsupported schema version %.2f. Current Sysmon schema version %.2f\n\n"),
TO_DOUBLE(version), TO_DOUBLE(ConfigurationVersion));
#endif
}
return ConfigurationDtdRule;
}
#endif
//
// Filter options
// Part of the format, always add new entries at the end of the list in the template.
//
<#
filterStrs = filterStrs.ToList();
#>
typedef enum {
<#
foreach (string f in filterStrs) {
#>
<#= ToFitlerName(f) #>,
<#
}
#>
// As the compiler sizes enums according to the size of the values within them,
// the inclusion of a 32 bit value will size the enum to 32 bits, and the
// inclusion of a negative value will make the enum signed.
//
// On Windows, positive values >= 0x80000000 (but <= 0xffffffff) will be treated
// as negative values and the enum will remain as a signed 32 bit value. On Linux,
// however, such values will cause the enum to be expanded to a signed 64 bit value.
//
// The ramification is that the internal representation of the rules will change
// due to the expansion of each filter struct by 4 bytes.
//
// As such, please don't use values >= 0x80000000 (unless absolutely necessary)
// to maintain cross-platform compatibility of internal representations, which is
// tested by the unit tests.
//
// Environment variables need to be expanded, set on rule loading.
Filter_Environment = 0x40000000,
Filter_Unknown = -1
} FilterOption;
#define FilterValue(_x) (_x & 0xFFFF)
#if !defined(SYSMON_EVENT_C) && !defined(SYSMON_DRIVER)
FilterOption
GetFilterOption(
const char *value
);
PTCHAR
GetFilterName(
FilterOption value
);
RuleDefaultType
GetRuleDefault(
const char *value
);
PTCHAR
GetRuleDefaultName(
RuleDefaultType value
);
RuleDefaultType
GetRuleMatch(
const char *value
);
PTCHAR
GetRuleMatchName(
RuleDefaultType value
);
#define SYSMON_FILTER_CONDITIONS _T("<#= String.Join(", ", filterStrs) #>")
#elif !defined(SYSMON_DRIVER)
FilterOption
GetFilterOption(
const char *value
)
{
if( value == NULL || *value == 0 ) {
return <#= ToFitlerName(defaultFilter) #>;
}<#
foreach (string f in filterStrs) {
#> else if( 0 == STRCASECMP( value, "<#= f #>" ) ) {
return <#= ToFitlerName(f) #>;
}<#
}
#>
return Filter_Unknown;
}
PTCHAR
GetFilterName(
FilterOption value
)
{
switch( value ) {
<#
foreach (string f in filterStrs) {
#> case <#= ToFitlerName(f) #>:
return _T("<#= f #>");
<#
}
#>
default:
return _T("<#= defaultFilter #>");
}
}
RuleDefaultType
GetRuleDefault(
const char *value
)
{
if( value == NULL ) {
return Rule_Unknown;
}
// It is inverted due to change in configuration files
if( 0 == STRCASECMP( value, "include" ) ) {
return Rule_include;
} else if( 0 == STRCASECMP( value, "exclude" ) ) {
return Rule_exclude;
}
return Rule_Unknown;
}
PTCHAR
GetRuleDefaultName(
RuleDefaultType value
)
{
switch( value ) {
case Rule_include:
return _T("include");
case Rule_exclude:
return _T("exclude");
default:
return _T("?");
}
}
RuleDefaultType
GetRuleMatch(
const char *value
)
{
if( value == NULL ) {
return Rule_Unknown;
}
// It is inverted due to change in configuration files
if( 0 == STRCASECMP( value, "exclude" ) ) {
return Rule_include;
} else if( 0 == STRCASECMP( value, "include" ) ) {
return Rule_exclude;
}
return Rule_Unknown;
}
PTCHAR
GetRuleMatchName(
RuleDefaultType value
)
{
switch( value ) {
case Rule_include:
return _T("exclude");
case Rule_exclude:
return _T("include");
default:
return _T("?");
}
}
<#
filterStrs = filterStrs.Distinct().ToList();
#>
#endif
//
// Rules structures
//
#pragma pack(push)
#pragma pack(1)
typedef struct _RULE_AGGREGATION
{
WCHAR name[128]; // Optional name.
ULONG64 messageId; // Event sequence number. Used for event correlation during rule matching
ULONG aggregationId; // One up correlation ID for matching filter rules
ULONG rootRuleOffset; // Offset for the first filter rule in the chain
ULONG nextOffset; // Offset for next aggreation item in the chain
ULONG ruleCount; // The number of rules in this aggregation
RuleCombineType combineType; // How the rules are combined
ULONG rulesChecked; // used by matching routine to record how many filters have been checked
ULONG rulesMatched; // used by matching routine to record how many filters have been checked
} RULE_AGGREGATION, *PRULE_AGGREGATION;
typedef struct _RULE_FILTER
{
ULONG FieldId;
WCHAR Name[256];
FilterOption FilterType;
ULONG NextOffset;
ULONG DataSize;
ULONG AggregationId; // Aggregation ID if this is part of a <Rule>
ULONG AggregationOffset; // Offset to the RULE_AGGREGATION if this is a <Rule>
UCHAR Data[ANYSIZE_ARRAY];
} RULE_FILTER, *PRULE_FILTER;
typedef struct _RULE_EVENT
{
ULONG EventId;
RuleDefaultType RuleDefault;
RuleCombineType CombineType;
ULONG NextOffset;
ULONG FilterCount;
ULONG FirstFilterOffset; // Offset of the first RULE_FILTER for this event instance
} RULE_EVENT, *PRULE_EVENT;
typedef struct _RULE_REG
{
ULONG Version;
ULONG RuleCount;
} RULE_REG, *PRULE_REG;
typedef struct _RULE_REG_EXT
{
RULE_REG header;
ULONG RuleRegSize;
ULONG SchemaVersion;
ULONG FirstEventOffset; // Offset of the first RULE_EVENT
ULONG FirstAggregationOffset; // Offset of the first RULE_AGGREGATION
} RULE_REG_EXT, *PRULE_REG_EXT;
#pragma pack(pop)
//
// Configuration structures
//
typedef struct _CONFIGURATION_OPTION
{
BOOLEAN IsSet;
PVOID Value;
ULONG Size;
BOOLEAN ValueAllocated;
} CONFIGURATION_OPTION, *PCONFIGURATION_OPTION;
typedef struct _CONFIGURATION_OPTIONS
{
<#
foreach (string k in configurationOptions.Keys)
{
var i = configurationIfDef[k];
if (i != "") {
#>
#if <#= i #>
<#
}
#>
CONFIGURATION_OPTION <#= k #>;
<#
if (i != "") {
#>
#endif
<#
}
}
#>
} CONFIGURATION_OPTIONS, *PCONFIGURATION_OPTIONS;
typedef enum {
ConfigNoValue,
ConfigValueRequired,
ConfigValueOptional,
} ConfigType;
typedef struct _CONFIGURATION_OPTION_TYPE
{
BOOLEAN CommandLineOnly;
BOOLEAN Exclusive;
BOOLEAN OnRule;
PTCHAR FieldName;
SIZE_T FieldNameCch;
PTCHAR Switch;
ConfigType ValueFlag;
PCONFIGURATION_OPTION Option;
} CONFIGURATION_OPTION_TYPE, *PCONFIGURATION_OPTION_TYPE;
#define OPT_DATA(_x) (ConfigOptions._x)
#define OPT_SET(_x) (OPT_DATA(_x).IsSet)
#define OPT_SIZE(_x) (OPT_DATA(_x).Size)