-
Notifications
You must be signed in to change notification settings - Fork 635
Expand file tree
/
Copy pathtest_rules_remote.py
More file actions
330 lines (307 loc) · 17.6 KB
/
test_rules_remote.py
File metadata and controls
330 lines (307 loc) · 17.6 KB
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
# 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.
import unittest
from copy import deepcopy
import pytest
from detection_rules.esql_errors import (
EsqlSchemaError,
EsqlSemanticError,
EsqlSyntaxError,
EsqlTypeMismatchError,
EsqlUnknownIndexError,
)
from detection_rules.misc import (
get_default_config,
getdefault,
)
from detection_rules.rule_loader import RuleCollection
from detection_rules.utils import get_path, load_rule_contents
from .base import BaseRuleTest
@unittest.skipIf(get_default_config() is None, "Skipping remote validation due to missing config")
@unittest.skipIf(
not getdefault("remote_esql_validation")(), "Skipping remote validation because remote_esql_validation is False"
)
class TestRemoteRules(BaseRuleTest):
"""Test rules against a remote Elastic stack instance."""
def test_get_hashable_content_required_fields_popped_when_keep_star_used(self):
"""Hashable content must not contain required_fields when query uses keep * or field wildcards."""
file_path = get_path(["tests", "data", "command_control_dummy_production_rule.toml"])
original_production_rule = load_rule_contents(file_path)
production_rule = deepcopy(original_production_rule)[0]
# Non-aggregate queries must include _id, _version, _index in keep when keep is not exactly "*"
base = "from logs-aws.cloudtrail* metadata _id, _version, _index\n"
base += '| where event.action == "start"\n | eval Esql.entity_type = cloud.target.entity.type\n | keep '
keep_star_queries = [
base + "*",
base + "Esql.*, _id, _version, _index",
base + "host.name, Esql.*, _id, _version, _index",
base + "event.*, _id, _version, _index",
]
for query in keep_star_queries:
production_rule_copy = deepcopy(production_rule)
production_rule_copy["rule"]["query"] = query
rule = RuleCollection().load_dict(production_rule_copy)
hashable = rule.contents.get_hashable_content()
assert "required_fields" not in hashable, f"required_fields should be popped for keep-star query: {query!r}"
def test_get_hashable_content_required_fields_kept_when_no_keep_star(self):
"""Hashable content keeps required_fields when query uses explicit keep (no wildcards)."""
file_path = get_path(["tests", "data", "command_control_dummy_production_rule.toml"])
original_production_rule = load_rule_contents(file_path)
production_rule = deepcopy(original_production_rule)[0]
production_rule["rule"]["query"] = """
from logs-aws.cloudtrail* metadata _id, _version, _index
| where event.action == "start"
| keep _id, _version, _index
"""
rule = RuleCollection().load_dict(production_rule)
api = rule.contents.to_api_format()
hashable = rule.contents.get_hashable_content()
if "required_fields" in api:
assert "required_fields" in hashable, "required_fields must not be popped when keep has no wildcards"
def test_get_hashable_content_required_fields_kept_for_explicit_keep_only(self):
"""Hashable content keeps required_fields when keep lists only explicit fields."""
file_path = get_path(["tests", "data", "command_control_dummy_production_rule.toml"])
original_production_rule = load_rule_contents(file_path)
production_rule = deepcopy(original_production_rule)[0]
production_rule["rule"]["query"] = """
from logs-aws.cloudtrail* metadata _id, _version, _index
| where event.action == "start"
| keep host.name, user.name, _id, _version, _index
"""
rule = RuleCollection().load_dict(production_rule)
api = rule.contents.to_api_format()
hashable = rule.contents.get_hashable_content()
if "required_fields" in api:
assert "required_fields" in hashable
def test_esql_related_integrations(self):
"""Test an ESQL rule has its related integrations built correctly."""
file_path = get_path(["tests", "data", "command_control_dummy_production_rule.toml"])
original_production_rule = load_rule_contents(file_path)
production_rule = deepcopy(original_production_rule)[0]
production_rule["metadata"]["integration"] = ["aws"]
production_rule["rule"]["query"] = """
from logs-aws.cloudtrail* metadata _id, _version, _index
| where @timestamp > now() - 30 minutes
and event.dataset in ("aws.cloudtrail", "aws.billing")
and aws.cloudtrail.user_identity.arn is not null
and aws.cloudtrail.user_identity.type == "IAMUser"
| keep
aws.cloudtrail.user_identity.type, _id, _version, _index
"""
rule = RuleCollection().load_dict(production_rule)
related_integrations = rule.contents.to_api_format()["related_integrations"]
for integration in related_integrations:
assert integration["package"] == "aws", f"Expected 'aws', but got {integration['package']}"
def test_esql_non_dataset_package_related_integrations(self):
"""Test an ESQL rule has its related integrations built correctly with a non dataset package."""
file_path = get_path(["tests", "data", "command_control_dummy_production_rule.toml"])
original_production_rule = load_rule_contents(file_path)
production_rule = deepcopy(original_production_rule)[0]
production_rule["metadata"]["integration"] = ["aws_bedrock"]
production_rule["rule"]["query"] = """
from logs-aws_bedrock.invocation-* metadata _id, _version, _index
// Filter for access denied errors from GenAI responses
| where gen_ai.response.error_code == "AccessDeniedException"
// keep ECS and response fields
| keep
user.id,
gen_ai.request.model.id,
cloud.account.id,
gen_ai.response.error_code, _id, _version, _index
"""
rule = RuleCollection().load_dict(production_rule)
related_integrations = rule.contents.to_api_format()["related_integrations"]
for integration in related_integrations:
assert integration["package"] == "aws_bedrock", f"Expected 'aws_bedrock', but got {integration['package']}"
def test_esql_event_dataset_schema_error(self):
"""Test an ESQL rule that uses event.dataset field in the query that restricts the schema failing validation."""
file_path = get_path(["tests", "data", "command_control_dummy_production_rule.toml"])
original_production_rule = load_rule_contents(file_path)
# Test that a ValidationError is raised if the query doesn't match the schema
production_rule = deepcopy(original_production_rule)[0]
del production_rule["metadata"]["integration"]
production_rule["rule"]["query"] = """
from logs-aws.cloudtrail* metadata _id, _version, _index
| where @timestamp > now() - 30 minutes
and event.dataset in ("aws.billing")
and aws.cloudtrail.user_identity.type == "IAMUser"
| keep
aws.cloudtrail.user_identity.type, _id, _version, _index
"""
with pytest.raises(EsqlSchemaError):
_ = RuleCollection().load_dict(production_rule)
def test_esql_type_mismatch_error(self):
"""Test an ESQL rule that produces a type error comparing a keyword to a number."""
file_path = get_path(["tests", "data", "command_control_dummy_production_rule.toml"])
original_production_rule = load_rule_contents(file_path)
# Test that a ValidationError is raised if the query doesn't match the schema
production_rule = deepcopy(original_production_rule)[0]
production_rule["metadata"]["integration"] = ["aws"]
production_rule["rule"]["query"] = """
from logs-aws.cloudtrail* metadata _id, _version, _index
| where @timestamp > now() - 30 minutes
and event.dataset in ("aws.cloudtrail", "aws.billing")
and aws.cloudtrail.user_identity.type == 5
| keep
aws.cloudtrail.user_identity.type, _id, _version, _index
"""
with pytest.raises(EsqlTypeMismatchError):
_ = RuleCollection().load_dict(production_rule)
def test_esql_syntax_error(self):
"""Test an ESQL rule that incorrectly using = for comparison."""
file_path = get_path(["tests", "data", "command_control_dummy_production_rule.toml"])
original_production_rule = load_rule_contents(file_path)
# Test that a ValidationError is raised if the query doesn't match the schema
production_rule = deepcopy(original_production_rule)[0]
production_rule["metadata"]["integration"] = ["aws"]
production_rule["rule"]["query"] = """
from logs-aws.cloudtrail* metadata _id, _version, _index
| where @timestamp > now() - 30 minutes
and event.dataset in ("aws.cloudtrail", "aws.billing")
and aws.cloudtrail.user_identity.type = "IAMUser"
| keep
aws.cloudtrail.user_identity.type, _id, _version, _index
"""
with pytest.raises(EsqlSyntaxError):
_ = RuleCollection().load_dict(production_rule)
def test_esql_filtered_index(self):
"""Test an ESQL rule's schema validation to properly reduce it by the index and handle implicit fields."""
file_path = get_path(["tests", "data", "command_control_dummy_production_rule.toml"])
original_production_rule = load_rule_contents(file_path)
# Test that a ValidationError is raised if the query doesn't match the schema
production_rule = deepcopy(original_production_rule)[0]
production_rule["metadata"]["integration"] = ["aws"]
production_rule["rule"]["query"] = """
from logs-aws.cloud* metadata _id, _version, _index
| where @timestamp > now() - 30 minutes
and aws.cloudtrail.user_identity.type == "IAMUser"
| keep
aws.*, _id, _version, _index
"""
_ = RuleCollection().load_dict(production_rule)
def test_esql_filtered_index_error(self):
"""Test an ESQL rule's schema validation when reduced by the index and check if the field is present."""
file_path = get_path(["tests", "data", "command_control_dummy_production_rule.toml"])
original_production_rule = load_rule_contents(file_path)
# Test that a ValidationError is raised if the query doesn't match the schema
production_rule = deepcopy(original_production_rule)[0]
production_rule["metadata"]["integration"] = ["aws"]
production_rule["rule"]["query"] = """
from logs-aws.billing* metadata _id, _version, _index
| where @timestamp > now() - 30 minutes
and aws.cloudtrail.user_identity.type == "IAMUser"
| keep
aws.cloudtrail.user_identity.type, _id, _version, _index
"""
with pytest.raises(EsqlSchemaError):
_ = RuleCollection().load_dict(production_rule)
def test_new_line_split_index(self):
"""Test an ESQL rule's index validation to ensure that it can handle new line split indices."""
file_path = get_path(["tests", "data", "command_control_dummy_production_rule.toml"])
original_production_rule = load_rule_contents(file_path)
production_rule = deepcopy(original_production_rule)[0]
production_rule["metadata"]["integration"] = ["aws"]
production_rule["rule"]["query"] = """
from logs-aws.cloud*, logs-network_traffic.http-*,
logs-nginx.access-* metadata _id, _version, _index
| where @timestamp > now() - 30 minutes
and aws.cloudtrail.user_identity.type == "IAMUser"
| keep
aws.*, _id, _version, _index
"""
_ = RuleCollection().load_dict(production_rule)
def test_esql_endpoint_alerts_index(self):
"""Test an ESQL rule's schema validation using ecs fields in the alerts index."""
file_path = get_path(["tests", "data", "command_control_dummy_production_rule.toml"])
original_production_rule = load_rule_contents(file_path)
production_rule = deepcopy(original_production_rule)[0]
production_rule["rule"]["query"] = """
from logs-endpoint.alerts-* METADATA _id, _version, _index
| where event.code in ("malicious_file", "memory_signature", "shellcode_thread") and rule.name is not null
| keep host.id, rule.name, event.code, _id, _version, _index
| stats Esql.host_id_count_distinct = count_distinct(host.id) by rule.name, event.code
| where Esql.host_id_count_distinct >= 3
"""
_ = RuleCollection().load_dict(production_rule)
def test_esql_endpoint_unknown_index(self):
"""Test an ESQL rule's index validation. This is expected to error on an unknown index."""
file_path = get_path(["tests", "data", "command_control_dummy_production_rule.toml"])
original_production_rule = load_rule_contents(file_path)
production_rule = deepcopy(original_production_rule)[0]
production_rule["rule"]["query"] = """
from logs-endpoint.fake-*
| where event.code in ("malicious_file", "memory_signature", "shellcode_thread") and rule.name is not null
| keep host.id, rule.name, event.code, _id, _version, _index
| stats Esql.host_id_count_distinct = count_distinct(host.id) by rule.name, event.code
| where Esql.host_id_count_distinct >= 3
"""
with pytest.raises(EsqlUnknownIndexError):
_ = RuleCollection().load_dict(production_rule)
def test_esql_endpoint_alerts_index_endpoint_fields(self):
"""Test an ESQL rule's schema validation using endpoint integration fields in the alerts index."""
file_path = get_path(["tests", "data", "command_control_dummy_production_rule.toml"])
original_production_rule = load_rule_contents(file_path)
production_rule = deepcopy(original_production_rule)[0]
production_rule["metadata"]["integration"] = []
production_rule["rule"]["query"] = """
from logs-endpoint.alerts-* METADATA _id, _version, _index
| where event.code in ("malicious_file", "memory_signature", "shellcode_thread") and rule.name is not null and file.Ext.entry_modified > 0
| keep host.id, rule.name, event.code, file.Ext.entry_modified, _id, _version, _index
| stats Esql.host_id_count_distinct = count_distinct(host.id) by rule.name, event.code, file.Ext.entry_modified
| where Esql.host_id_count_distinct >= 3
"""
# This is a type mismatch error due to Elastic Container project including the Endpoint integration by default.
# Otherwise one would expect an EsqlSchemaError due to the field not being present in the alerts index.
with pytest.raises(EsqlTypeMismatchError):
_ = RuleCollection().load_dict(production_rule)
def test_esql_filtered_keep(self):
"""Test an ESQL rule's schema validation."""
file_path = get_path(["tests", "data", "command_control_dummy_production_rule.toml"])
original_production_rule = load_rule_contents(file_path)
# Test that a ValidationError is raised if the query doesn't match the schema
production_rule = deepcopy(original_production_rule)[0]
production_rule["metadata"]["integration"] = ["aws"]
production_rule["rule"]["query"] = """
from logs-aws.billing* metadata _id, _version, _index
| where @timestamp > now() - 30 minutes and aws.cloudtrail.user_identity.type == "IAMUser"
| keep host.id, rule.name, event.code, _id, _version, _index
| stats Esql.host_id_count_distinct = count_distinct(host.id) by rule.name, event.code
| where Esql.host_id_count_distinct >= 3
"""
with pytest.raises(EsqlSchemaError):
_ = RuleCollection().load_dict(production_rule)
def test_esql_non_ecs_schema_conflict_resolution(self):
"""Test an ESQL rule that has a known conflict between non_ecs and integrations for correct handling."""
file_path = get_path(["tests", "data", "command_control_dummy_production_rule.toml"])
original_production_rule = load_rule_contents(file_path)
production_rule = deepcopy(original_production_rule)[0]
production_rule["metadata"]["integration"] = ["azure", "o365"]
production_rule["rule"]["query"] = """
from logs-azure.signinlogs-* metadata _id, _version, _index
| where @timestamp > now() - 30 minutes
and event.dataset in ("azure.signinlogs")
and event.outcome == "success"
and azure.signinlogs.properties.user_id is not null
| keep
event.outcome, _id, _version, _index
"""
_ = RuleCollection().load_dict(production_rule)
def test_esql_multiple_keeps(self):
"""Test an ESQL rule that has multiple keeps in the query."""
file_path = get_path(["tests", "data", "command_control_dummy_production_rule.toml"])
original_production_rule = load_rule_contents(file_path)
production_rule = deepcopy(original_production_rule)[0]
production_rule["metadata"]["integration"] = ["aws"]
production_rule["rule"]["query"] = """
from logs-aws.cloudtrail* metadata _id, _version, _index
| where @timestamp > now() - 30 minutes
and event.dataset in ("aws.cloudtrail", "aws.billing")
and aws.cloudtrail.user_identity.type == "IAMUser"
| keep aws.cloudtrail.user_identity.type, _id, _version, _index
| eval Esql.user_type = aws.cloudtrail.user_identity.type
| keep Esql.user_type
"""
with pytest.raises(EsqlSemanticError):
_ = RuleCollection().load_dict(production_rule)