-
Notifications
You must be signed in to change notification settings - Fork 516
/
Copy pathrule.py
1632 lines (1296 loc) · 62.2 KB
/
rule.py
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 Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
# or more contributor license agreements. Licensed under the Elastic License
# 2.0; you may not use this file except in compliance with the Elastic License
# 2.0.
"""Rule object."""
import copy
import dataclasses
import json
import os
import re
import time
import typing
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from functools import cached_property
from pathlib import Path
from typing import Any, Dict, List, Literal, Optional, Tuple, Union
from urllib.parse import urlparse
from uuid import uuid4
import eql
import marshmallow
from semver import Version
from marko.block import Document as MarkoDocument
from marko.ext.gfm import gfm
from marshmallow import ValidationError, pre_load, validates_schema
import kql
from . import beats, ecs, endgame, utils
from .config import load_current_package_version, parse_rules_config
from .integrations import (find_least_compatible_version, get_integration_schema_fields,
load_integrations_manifests, load_integrations_schemas,
parse_datasets)
from .mixins import MarshmallowDataclassMixin, StackCompatMixin
from .rule_formatter import nested_normalize, toml_write
from .schemas import (SCHEMA_DIR, definitions, downgrade,
get_min_supported_stack_version, get_stack_schemas,
strip_non_public_fields)
from .schemas.stack_compat import get_restricted_fields
from .utils import PatchedTemplate, cached, convert_time_span, get_nested_value, set_nested_value
_META_SCHEMA_REQ_DEFAULTS = {}
MIN_FLEET_PACKAGE_VERSION = '7.13.0'
TIME_NOW = time.strftime('%Y/%m/%d')
RULES_CONFIG = parse_rules_config()
DEFAULT_PREBUILT_RULES_DIRS = RULES_CONFIG.rule_dirs
DEFAULT_PREBUILT_BBR_DIRS = RULES_CONFIG.bbr_rules_dirs
BYPASS_VERSION_LOCK = RULES_CONFIG.bypass_version_lock
BUILD_FIELD_VERSIONS = {
"related_integrations": (Version.parse('8.3.0'), None),
"required_fields": (Version.parse('8.3.0'), None),
"setup": (Version.parse('8.3.0'), None)
}
@dataclass
class DictRule:
"""Simple object wrapper for raw rule dicts."""
contents: dict
path: Optional[Path] = None
@property
def metadata(self) -> dict:
"""Metadata portion of TOML file rule."""
return self.contents.get('metadata', {})
@property
def data(self) -> dict:
"""Rule portion of TOML file rule."""
return self.contents.get('data') or self.contents
@property
def id(self) -> str:
"""Get the rule ID."""
return self.data['rule_id']
@property
def name(self) -> str:
"""Get the rule name."""
return self.data['name']
def __hash__(self) -> int:
"""Get the hash of the rule."""
return hash(self.id + self.name)
def __repr__(self) -> str:
"""Get a string representation of the rule."""
return f"Rule({self.name} {self.id})"
@dataclass(frozen=True)
class RuleMeta(MarshmallowDataclassMixin):
"""Data stored in a rule's [metadata] section of TOML."""
creation_date: definitions.Date
updated_date: definitions.Date
deprecation_date: Optional[definitions.Date]
# Optional fields
bypass_bbr_timing: Optional[bool]
comments: Optional[str]
integration: Optional[Union[str, List[str]]]
maturity: Optional[definitions.Maturity]
min_stack_version: Optional[definitions.SemVer]
min_stack_comments: Optional[str]
os_type_list: Optional[List[definitions.OSType]]
query_schema_validation: Optional[bool]
related_endpoint_rules: Optional[List[str]]
promotion: Optional[bool]
# Extended information as an arbitrary dictionary
extended: Optional[Dict[str, Any]]
def get_validation_stack_versions(self) -> Dict[str, dict]:
"""Get a dict of beats and ecs versions per stack release."""
stack_versions = get_stack_schemas(self.min_stack_version)
return stack_versions
@dataclass(frozen=True)
class RuleTransform(MarshmallowDataclassMixin):
"""Data stored in a rule's [transform] section of TOML."""
# note (investigation guides) Markdown plugins
# /elastic/kibana/tree/main/x-pack/plugins/security_solution/public/common/components/markdown_editor/plugins
##############################################
# timelines out of scope at the moment
@dataclass(frozen=True)
class OsQuery:
label: str
query: str
ecs_mapping: Optional[Dict[str, Dict[Literal['field', 'value'], str]]]
@dataclass(frozen=True)
class Investigate:
@dataclass(frozen=True)
class Provider:
excluded: bool
field: str
queryType: definitions.InvestigateProviderQueryType
value: str
valueType: definitions.InvestigateProviderValueType
label: str
description: Optional[str]
providers: List[List[Provider]]
relativeFrom: Optional[str]
relativeTo: Optional[str]
# these must be lists in order to have more than one. Their index in the list is how they will be referenced in the
# note string templates
osquery: Optional[List[OsQuery]]
investigate: Optional[List[Investigate]]
def render_investigate_osquery_to_string(self) -> Dict[definitions.TransformTypes, List[str]]:
obj = self.to_dict()
rendered: Dict[definitions.TransformTypes, List[str]] = {'osquery': [], 'investigate': []}
for plugin, entries in obj.items():
for entry in entries:
rendered[plugin].append(f'!{{{plugin}{json.dumps(entry, sort_keys=True, separators=(",", ":"))}}}')
return rendered
##############################################
@dataclass(frozen=True)
class BaseThreatEntry:
id: str
name: str
reference: str
@pre_load
def modify_url(self, data: Dict[str, Any], **kwargs):
"""Modify the URL to support MITRE ATT&CK URLS with and without trailing forward slash."""
if urlparse(data["reference"]).scheme:
if not data["reference"].endswith("/"):
data["reference"] += "/"
return data
@dataclass(frozen=True)
class SubTechnique(BaseThreatEntry):
"""Mapping to threat subtechnique."""
reference: definitions.SubTechniqueURL
@dataclass(frozen=True)
class Technique(BaseThreatEntry):
"""Mapping to threat subtechnique."""
# subtechniques are stored at threat[].technique.subtechnique[]
reference: definitions.TechniqueURL
subtechnique: Optional[List[SubTechnique]]
@dataclass(frozen=True)
class Tactic(BaseThreatEntry):
"""Mapping to a threat tactic."""
reference: definitions.TacticURL
@dataclass(frozen=True)
class ThreatMapping(MarshmallowDataclassMixin):
"""Mapping to a threat framework."""
framework: Literal["MITRE ATT&CK"]
tactic: Tactic
technique: Optional[List[Technique]]
@staticmethod
def flatten(threat_mappings: Optional[List]) -> 'FlatThreatMapping':
"""Get flat lists of tactic and technique info."""
tactic_names = []
tactic_ids = []
technique_ids = set()
technique_names = set()
sub_technique_ids = set()
sub_technique_names = set()
for entry in (threat_mappings or []):
tactic_names.append(entry.tactic.name)
tactic_ids.append(entry.tactic.id)
for technique in (entry.technique or []):
technique_names.add(technique.name)
technique_ids.add(technique.id)
for subtechnique in (technique.subtechnique or []):
sub_technique_ids.add(subtechnique.id)
sub_technique_names.add(subtechnique.name)
return FlatThreatMapping(
tactic_names=sorted(tactic_names),
tactic_ids=sorted(tactic_ids),
technique_names=sorted(technique_names),
technique_ids=sorted(technique_ids),
sub_technique_names=sorted(sub_technique_names),
sub_technique_ids=sorted(sub_technique_ids)
)
@dataclass(frozen=True)
class RiskScoreMapping(MarshmallowDataclassMixin):
field: str
operator: Optional[definitions.Operator]
value: Optional[str]
@dataclass(frozen=True)
class SeverityMapping(MarshmallowDataclassMixin):
field: str
operator: Optional[definitions.Operator]
value: Optional[str]
severity: Optional[str]
@dataclass(frozen=True)
class FlatThreatMapping(MarshmallowDataclassMixin):
tactic_names: List[str]
tactic_ids: List[str]
technique_names: List[str]
technique_ids: List[str]
sub_technique_names: List[str]
sub_technique_ids: List[str]
@dataclass(frozen=True)
class AlertSuppressionDuration:
"""Mapping to alert suppression duration."""
unit: definitions.TimeUnits
value: definitions.AlertSuppressionValue
@dataclass(frozen=True)
class AlertSuppressionMapping(MarshmallowDataclassMixin, StackCompatMixin):
"""Mapping to alert suppression."""
group_by: definitions.AlertSuppressionGroupBy
duration: Optional[AlertSuppressionDuration]
missing_fields_strategy: definitions.AlertSuppressionMissing
@dataclass(frozen=True)
class ThresholdAlertSuppression:
"""Mapping to alert suppression."""
duration: AlertSuppressionDuration
@dataclass(frozen=True)
class FilterStateStore:
store: definitions.StoreType
@dataclass(frozen=True)
class FilterMeta:
alias: Optional[Union[str, None]] = None
disabled: Optional[bool] = None
negate: Optional[bool] = None
controlledBy: Optional[str] = None # identify who owns the filter
group: Optional[str] = None # allows grouping of filters
index: Optional[str] = None
isMultiIndex: Optional[bool] = None
type: Optional[str] = None
key: Optional[str] = None
params: Optional[str] = None # Expand to FilterMetaParams when needed
value: Optional[str] = None
@dataclass(frozen=True)
class WildcardQuery:
case_insensitive: bool
value: str
@dataclass(frozen=True)
class Query:
wildcard: Optional[Dict[str, WildcardQuery]] = None
@dataclass(frozen=True)
class Filter:
"""Kibana Filter for Base Rule Data."""
# TODO: Currently unused in BaseRuleData. Revisit to extend or remove.
# https://github.com/elastic/detection-rules/issues/3773
meta: FilterMeta
state: Optional[FilterStateStore] = field(metadata=dict(data_key="$state"))
query: Optional[Union[Query, Dict[str, Any]]] = None
@dataclass(frozen=True)
class BaseRuleData(MarshmallowDataclassMixin, StackCompatMixin):
"""Base rule data."""
@dataclass
class InvestigationFields:
field_names: List[definitions.NonEmptyStr]
@dataclass
class RequiredFields:
name: definitions.NonEmptyStr
type: definitions.NonEmptyStr
ecs: bool
@dataclass
class RelatedIntegrations:
package: definitions.NonEmptyStr
version: definitions.NonEmptyStr
integration: Optional[definitions.NonEmptyStr]
actions: Optional[list]
author: List[str]
building_block_type: Optional[definitions.BuildingBlockType]
description: str
enabled: Optional[bool]
exceptions_list: Optional[list]
license: Optional[str]
false_positives: Optional[List[str]]
filters: Optional[List[dict]]
# trailing `_` required since `from` is a reserved word in python
from_: Optional[str] = field(metadata=dict(data_key="from"))
interval: Optional[definitions.Interval]
investigation_fields: Optional[InvestigationFields] = field(metadata=dict(metadata=dict(min_compat="8.11")))
max_signals: Optional[definitions.MaxSignals]
meta: Optional[Dict[str, Any]]
name: definitions.RuleName
note: Optional[definitions.Markdown]
# can we remove this comment?
# explicitly NOT allowed!
# output_index: Optional[str]
references: Optional[List[str]]
related_integrations: Optional[List[RelatedIntegrations]] = field(metadata=dict(metadata=dict(min_compat="8.3")))
required_fields: Optional[List[RequiredFields]] = field(metadata=dict(metadata=dict(min_compat="8.3")))
revision: Optional[int] = field(metadata=dict(metadata=dict(min_compat="8.8")))
risk_score: definitions.RiskScore
risk_score_mapping: Optional[List[RiskScoreMapping]]
rule_id: definitions.UUIDString
rule_name_override: Optional[str]
setup: Optional[definitions.Markdown] = field(metadata=dict(metadata=dict(min_compat="8.3")))
severity_mapping: Optional[List[SeverityMapping]]
severity: definitions.Severity
tags: Optional[List[str]]
throttle: Optional[str]
timeline_id: Optional[definitions.TimelineTemplateId]
timeline_title: Optional[definitions.TimelineTemplateTitle]
timestamp_override: Optional[str]
to: Optional[str]
type: definitions.RuleType
threat: Optional[List[ThreatMapping]]
version: Optional[definitions.PositiveInteger]
@classmethod
def save_schema(cls):
"""Save the schema as a jsonschema."""
fields: Tuple[dataclasses.Field, ...] = dataclasses.fields(cls)
type_field = next(f for f in fields if f.name == "type")
rule_type = typing.get_args(type_field.type)[0] if cls != BaseRuleData else "base"
schema = cls.jsonschema()
version_dir = SCHEMA_DIR / "master"
version_dir.mkdir(exist_ok=True, parents=True)
# expand out the jsonschema definitions
with (version_dir / f"master.{rule_type}.json").open("w") as f:
json.dump(schema, f, indent=2, sort_keys=True)
def validate_query(self, meta: RuleMeta) -> None:
pass
@cached_property
def get_restricted_fields(self) -> Optional[Dict[str, tuple]]:
"""Get stack version restricted fields."""
fields: List[dataclasses.Field, ...] = list(dataclasses.fields(self))
return get_restricted_fields(fields)
@cached_property
def data_validator(self) -> Optional['DataValidator']:
return DataValidator(is_elastic_rule=self.is_elastic_rule, **self.to_dict())
@cached_property
def notify(self) -> bool:
return os.environ.get('DR_NOTIFY_INTEGRATION_UPDATE_AVAILABLE') is not None
@cached_property
def parsed_note(self) -> Optional[MarkoDocument]:
dv = self.data_validator
if dv:
return dv.parsed_note
@property
def is_elastic_rule(self):
return 'elastic' in [a.lower() for a in self.author]
def get_build_fields(self) -> {}:
"""Get a list of build-time fields along with the stack versions which they will build within."""
build_fields = {}
rule_fields = {f.name: f for f in dataclasses.fields(self)}
for fld in BUILD_FIELD_VERSIONS:
if fld in rule_fields:
build_fields[fld] = BUILD_FIELD_VERSIONS[fld]
return build_fields
@classmethod
def process_transforms(cls, transform: RuleTransform, obj: dict) -> dict:
"""Process transforms from toml [transform] called in TOMLRuleContents.to_dict."""
# only create functions that CAREFULLY mutate the obj dict
def process_note_plugins():
"""Format the note field with osquery and investigate plugin strings."""
note = obj.get('note')
if not note:
return
rendered = transform.render_investigate_osquery_to_string()
rendered_patterns = {}
for plugin, entries in rendered.items():
rendered_patterns.update(**{f'{plugin}_{i}': e for i, e in enumerate(entries)})
note_template = PatchedTemplate(note)
rendered_note = note_template.safe_substitute(**rendered_patterns)
obj['note'] = rendered_note
# call transform functions
if transform:
process_note_plugins()
return obj
@validates_schema
def validates_data(self, data, **kwargs):
"""Validate fields and data for marshmallow schemas."""
# Validate version and revision fields not supplied.
disallowed_fields = [field for field in ['version', 'revision'] if data.get(field) is not None]
if not disallowed_fields:
return
error_message = " and ".join(disallowed_fields)
# If version and revision fields are supplied, and using locked versions raise an error.
if BYPASS_VERSION_LOCK is not True:
msg = (f"Configuration error: Rule {data['name']} - {data['rule_id']} "
f"should not contain rules with `{error_message}` set.")
raise ValidationError(msg)
class DataValidator:
"""Additional validation beyond base marshmallow schema validation."""
def __init__(self,
name: definitions.RuleName,
is_elastic_rule: bool,
note: Optional[definitions.Markdown] = None,
interval: Optional[definitions.Interval] = None,
building_block_type: Optional[definitions.BuildingBlockType] = None,
setup: Optional[str] = None,
**extras):
# only define fields needing additional validation
self.name = name
self.is_elastic_rule = is_elastic_rule
self.note = note
# Need to use extras because from is a reserved word in python
self.from_ = extras.get('from')
self.interval = interval
self.building_block_type = building_block_type
self.setup = setup
self._setup_in_note = False
@cached_property
def parsed_note(self) -> Optional[MarkoDocument]:
if self.note:
return gfm.parse(self.note)
@property
def setup_in_note(self):
return self._setup_in_note
@setup_in_note.setter
def setup_in_note(self, value: bool):
self._setup_in_note = value
@cached_property
def skip_validate_note(self) -> bool:
return os.environ.get('DR_BYPASS_NOTE_VALIDATION_AND_PARSE') is not None
@cached_property
def skip_validate_bbr(self) -> bool:
return os.environ.get('DR_BYPASS_BBR_LOOKBACK_VALIDATION') is not None
def validate_bbr(self, bypass: bool = False):
"""Validate building block type and rule type."""
if self.skip_validate_bbr or bypass:
return
def validate_lookback(str_time: str) -> bool:
"""Validate that the time is at least now-119m and at least 60m respectively."""
try:
if "now-" in str_time:
str_time = str_time[4:]
time = convert_time_span(str_time)
# if from time is less than 119m as milliseconds
if time < 119 * 60 * 1000:
return False
else:
return False
except Exception as e:
raise ValidationError(f"Invalid time format: {e}")
return True
def validate_interval(str_time: str) -> bool:
"""Validate that the time is at least now-119m and at least 60m respectively."""
try:
time = convert_time_span(str_time)
# if interval time is less than 60m as milliseconds
if time < 60 * 60 * 1000:
return False
except Exception as e:
raise ValidationError(f"Invalid time format: {e}")
return True
bypass_instructions = "To bypass, use the environment variable `DR_BYPASS_BBR_LOOKBACK_VALIDATION`"
if self.building_block_type:
if not self.from_ or not self.interval:
raise ValidationError(
f"{self.name} is invalid."
"BBR require `from` and `interval` to be defined. "
"Please set or bypass." + bypass_instructions
)
elif not validate_lookback(self.from_) or not validate_interval(self.interval):
raise ValidationError(
f"{self.name} is invalid."
"Default BBR require `from` and `interval` to be at least now-119m and at least 60m respectively "
"(using the now-Xm and Xm format where x is in minuets). "
"Please update values or bypass. " + bypass_instructions
)
def validate_note(self):
if self.skip_validate_note or not self.note:
return
try:
for child in self.parsed_note.children:
if child.get_type() == "Heading":
header = gfm.renderer.render_children(child)
if header.lower() == "setup":
# check that the Setup header is correctly formatted at level 2
if child.level != 2:
raise ValidationError(f"Setup section with wrong header level: {child.level}")
# check that the Setup header is capitalized
if child.level == 2 and header != "Setup":
raise ValidationError(f"Setup header has improper casing: {header}")
self.setup_in_note = True
else:
# check that the header Config does not exist in the Setup section
if child.level == 2 and "config" in header.lower():
raise ValidationError(f"Setup header contains Config: {header}")
except Exception as e:
raise ValidationError(f"Invalid markdown in rule `{self.name}`: {e}. To bypass validation on the `note`"
f"field, use the environment variable `DR_BYPASS_NOTE_VALIDATION_AND_PARSE`")
# raise if setup header is in note and in setup
if self.setup_in_note and (self.setup and self.setup != "None"):
raise ValidationError("Setup header found in both note and setup fields.")
@dataclass
class QueryValidator:
query: str
@property
def ast(self) -> Any:
raise NotImplementedError()
@property
def unique_fields(self) -> Any:
raise NotImplementedError()
def validate(self, data: 'QueryRuleData', meta: RuleMeta) -> None:
raise NotImplementedError()
@cached
def get_required_fields(self, index: str) -> List[Optional[dict]]:
"""Retrieves fields needed for the query along with type information from the schema."""
if isinstance(self, ESQLValidator):
return []
current_version = Version.parse(load_current_package_version(), optional_minor_and_patch=True)
ecs_version = get_stack_schemas()[str(current_version)]['ecs']
beats_version = get_stack_schemas()[str(current_version)]['beats']
endgame_version = get_stack_schemas()[str(current_version)]['endgame']
ecs_schema = ecs.get_schema(ecs_version)
beat_types, beat_schema, schema = self.get_beats_schema(index or [], beats_version, ecs_version)
endgame_schema = self.get_endgame_schema(index or [], endgame_version)
# construct integration schemas
packages_manifest = load_integrations_manifests()
integrations_schemas = load_integrations_schemas()
datasets, _ = beats.get_datasets_and_modules(self.ast)
package_integrations = parse_datasets(datasets, packages_manifest)
int_schema = {}
data = {"notify": False}
for pk_int in package_integrations:
package = pk_int["package"]
integration = pk_int["integration"]
schema, _ = get_integration_schema_fields(integrations_schemas, package, integration,
current_version, packages_manifest, {}, data)
int_schema.update(schema)
required = []
unique_fields = self.unique_fields or []
for fld in unique_fields:
field_type = ecs_schema.get(fld, {}).get('type')
is_ecs = field_type is not None
if not is_ecs:
if int_schema:
field_type = int_schema.get(fld, None)
elif beat_schema:
field_type = beat_schema.get(fld, {}).get('type')
elif endgame_schema:
field_type = endgame_schema.endgame_schema.get(fld, None)
required.append(dict(name=fld, type=field_type or 'unknown', ecs=is_ecs))
return sorted(required, key=lambda f: f['name'])
@cached
def get_beats_schema(self, index: list, beats_version: str, ecs_version: str) -> (list, dict, dict):
"""Get an assembled beats schema."""
beat_types = beats.parse_beats_from_index(index)
beat_schema = beats.get_schema_from_kql(self.ast, beat_types, version=beats_version) if beat_types else None
schema = ecs.get_kql_schema(version=ecs_version, indexes=index, beat_schema=beat_schema)
return beat_types, beat_schema, schema
@cached
def get_endgame_schema(self, index: list, endgame_version: str) -> Optional[endgame.EndgameSchema]:
"""Get an assembled flat endgame schema."""
if index and "endgame-*" not in index:
return None
endgame_schema = endgame.read_endgame_schema(endgame_version=endgame_version)
return endgame.EndgameSchema(endgame_schema)
@dataclass(frozen=True)
class QueryRuleData(BaseRuleData):
"""Specific fields for query event types."""
type: Literal["query"]
index: Optional[List[str]]
data_view_id: Optional[str]
query: str
language: definitions.FilterLanguages
alert_suppression: Optional[AlertSuppressionMapping] = field(metadata=dict(metadata=dict(min_compat="8.8")))
@cached_property
def index_or_dataview(self) -> list[str]:
"""Return the index or dataview depending on which is set. If neither returns empty list."""
if self.index is not None:
return self.index
elif self.data_view_id is not None:
return [self.data_view_id]
else:
return []
@cached_property
def validator(self) -> Optional[QueryValidator]:
if self.language == "kuery":
return KQLValidator(self.query)
elif self.language == "eql":
return EQLValidator(self.query)
elif self.language == "esql":
return ESQLValidator(self.query)
def validate_query(self, meta: RuleMeta) -> None:
validator = self.validator
if validator is not None:
return validator.validate(self, meta)
@cached_property
def ast(self):
validator = self.validator
if validator is not None:
return validator.ast
@cached_property
def unique_fields(self):
validator = self.validator
if validator is not None:
return validator.unique_fields
@cached
def get_required_fields(self, index: str) -> List[dict]:
validator = self.validator
if validator is not None:
return validator.get_required_fields(index or [])
@validates_schema
def validates_index_and_data_view_id(self, data, **kwargs):
"""Validate that either index or data_view_id is set, but not both."""
if data.get('index') and data.get('data_view_id'):
raise ValidationError("Only one of index or data_view_id should be set.")
@dataclass(frozen=True)
class MachineLearningRuleData(BaseRuleData):
type: Literal["machine_learning"]
anomaly_threshold: int
machine_learning_job_id: Union[str, List[str]]
alert_suppression: Optional[AlertSuppressionMapping] = field(metadata=dict(metadata=dict(min_compat="8.15")))
@dataclass(frozen=True)
class ThresholdQueryRuleData(QueryRuleData):
"""Specific fields for query event types."""
@dataclass(frozen=True)
class ThresholdMapping(MarshmallowDataclassMixin):
@dataclass(frozen=True)
class ThresholdCardinality:
field: str
value: definitions.ThresholdValue
field: definitions.CardinalityFields
value: definitions.ThresholdValue
cardinality: Optional[List[ThresholdCardinality]]
type: Literal["threshold"]
threshold: ThresholdMapping
alert_suppression: Optional[ThresholdAlertSuppression] = field(metadata=dict(metadata=dict(min_compat="8.12")))
@dataclass(frozen=True)
class NewTermsRuleData(QueryRuleData):
"""Specific fields for new terms field rule."""
@dataclass(frozen=True)
class NewTermsMapping(MarshmallowDataclassMixin):
@dataclass(frozen=True)
class HistoryWindowStart:
field: definitions.NonEmptyStr
value: definitions.NonEmptyStr
field: definitions.NonEmptyStr
value: definitions.NewTermsFields
history_window_start: List[HistoryWindowStart]
type: Literal["new_terms"]
new_terms: NewTermsMapping
alert_suppression: Optional[AlertSuppressionMapping] = field(metadata=dict(metadata=dict(min_compat="8.14")))
@pre_load
def preload_data(self, data: dict, **kwargs) -> dict:
"""Preloads and formats the data to match the required schema."""
if "new_terms_fields" in data and "history_window_start" in data:
new_terms_mapping = {
"field": "new_terms_fields",
"value": data["new_terms_fields"],
"history_window_start": [
{
"field": "history_window_start",
"value": data["history_window_start"]
}
]
}
data["new_terms"] = new_terms_mapping
# cleanup original fields after building into our toml format
data.pop("new_terms_fields")
data.pop("history_window_start")
return data
def transform(self, obj: dict) -> dict:
"""Transforms new terms data to API format for Kibana."""
obj[obj["new_terms"].get("field")] = obj["new_terms"].get("value")
obj["history_window_start"] = obj["new_terms"]["history_window_start"][0].get("value")
del obj["new_terms"]
return obj
@dataclass(frozen=True)
class EQLRuleData(QueryRuleData):
"""EQL rules are a special case of query rules."""
type: Literal["eql"]
language: Literal["eql"]
timestamp_field: Optional[str] = field(metadata=dict(metadata=dict(min_compat="8.0")))
event_category_override: Optional[str] = field(metadata=dict(metadata=dict(min_compat="8.0")))
tiebreaker_field: Optional[str] = field(metadata=dict(metadata=dict(min_compat="8.0")))
alert_suppression: Optional[AlertSuppressionMapping] = field(metadata=dict(metadata=dict(min_compat="8.14")))
def convert_relative_delta(self, lookback: str) -> int:
now = len("now")
min_length = now + len('+5m')
if lookback.startswith("now") and len(lookback) >= min_length:
lookback = lookback[len("now"):]
sign = lookback[0] # + or -
span = lookback[1:]
amount = convert_time_span(span)
return amount * (-1 if sign == "-" else 1)
else:
return convert_time_span(lookback)
@cached_property
def is_sample(self) -> bool:
"""Checks if the current rule is a sample-based rule."""
return eql.utils.get_query_type(self.ast) == 'sample'
@cached_property
def is_sequence(self) -> bool:
"""Checks if the current rule is a sequence-based rule."""
return eql.utils.get_query_type(self.ast) == 'sequence'
@cached_property
def max_span(self) -> Optional[int]:
"""Maxspan value for sequence rules if defined."""
if self.is_sequence and hasattr(self.ast.first, 'max_span'):
return self.ast.first.max_span.as_milliseconds() if self.ast.first.max_span else None
@cached_property
def look_back(self) -> Optional[Union[int, Literal['unknown']]]:
"""Lookback value of a rule."""
# https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math
to = self.convert_relative_delta(self.to) if self.to else 0
from_ = self.convert_relative_delta(self.from_ or "now-6m")
if not (to or from_):
return 'unknown'
else:
return to - from_
@cached_property
def interval_ratio(self) -> Optional[float]:
"""Ratio of interval time window / max_span time window."""
if self.max_span:
interval = convert_time_span(self.interval or '5m')
return interval / self.max_span
@dataclass(frozen=True)
class ESQLRuleData(QueryRuleData):
"""ESQL rules are a special case of query rules."""
type: Literal["esql"]
language: Literal["esql"]
query: str
alert_suppression: Optional[AlertSuppressionMapping] = field(metadata=dict(metadata=dict(min_compat="8.15")))
@validates_schema
def validates_esql_data(self, data, **kwargs):
"""Custom validation for query rule type and subclasses."""
if data.get('index'):
raise ValidationError("Index is not a valid field for ES|QL rule type.")
# Convert the query string to lowercase to handle case insensitivity
query_lower = data['query'].lower()
# Combine both patterns using an OR operator and compile the regex
combined_pattern = re.compile(
r'(from\s+\S+\s+metadata\s+_id,\s*_version,\s*_index)|(\bstats\b.*?\bby\b)', re.DOTALL
)
# Ensure that non-aggregate queries have metadata
if not combined_pattern.search(query_lower):
raise ValidationError(
f"Rule: {data['name']} contains a non-aggregate query without"
f" metadata fields '_id', '_version', and '_index' ->"
f" Add 'metadata _id, _version, _index' to the from command or add an aggregate function."
)
# Enforce KEEP command for ESQL rules
if '| keep' not in query_lower:
raise ValidationError(
f"Rule: {data['name']} does not contain a 'keep' command ->"
f" Add a 'keep' command to the query."
)
@dataclass(frozen=True)
class ThreatMatchRuleData(QueryRuleData):
"""Specific fields for indicator (threat) match rule."""
@dataclass(frozen=True)
class Entries:
@dataclass(frozen=True)
class ThreatMapEntry:
field: definitions.NonEmptyStr
type: Literal["mapping"]
value: definitions.NonEmptyStr
entries: List[ThreatMapEntry]
type: Literal["threat_match"]
concurrent_searches: Optional[definitions.PositiveInteger]
items_per_search: Optional[definitions.PositiveInteger]
threat_mapping: List[Entries]
threat_filters: Optional[List[dict]]
threat_query: Optional[str]
threat_language: Optional[definitions.FilterLanguages]
threat_index: List[str]
threat_indicator_path: Optional[str]
alert_suppression: Optional[AlertSuppressionMapping] = field(metadata=dict(metadata=dict(min_compat="8.13")))
def validate_query(self, meta: RuleMeta) -> None:
super(ThreatMatchRuleData, self).validate_query(meta)
if self.threat_query:
if not self.threat_language:
raise ValidationError('`threat_language` required when a `threat_query` is defined')
if self.threat_language == "kuery":
threat_query_validator = KQLValidator(self.threat_query)
elif self.threat_language == "eql":
threat_query_validator = EQLValidator(self.threat_query)
else:
return
threat_query_validator.validate(self, meta)
# All of the possible rule types
# Sort inverse of any inheritance - see comment in TOMLRuleContents.to_dict
AnyRuleData = Union[EQLRuleData, ESQLRuleData, ThresholdQueryRuleData, ThreatMatchRuleData,
MachineLearningRuleData, QueryRuleData, NewTermsRuleData]
class BaseRuleContents(ABC):
"""Base contents object for shared methods between active and deprecated rules."""
@property
@abstractmethod
def id(self):
pass
@property
@abstractmethod
def name(self):
pass