2023-01-12 07:20:48 +00:00
|
|
|
from yaml import dump, load
|
2023-01-12 07:20:43 +00:00
|
|
|
from yaml.parser import ParserError
|
2023-01-12 07:20:48 +00:00
|
|
|
from yaml.scanner import ScannerError
|
|
|
|
|
2023-01-12 07:20:43 +00:00
|
|
|
try:
|
2023-01-12 07:20:48 +00:00
|
|
|
from yaml import CDumper as Dumper
|
|
|
|
from yaml import CLoader as Loader
|
2023-01-12 07:20:43 +00:00
|
|
|
except ImportError:
|
|
|
|
from yaml import Loader, Dumper
|
|
|
|
|
2023-02-09 19:11:38 +00:00
|
|
|
import uuid
|
2023-02-02 20:04:55 +00:00
|
|
|
from datetime import datetime
|
|
|
|
|
2023-01-15 23:02:13 +00:00
|
|
|
import orjson
|
2023-02-02 18:58:40 +00:00
|
|
|
from siphashc import siphash
|
2023-01-15 17:59:12 +00:00
|
|
|
|
2023-01-12 07:20:48 +00:00
|
|
|
from core.lib.notify import sendmsg
|
2023-01-15 17:59:12 +00:00
|
|
|
from core.lib.parsing import parse_index, parse_source
|
2023-01-12 07:20:48 +00:00
|
|
|
from core.util import logs
|
|
|
|
|
|
|
|
log = logs.get_logger("rules")
|
|
|
|
|
2023-01-14 16:36:22 +00:00
|
|
|
SECONDS_PER_UNIT = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}
|
|
|
|
|
|
|
|
MAX_WINDOW = 2592000
|
2023-01-16 07:20:37 +00:00
|
|
|
MAX_AMOUNT_NTFY = 10
|
|
|
|
MAX_AMOUNT_WEBHOOK = 1000
|
2023-02-02 19:08:10 +00:00
|
|
|
HIGH_FREQUENCY_MIN_SEC = 60
|
2023-01-14 16:36:22 +00:00
|
|
|
|
2023-01-12 07:20:48 +00:00
|
|
|
|
2023-01-14 14:45:19 +00:00
|
|
|
class RuleParseError(Exception):
|
|
|
|
def __init__(self, message, field):
|
|
|
|
super().__init__(message)
|
|
|
|
self.field = field
|
|
|
|
|
|
|
|
|
2023-01-16 00:10:41 +00:00
|
|
|
def format_ntfy(**kwargs):
|
|
|
|
"""
|
|
|
|
Format a message for ntfy.
|
2023-01-16 07:20:37 +00:00
|
|
|
If the message is a list, it will be joined with newlines.
|
|
|
|
If the message is None, it will be replaced with an empty string.
|
|
|
|
If specified, `matched` will be pretty-printed in the first line.
|
|
|
|
kwargs:
|
|
|
|
rule: The rule object, must be specified
|
|
|
|
index: The index the rule matched on, can be None
|
|
|
|
message: The message to send, can be None
|
|
|
|
matched: The matched fields, can be None
|
2023-02-01 07:20:24 +00:00
|
|
|
total_hits: The total number of matches, optional
|
2023-01-16 00:10:41 +00:00
|
|
|
"""
|
|
|
|
rule = kwargs.get("rule")
|
|
|
|
index = kwargs.get("index")
|
|
|
|
message = kwargs.get("message")
|
|
|
|
matched = kwargs.get("matched")
|
2023-02-01 07:20:24 +00:00
|
|
|
total_hits = kwargs.get("total_hits", 0)
|
2023-01-16 00:10:41 +00:00
|
|
|
if message:
|
2023-01-15 23:02:13 +00:00
|
|
|
# Dump the message in YAML for readability
|
|
|
|
messages_formatted = ""
|
|
|
|
if isinstance(message, list):
|
2023-01-16 07:20:37 +00:00
|
|
|
for message_iter in message:
|
2023-01-15 23:02:13 +00:00
|
|
|
messages_formatted += dump(
|
2023-01-16 07:20:37 +00:00
|
|
|
message_iter, Dumper=Dumper, default_flow_style=False
|
2023-01-15 23:02:13 +00:00
|
|
|
)
|
|
|
|
messages_formatted += "\n"
|
|
|
|
else:
|
|
|
|
messages_formatted = dump(message, Dumper=Dumper, default_flow_style=False)
|
2023-01-16 00:10:41 +00:00
|
|
|
else:
|
|
|
|
messages_formatted = ""
|
|
|
|
|
|
|
|
if matched:
|
2023-01-15 23:02:13 +00:00
|
|
|
matched = ", ".join([f"{k}: {v}" for k, v in matched.items()])
|
2023-01-16 00:10:41 +00:00
|
|
|
else:
|
|
|
|
matched = ""
|
|
|
|
|
|
|
|
notify_message = f"{rule.name} on {index}: {matched}\n{messages_formatted}"
|
2023-02-01 07:20:24 +00:00
|
|
|
notify_message += f"\nTotal hits: {total_hits}"
|
2023-01-16 00:10:41 +00:00
|
|
|
notify_message = notify_message.encode("utf-8", "replace")
|
|
|
|
|
|
|
|
return notify_message
|
|
|
|
|
|
|
|
|
|
|
|
def format_webhook(**kwargs):
|
|
|
|
"""
|
|
|
|
Format a message for a webhook.
|
2023-01-16 07:20:37 +00:00
|
|
|
Adds some metadata to the message that would normally be only in
|
|
|
|
notification_settings.
|
|
|
|
Dumps the message in JSON.
|
|
|
|
kwargs:
|
|
|
|
rule: The rule object, must be specified
|
|
|
|
index: The index the rule matched on, can be None
|
|
|
|
message: The message to send, can be None, but will be sent as None
|
|
|
|
matched: The matched fields, can be None, but will be sent as None
|
2023-02-01 07:20:24 +00:00
|
|
|
total_hits: The total number of matches, optional
|
2023-01-16 07:20:37 +00:00
|
|
|
notification_settings: The notification settings, must be specified
|
|
|
|
priority: The priority of the message, optional
|
|
|
|
topic: The topic of the message, optional
|
2023-01-16 00:10:41 +00:00
|
|
|
"""
|
|
|
|
rule = kwargs.get("rule")
|
|
|
|
index = kwargs.get("index")
|
|
|
|
message = kwargs.get("message")
|
|
|
|
matched = kwargs.get("matched")
|
2023-02-01 07:20:24 +00:00
|
|
|
total_hits = kwargs.get("total_hits", 0)
|
2023-01-16 00:10:41 +00:00
|
|
|
notification_settings = kwargs.get("notification_settings")
|
|
|
|
notify_message = {
|
|
|
|
"rule_id": rule.id,
|
|
|
|
"rule_name": rule.name,
|
2023-02-09 22:54:38 +00:00
|
|
|
"matched": matched,
|
2023-02-01 07:20:24 +00:00
|
|
|
"total_hits": total_hits,
|
2023-01-16 00:10:41 +00:00
|
|
|
"index": index,
|
|
|
|
"data": message,
|
|
|
|
}
|
|
|
|
if "priority" in notification_settings:
|
|
|
|
notify_message["priority"] = notification_settings["priority"]
|
|
|
|
if "topic" in notification_settings:
|
|
|
|
notify_message["topic"] = notification_settings["topic"]
|
|
|
|
notify_message = orjson.dumps(notify_message)
|
|
|
|
|
|
|
|
return notify_message
|
2023-01-15 23:02:13 +00:00
|
|
|
|
2023-01-16 00:10:41 +00:00
|
|
|
|
2023-01-16 07:20:37 +00:00
|
|
|
def rule_notify(rule, index, message, meta=None):
|
2023-01-16 07:20:37 +00:00
|
|
|
"""
|
|
|
|
Send a notification for a matching rule.
|
|
|
|
Gets the notification settings for the rule.
|
|
|
|
Runs the formatting helpers for the service.
|
|
|
|
:param rule: The rule object, must be specified
|
|
|
|
:param index: The index the rule matched on, can be None
|
|
|
|
:param message: The message to send, can be None
|
2023-01-16 07:20:37 +00:00
|
|
|
:param meta: dict of metadata, contains `aggs` key for the matched fields
|
2023-01-16 07:20:37 +00:00
|
|
|
"""
|
|
|
|
# If there is no message, don't say anything matched
|
2023-01-16 00:10:41 +00:00
|
|
|
if message:
|
|
|
|
word = "match"
|
|
|
|
else:
|
|
|
|
word = "no match"
|
2023-01-16 07:20:37 +00:00
|
|
|
|
2023-01-16 00:10:41 +00:00
|
|
|
title = f"Rule {rule.name} {word} on {index}"
|
2023-01-16 07:20:37 +00:00
|
|
|
|
|
|
|
# The user notification settings are merged in with this
|
2023-01-16 00:10:41 +00:00
|
|
|
notification_settings = rule.get_notification_settings()
|
|
|
|
if not notification_settings:
|
2023-01-16 07:20:37 +00:00
|
|
|
# No/invalid notification settings, don't send anything
|
2023-01-16 00:10:41 +00:00
|
|
|
return
|
2023-02-09 07:20:07 +00:00
|
|
|
if notification_settings.get("service") == "none":
|
|
|
|
# Don't send anything
|
|
|
|
return
|
2023-01-16 07:20:37 +00:00
|
|
|
|
|
|
|
# Create a cast we can reuse for the formatting helpers and sendmsg
|
2023-01-16 00:10:41 +00:00
|
|
|
cast = {
|
|
|
|
"title": title,
|
|
|
|
"user": rule.user,
|
|
|
|
"rule": rule,
|
|
|
|
"index": index,
|
|
|
|
"message": message,
|
|
|
|
"notification_settings": notification_settings,
|
|
|
|
}
|
2023-01-16 07:20:37 +00:00
|
|
|
if meta:
|
2023-02-01 07:20:24 +00:00
|
|
|
if "matched" in meta:
|
|
|
|
cast["matched"] = meta["matched"]
|
|
|
|
if "total_hits" in meta:
|
|
|
|
cast["total_hits"] = meta["total_hits"]
|
2023-01-16 07:20:37 +00:00
|
|
|
|
2023-01-16 00:10:41 +00:00
|
|
|
if rule.service == "ntfy":
|
|
|
|
cast["msg"] = format_ntfy(**cast)
|
2023-01-15 23:02:13 +00:00
|
|
|
|
|
|
|
elif rule.service == "webhook":
|
2023-01-16 00:10:41 +00:00
|
|
|
cast["msg"] = format_webhook(**cast)
|
2023-01-15 23:02:13 +00:00
|
|
|
|
2023-01-16 00:10:41 +00:00
|
|
|
sendmsg(**cast)
|
2023-01-12 07:20:48 +00:00
|
|
|
|
|
|
|
|
2023-01-12 07:20:43 +00:00
|
|
|
class NotificationRuleData(object):
|
2023-01-15 17:59:12 +00:00
|
|
|
def __init__(self, user, cleaned_data, db):
|
2023-01-12 07:20:43 +00:00
|
|
|
self.user = user
|
2023-01-15 17:59:12 +00:00
|
|
|
self.object = None
|
|
|
|
|
2023-01-16 07:20:37 +00:00
|
|
|
# We are running live and have been passed a database object
|
2023-01-15 17:59:12 +00:00
|
|
|
if not isinstance(cleaned_data, dict):
|
|
|
|
self.object = cleaned_data
|
|
|
|
cleaned_data = cleaned_data.__dict__
|
|
|
|
|
2023-01-14 14:45:19 +00:00
|
|
|
self.cleaned_data = cleaned_data
|
2023-01-15 17:59:12 +00:00
|
|
|
self.db = db
|
2023-01-14 14:45:19 +00:00
|
|
|
self.data = self.cleaned_data.get("data")
|
2023-01-16 01:17:19 +00:00
|
|
|
self.window = self.cleaned_data.get("window")
|
2023-02-09 07:20:35 +00:00
|
|
|
self.policy = self.cleaned_data.get("policy")
|
2023-01-12 07:20:43 +00:00
|
|
|
self.parsed = None
|
2023-01-15 17:59:12 +00:00
|
|
|
self.aggs = {}
|
2023-01-12 07:20:43 +00:00
|
|
|
|
2023-01-14 16:36:22 +00:00
|
|
|
self.validate_user_permissions()
|
|
|
|
|
2023-01-12 07:20:43 +00:00
|
|
|
self.parse_data()
|
2023-01-15 17:59:12 +00:00
|
|
|
self.ensure_list()
|
2023-01-12 07:20:43 +00:00
|
|
|
self.validate_permissions()
|
2023-01-15 17:59:12 +00:00
|
|
|
self.validate_schedule_fields()
|
2023-01-14 14:45:19 +00:00
|
|
|
self.validate_time_fields()
|
2023-01-16 00:29:54 +00:00
|
|
|
if self.object is not None:
|
|
|
|
self.populate_matched()
|
|
|
|
|
2023-02-09 21:17:50 +00:00
|
|
|
def clear_database_matches(self):
|
|
|
|
"""
|
|
|
|
Delete all matches for this rule.
|
|
|
|
"""
|
|
|
|
rule_id = str(self.object.id)
|
|
|
|
self.db.delete_rule_entries(rule_id)
|
|
|
|
|
2023-01-16 00:29:54 +00:00
|
|
|
def populate_matched(self):
|
2023-01-16 07:20:37 +00:00
|
|
|
"""
|
|
|
|
On first creation, the match field is None. We need to populate it with
|
|
|
|
a dictionary containing the index names as keys and False as values.
|
|
|
|
"""
|
2023-01-16 00:29:54 +00:00
|
|
|
if self.object.match is None:
|
|
|
|
self.object.match = {}
|
|
|
|
for index in self.parsed["index"]:
|
|
|
|
if index not in self.object.match:
|
|
|
|
self.object.match[index] = False
|
|
|
|
self.object.save()
|
2023-01-14 14:45:19 +00:00
|
|
|
|
2023-02-09 22:54:38 +00:00
|
|
|
def format_matched(self, messages):
|
|
|
|
matched = {}
|
|
|
|
for message in messages:
|
2023-02-09 22:59:00 +00:00
|
|
|
for field, value in self.parsed.items():
|
2023-02-09 22:54:38 +00:00
|
|
|
if field == "msg":
|
|
|
|
# Allow partial matches for msg
|
|
|
|
for msg in value:
|
|
|
|
if "msg" in message:
|
|
|
|
if msg.lower() in message["msg"].lower():
|
|
|
|
matched[field] = msg
|
|
|
|
# Break out of the msg matching loop
|
|
|
|
break
|
|
|
|
# Continue to next field
|
|
|
|
continue
|
|
|
|
if field in message and message[field] in value:
|
|
|
|
# Do exact matches for all other fields
|
|
|
|
matched[field] = message[field]
|
|
|
|
return matched
|
|
|
|
|
2023-01-15 17:59:12 +00:00
|
|
|
def store_match(self, index, match):
|
|
|
|
"""
|
|
|
|
Store a match result.
|
2023-01-16 07:20:37 +00:00
|
|
|
Accepts None for the index to set all indices.
|
|
|
|
:param index: the index to store the match for, can be None
|
2023-02-02 18:58:40 +00:00
|
|
|
:param match: the object that matched
|
2023-01-15 17:59:12 +00:00
|
|
|
"""
|
2023-02-02 18:58:40 +00:00
|
|
|
if match is not False:
|
|
|
|
# Dump match to JSON while sorting the keys
|
|
|
|
match_normalised = orjson.dumps(match, option=orjson.OPT_SORT_KEYS)
|
|
|
|
match = siphash(self.db.hash_key, match_normalised)
|
|
|
|
|
2023-01-15 17:59:12 +00:00
|
|
|
if self.object.match is None:
|
|
|
|
self.object.match = {}
|
|
|
|
if not isinstance(self.object.match, dict):
|
|
|
|
self.object.match = {}
|
|
|
|
|
2023-01-16 00:10:41 +00:00
|
|
|
if index is None:
|
|
|
|
for index_iter in self.parsed["index"]:
|
|
|
|
self.object.match[index_iter] = match
|
|
|
|
else:
|
|
|
|
self.object.match[index] = match
|
2023-01-15 17:59:12 +00:00
|
|
|
self.object.save()
|
|
|
|
log.debug(f"Stored match: {index} - {match}")
|
|
|
|
|
2023-02-02 18:58:40 +00:00
|
|
|
def get_match(self, index=None, match=None):
|
2023-01-15 18:40:17 +00:00
|
|
|
"""
|
|
|
|
Get a match result for an index.
|
2023-01-16 07:20:37 +00:00
|
|
|
If the index is None, it will return True if any index has a match.
|
|
|
|
:param index: the index to get the match for, can be None
|
2023-01-15 18:40:17 +00:00
|
|
|
"""
|
|
|
|
if self.object.match is None:
|
2023-01-16 00:20:40 +00:00
|
|
|
self.object.match = {}
|
|
|
|
self.object.save()
|
2023-01-15 18:40:17 +00:00
|
|
|
return None
|
|
|
|
if not isinstance(self.object.match, dict):
|
|
|
|
return None
|
|
|
|
|
2023-01-16 00:10:41 +00:00
|
|
|
if index is None:
|
|
|
|
# Check if we have any matches on all indices
|
2023-02-09 07:20:07 +00:00
|
|
|
values = self.object.match.values()
|
|
|
|
if not values:
|
|
|
|
return None
|
|
|
|
return any(values)
|
2023-01-16 00:10:41 +00:00
|
|
|
|
2023-02-02 18:58:40 +00:00
|
|
|
# Check if it's the same hash
|
|
|
|
if match is not None:
|
|
|
|
match_normalised = orjson.dumps(match, option=orjson.OPT_SORT_KEYS)
|
|
|
|
match = siphash(self.db.hash_key, match_normalised)
|
|
|
|
hash_matches = self.object.match.get(index) == match
|
|
|
|
return hash_matches
|
|
|
|
|
2023-02-09 20:28:34 +00:00
|
|
|
returned_match = self.object.match.get(index, None)
|
|
|
|
if type(returned_match) == int:
|
|
|
|
# We are getting a hash from the database,
|
|
|
|
# but we have nothing to check it against.
|
|
|
|
# In this instance, we are checking if we got a match
|
|
|
|
# at all last time. We can confidently say that since
|
|
|
|
# we have a hash, we did.
|
|
|
|
returned_match = True
|
|
|
|
return returned_match
|
2023-01-15 18:40:17 +00:00
|
|
|
|
|
|
|
def format_aggs(self, aggs):
|
|
|
|
"""
|
|
|
|
Format aggregations for the query.
|
|
|
|
We have self.aggs, which contains:
|
|
|
|
{"avg_sentiment": (">", 0.5)}
|
|
|
|
and aggs, which contains:
|
|
|
|
{"avg_sentiment": {"value": 0.6}}
|
|
|
|
It's matched already, we just need to format it like so:
|
|
|
|
{"avg_sentiment": "0.06>0.5"}
|
2023-01-16 07:20:37 +00:00
|
|
|
:param aggs: the aggregations to format
|
|
|
|
:return: the formatted aggregations
|
2023-01-15 18:40:17 +00:00
|
|
|
"""
|
|
|
|
new_aggs = {}
|
|
|
|
for agg_name, agg in aggs.items():
|
2023-02-09 22:54:38 +00:00
|
|
|
if agg_name in self.aggs:
|
|
|
|
op, value = self.aggs[agg_name]
|
|
|
|
new_aggs[agg_name] = f"{agg['value']}{op}{value}"
|
2023-01-15 18:40:17 +00:00
|
|
|
|
2023-02-09 21:41:00 +00:00
|
|
|
return new_aggs
|
2023-01-15 18:40:17 +00:00
|
|
|
|
2023-02-09 07:20:45 +00:00
|
|
|
def reform_matches(self, index, matches, meta, mode):
|
2023-02-02 20:04:55 +00:00
|
|
|
if not isinstance(matches, list):
|
|
|
|
matches = [matches]
|
|
|
|
matches_copy = matches.copy()
|
|
|
|
match_ts = datetime.utcnow().isoformat()
|
2023-02-09 19:11:38 +00:00
|
|
|
batch_id = uuid.uuid4()
|
|
|
|
|
|
|
|
# Filter empty fields in meta
|
|
|
|
meta = {k: v for k, v in meta.items() if v}
|
|
|
|
|
2023-02-02 20:04:55 +00:00
|
|
|
for match_index, _ in enumerate(matches_copy):
|
|
|
|
matches_copy[match_index]["index"] = index
|
2023-02-09 19:11:38 +00:00
|
|
|
matches_copy[match_index]["rule_id"] = str(self.object.id)
|
2023-02-02 20:04:55 +00:00
|
|
|
matches_copy[match_index]["meta"] = meta
|
|
|
|
matches_copy[match_index]["match_ts"] = match_ts
|
2023-02-08 18:26:40 +00:00
|
|
|
matches_copy[match_index]["mode"] = mode
|
2023-02-09 19:11:38 +00:00
|
|
|
matches_copy[match_index]["batch_id"] = str(batch_id)
|
2023-02-09 07:20:45 +00:00
|
|
|
return matches_copy
|
|
|
|
|
|
|
|
async def ingest_matches(self, index, matches, meta, mode):
|
|
|
|
"""
|
|
|
|
Store all matches for an index.
|
|
|
|
:param index: the index to store the matches for
|
|
|
|
:param matches: the matches to store
|
|
|
|
"""
|
|
|
|
new_matches = self.reform_matches(index, matches, meta, mode)
|
|
|
|
await self.db.async_store_matches(new_matches)
|
|
|
|
|
|
|
|
def ingest_matches_sync(self, index, matches, meta, mode):
|
|
|
|
"""
|
|
|
|
Store all matches for an index.
|
|
|
|
:param index: the index to store the matches for
|
|
|
|
:param matches: the matches to store
|
|
|
|
"""
|
|
|
|
new_matches = self.reform_matches(index, matches, meta, mode)
|
|
|
|
self.db.store_matches(new_matches)
|
2023-02-02 20:04:55 +00:00
|
|
|
|
2023-02-08 18:26:40 +00:00
|
|
|
async def rule_matched(self, index, message, meta, mode):
|
2023-01-16 00:10:41 +00:00
|
|
|
"""
|
|
|
|
A rule has matched.
|
2023-01-16 07:20:37 +00:00
|
|
|
If the previous run did not match, send a notification after formatting
|
|
|
|
the aggregations.
|
|
|
|
:param index: the index the rule matched on
|
|
|
|
:param message: the message object that matched
|
|
|
|
:param aggs: the aggregations that matched
|
2023-01-16 00:10:41 +00:00
|
|
|
"""
|
2023-02-02 18:58:40 +00:00
|
|
|
current_match = self.get_match(index, message)
|
2023-01-16 07:20:37 +00:00
|
|
|
log.debug(f"Rule matched: {index} - current match: {current_match}")
|
2023-02-09 07:20:35 +00:00
|
|
|
|
2023-02-09 19:11:38 +00:00
|
|
|
last_run_had_matches = current_match is True
|
|
|
|
|
|
|
|
if self.policy in ["change", "default"]:
|
|
|
|
# Change or Default policy, notifying only on new results
|
|
|
|
if last_run_had_matches:
|
|
|
|
# Last run had matches, and this one did too
|
|
|
|
# We don't need to notify
|
|
|
|
return
|
|
|
|
|
|
|
|
elif self.policy == "always":
|
|
|
|
# Only here for completeness, we notify below by default
|
|
|
|
pass
|
2023-02-09 07:20:35 +00:00
|
|
|
|
2023-02-09 19:11:38 +00:00
|
|
|
# We hit the return above if we don't need to notify
|
2023-02-09 23:34:29 +00:00
|
|
|
if "matched" not in meta:
|
|
|
|
meta["matched"] = self.format_matched(message)
|
2023-02-09 22:54:38 +00:00
|
|
|
if "aggs" in meta:
|
2023-02-09 23:18:16 +00:00
|
|
|
aggs_formatted = self.format_aggs(meta["aggs"])
|
|
|
|
if aggs_formatted:
|
|
|
|
meta["matched_aggs"] = aggs_formatted
|
2023-02-09 22:54:38 +00:00
|
|
|
|
2023-02-09 19:11:38 +00:00
|
|
|
rule_notify(self.object, index, message, meta)
|
|
|
|
self.store_match(index, message)
|
|
|
|
await self.ingest_matches(index, message, meta, mode)
|
2023-01-16 00:10:41 +00:00
|
|
|
|
2023-02-09 07:20:45 +00:00
|
|
|
def rule_matched_sync(self, index, message, meta, mode):
|
|
|
|
"""
|
|
|
|
A rule has matched.
|
|
|
|
If the previous run did not match, send a notification after formatting
|
|
|
|
the aggregations.
|
|
|
|
:param index: the index the rule matched on
|
|
|
|
:param message: the message object that matched
|
|
|
|
:param aggs: the aggregations that matched
|
|
|
|
"""
|
|
|
|
current_match = self.get_match(index, message)
|
|
|
|
log.debug(f"Rule matched: {index} - current match: {current_match}")
|
2023-02-09 07:20:35 +00:00
|
|
|
|
2023-02-09 19:11:38 +00:00
|
|
|
last_run_had_matches = current_match is True
|
|
|
|
|
|
|
|
if self.policy in ["change", "default"]:
|
|
|
|
# Change or Default policy, notifying only on new results
|
|
|
|
if last_run_had_matches:
|
|
|
|
# Last run had matches, and this one did too
|
|
|
|
# We don't need to notify
|
|
|
|
return
|
|
|
|
|
|
|
|
elif self.policy == "always":
|
|
|
|
# Only here for completeness, we notify below by default
|
|
|
|
pass
|
|
|
|
|
|
|
|
# We hit the return above if we don't need to notify
|
2023-02-09 23:34:29 +00:00
|
|
|
if "matched" not in meta:
|
|
|
|
meta["matched"] = self.format_matched(message)
|
2023-02-09 23:18:16 +00:00
|
|
|
if "aggs" in meta:
|
2023-02-09 23:34:29 +00:00
|
|
|
aggs_formatted = self.format_aggs(meta["aggs"])
|
|
|
|
if aggs_formatted:
|
|
|
|
meta["matched_aggs"] = aggs_formatted
|
|
|
|
|
2023-02-09 19:11:38 +00:00
|
|
|
rule_notify(self.object, index, message, meta)
|
|
|
|
self.store_match(index, message)
|
|
|
|
self.ingest_matches_sync(index, message, meta, mode)
|
2023-02-09 07:20:45 +00:00
|
|
|
|
2023-02-09 07:20:07 +00:00
|
|
|
# No async helper for this one as we only need it for schedules
|
2023-02-09 07:20:07 +00:00
|
|
|
async def rule_no_match(self, index=None, message=None):
|
2023-01-16 00:10:41 +00:00
|
|
|
"""
|
|
|
|
A rule has not matched.
|
2023-01-16 07:20:37 +00:00
|
|
|
If the previous run did match, send a notification if configured to notify
|
|
|
|
for empty matches.
|
|
|
|
:param index: the index the rule did not match on, can be None
|
|
|
|
|
2023-01-16 00:10:41 +00:00
|
|
|
"""
|
|
|
|
current_match = self.get_match(index)
|
2023-02-09 21:17:50 +00:00
|
|
|
log.debug(
|
|
|
|
f"Rule not matched: {index} - current match: {current_match}: {message}"
|
|
|
|
)
|
2023-02-09 07:20:35 +00:00
|
|
|
|
2023-02-09 19:11:38 +00:00
|
|
|
last_run_had_matches = current_match is True
|
2023-02-09 20:28:34 +00:00
|
|
|
initial = current_match is None
|
2023-02-09 19:11:38 +00:00
|
|
|
|
2023-02-09 20:28:34 +00:00
|
|
|
self.store_match(index, False)
|
2023-02-09 19:11:38 +00:00
|
|
|
|
2023-02-09 20:28:34 +00:00
|
|
|
if self.policy != "always":
|
|
|
|
# We hit the return above if we don't need to notify
|
|
|
|
if self.policy in ["change", "default"]:
|
|
|
|
if not last_run_had_matches and not initial:
|
|
|
|
# We don't need to notify if the last run didn't have matches
|
|
|
|
return
|
|
|
|
|
|
|
|
if self.policy in ["always", "change"]:
|
|
|
|
# Never notify for empty matches on default policy
|
2023-02-09 19:11:38 +00:00
|
|
|
rule_notify(self.object, index, "no_match", None)
|
2023-02-09 20:28:34 +00:00
|
|
|
await self.ingest_matches(
|
2023-02-09 21:17:50 +00:00
|
|
|
index=index,
|
|
|
|
matches=[{"msg": None}],
|
|
|
|
meta={"msg": message},
|
|
|
|
mode="schedule",
|
2023-02-09 20:28:34 +00:00
|
|
|
)
|
2023-01-16 00:10:41 +00:00
|
|
|
|
2023-01-15 17:59:12 +00:00
|
|
|
async def run_schedule(self):
|
|
|
|
"""
|
|
|
|
Run the schedule query.
|
2023-01-16 07:20:37 +00:00
|
|
|
Get the results from the database, and check if the rule has matched.
|
|
|
|
Check if all of the required aggregations have matched.
|
2023-01-15 17:59:12 +00:00
|
|
|
"""
|
2023-01-15 18:40:17 +00:00
|
|
|
response = await self.db.schedule_query_results(self)
|
2023-01-16 00:10:41 +00:00
|
|
|
if not response:
|
2023-01-16 07:20:37 +00:00
|
|
|
# No results in the result_map
|
2023-02-09 07:20:07 +00:00
|
|
|
await self.rule_no_match(message="No response from database")
|
2023-02-09 20:28:34 +00:00
|
|
|
return
|
2023-01-16 07:20:37 +00:00
|
|
|
for index, (meta, results) in response.items():
|
2023-01-15 18:40:17 +00:00
|
|
|
if not results:
|
2023-01-16 07:20:37 +00:00
|
|
|
# Falsy results, no matches
|
2023-02-09 07:20:07 +00:00
|
|
|
await self.rule_no_match(index, message="No results for index")
|
2023-02-09 20:28:34 +00:00
|
|
|
continue
|
2023-01-15 17:59:12 +00:00
|
|
|
|
2023-01-16 07:20:37 +00:00
|
|
|
# Add the match values of all aggregations to a list
|
2023-01-15 18:40:17 +00:00
|
|
|
aggs_for_index = []
|
|
|
|
for agg_name in self.aggs.keys():
|
2023-01-16 07:20:37 +00:00
|
|
|
if agg_name in meta["aggs"]:
|
|
|
|
if "match" in meta["aggs"][agg_name]:
|
|
|
|
aggs_for_index.append(meta["aggs"][agg_name]["match"])
|
2023-01-15 18:40:17 +00:00
|
|
|
|
|
|
|
# All required aggs are present
|
|
|
|
if len(aggs_for_index) == len(self.aggs.keys()):
|
|
|
|
if all(aggs_for_index):
|
2023-01-16 07:20:37 +00:00
|
|
|
# All aggs have matched
|
2023-02-08 18:26:40 +00:00
|
|
|
await self.rule_matched(
|
|
|
|
index, results[: self.object.amount], meta, mode="schedule"
|
|
|
|
)
|
2023-01-15 18:40:17 +00:00
|
|
|
continue
|
2023-01-16 07:20:37 +00:00
|
|
|
# Default branch, since the happy path has a continue keyword
|
2023-02-09 07:20:07 +00:00
|
|
|
await self.rule_no_match(index, message="Aggregation did not match")
|
2023-01-15 18:40:17 +00:00
|
|
|
|
2023-01-15 17:59:12 +00:00
|
|
|
def test_schedule(self):
|
|
|
|
"""
|
|
|
|
Test the schedule query to ensure it is valid.
|
2023-01-16 07:20:37 +00:00
|
|
|
Raises an exception if the query is invalid.
|
2023-01-15 17:59:12 +00:00
|
|
|
"""
|
|
|
|
if self.db:
|
2023-02-09 07:20:35 +00:00
|
|
|
self.db.schedule_query_results_test_sync(self)
|
2023-01-15 17:59:12 +00:00
|
|
|
|
|
|
|
def validate_schedule_fields(self):
|
|
|
|
"""
|
|
|
|
Ensure schedule fields are valid.
|
|
|
|
index: can be a list, it will schedule one search per index.
|
|
|
|
source: can be a list, it will be the filter for each search.
|
|
|
|
tokens: can be list, it will ensure the message matches any token.
|
|
|
|
msg: can be a list, it will ensure the message contains any msg.
|
|
|
|
No other fields can be lists containing more than one item.
|
2023-01-16 07:20:37 +00:00
|
|
|
:raises RuleParseError: if the fields are invalid
|
2023-01-15 17:59:12 +00:00
|
|
|
"""
|
|
|
|
is_schedule = self.is_schedule
|
|
|
|
|
|
|
|
if is_schedule:
|
|
|
|
allowed_list_fields = ["index", "source", "tokens", "msg"]
|
|
|
|
for field, value in self.parsed.items():
|
|
|
|
if field not in allowed_list_fields:
|
|
|
|
if len(value) > 1:
|
|
|
|
raise RuleParseError(
|
|
|
|
(
|
|
|
|
f"For scheduled rules, field {field} cannot contain "
|
|
|
|
"more than one item"
|
|
|
|
),
|
|
|
|
"data",
|
|
|
|
)
|
|
|
|
if len(str(value[0])) == 0:
|
|
|
|
raise RuleParseError(f"Field {field} cannot be empty", "data")
|
|
|
|
if "sentiment" in self.parsed:
|
|
|
|
sentiment = str(self.parsed["sentiment"][0])
|
|
|
|
sentiment = sentiment.strip()
|
|
|
|
if sentiment[0] not in [">", "<", "="]:
|
|
|
|
raise RuleParseError(
|
|
|
|
(
|
|
|
|
"Sentiment field must be a comparison operator and then a "
|
|
|
|
"float: >0.02"
|
|
|
|
),
|
|
|
|
"data",
|
|
|
|
)
|
|
|
|
operator = sentiment[0]
|
|
|
|
number = sentiment[1:]
|
|
|
|
|
|
|
|
try:
|
|
|
|
number = float(number)
|
|
|
|
except ValueError:
|
|
|
|
raise RuleParseError(
|
|
|
|
(
|
|
|
|
"Sentiment field must be a comparison operator and then a "
|
|
|
|
"float: >0.02"
|
|
|
|
),
|
|
|
|
"data",
|
|
|
|
)
|
|
|
|
self.aggs["avg_sentiment"] = (operator, number)
|
|
|
|
|
|
|
|
else:
|
|
|
|
if "query" in self.parsed:
|
|
|
|
raise RuleParseError(
|
|
|
|
"Field query cannot be used with on-demand rules", "data"
|
|
|
|
)
|
|
|
|
if "tags" in self.parsed:
|
|
|
|
raise RuleParseError(
|
|
|
|
"Field tags cannot be used with on-demand rules", "data"
|
|
|
|
)
|
2023-02-09 07:20:35 +00:00
|
|
|
if self.policy != "default":
|
2023-02-09 07:20:07 +00:00
|
|
|
raise RuleParseError(
|
2023-02-09 21:41:00 +00:00
|
|
|
(
|
|
|
|
f"Cannot use {self.cleaned_data['policy']} policy with "
|
|
|
|
"on-demand rules"
|
|
|
|
),
|
2023-02-09 07:20:35 +00:00
|
|
|
"policy",
|
2023-02-09 07:20:07 +00:00
|
|
|
)
|
2023-01-15 17:59:12 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def is_schedule(self):
|
2023-01-16 07:20:37 +00:00
|
|
|
"""
|
|
|
|
Check if the rule is a schedule rule.
|
|
|
|
:return: True if the rule is a schedule rule, False otherwise
|
|
|
|
"""
|
2023-01-15 17:59:12 +00:00
|
|
|
if "interval" in self.cleaned_data:
|
|
|
|
if self.cleaned_data["interval"] != 0:
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
def ensure_list(self):
|
|
|
|
"""
|
2023-01-16 07:20:37 +00:00
|
|
|
Ensure all values in the data field are lists.
|
|
|
|
Convert all strings to lists with one item.
|
2023-01-15 17:59:12 +00:00
|
|
|
"""
|
|
|
|
for field, value in self.parsed.items():
|
|
|
|
if not isinstance(value, list):
|
|
|
|
self.parsed[field] = [value]
|
|
|
|
|
2023-01-14 16:36:22 +00:00
|
|
|
def validate_user_permissions(self):
|
|
|
|
"""
|
|
|
|
Ensure the user can use notification rules.
|
2023-01-16 07:20:37 +00:00
|
|
|
:raises RuleParseError: if the user does not have permission
|
2023-01-14 16:36:22 +00:00
|
|
|
"""
|
|
|
|
if not self.user.has_perm("core.use_rules"):
|
|
|
|
raise RuleParseError("User does not have permission to use rules", "data")
|
|
|
|
|
2023-01-14 14:45:19 +00:00
|
|
|
def validate_time_fields(self):
|
|
|
|
"""
|
|
|
|
Validate the interval and window fields.
|
|
|
|
Prohibit window being specified with an ondemand interval.
|
2023-01-16 07:20:37 +00:00
|
|
|
Prohibit window not being specified with a non-ondemand interval.
|
|
|
|
Prohibit amount being specified with an on-demand interval.
|
|
|
|
Prohibut amount not being specified with a non-ondemand interval.
|
|
|
|
Validate window field.
|
|
|
|
Validate window unit and enforce maximum.
|
|
|
|
:raises RuleParseError: if the fields are invalid
|
2023-01-14 14:45:19 +00:00
|
|
|
"""
|
|
|
|
interval = self.cleaned_data.get("interval")
|
|
|
|
window = self.cleaned_data.get("window")
|
2023-01-15 23:02:13 +00:00
|
|
|
amount = self.cleaned_data.get("amount")
|
2023-01-16 07:20:37 +00:00
|
|
|
service = self.cleaned_data.get("service")
|
2023-01-15 23:02:13 +00:00
|
|
|
|
|
|
|
on_demand = interval == 0
|
2023-02-02 19:08:10 +00:00
|
|
|
|
|
|
|
# Not on demand and interval is too low
|
|
|
|
if not on_demand and interval <= HIGH_FREQUENCY_MIN_SEC:
|
|
|
|
if not self.user.has_perm("core.rules_high_frequency"):
|
|
|
|
raise RuleParseError(
|
|
|
|
"User does not have permission to use high frequency rules", "data"
|
|
|
|
)
|
|
|
|
|
|
|
|
if not on_demand:
|
|
|
|
if not self.user.has_perm("core.rules_scheduled"):
|
|
|
|
raise RuleParseError(
|
|
|
|
"User does not have permission to use scheduled rules", "data"
|
|
|
|
)
|
|
|
|
|
2023-01-15 23:02:13 +00:00
|
|
|
if on_demand and window is not None:
|
|
|
|
# Interval is on demand and window is specified
|
|
|
|
# We can't have a window with on-demand rules
|
2023-01-14 14:45:19 +00:00
|
|
|
raise RuleParseError(
|
2023-01-14 16:36:22 +00:00
|
|
|
"Window cannot be specified with on-demand interval", "window"
|
2023-01-14 14:45:19 +00:00
|
|
|
)
|
2023-01-12 07:20:43 +00:00
|
|
|
|
2023-01-15 23:02:13 +00:00
|
|
|
if not on_demand and window is None:
|
|
|
|
# Interval is not on demand and window is not specified
|
|
|
|
# We can't have a non-on-demand interval without a window
|
2023-01-14 16:36:22 +00:00
|
|
|
raise RuleParseError(
|
|
|
|
"Window must be specified with non-on-demand interval", "window"
|
|
|
|
)
|
|
|
|
|
2023-01-15 23:02:13 +00:00
|
|
|
if not on_demand and amount is None:
|
|
|
|
# Interval is not on demand and amount is not specified
|
|
|
|
# We can't have a non-on-demand interval without an amount
|
|
|
|
raise RuleParseError(
|
|
|
|
"Amount must be specified with non-on-demand interval", "amount"
|
|
|
|
)
|
|
|
|
if on_demand and amount is not None:
|
|
|
|
# Interval is on demand and amount is specified
|
|
|
|
# We can't have an amount with on-demand rules
|
|
|
|
raise RuleParseError(
|
|
|
|
"Amount cannot be specified with on-demand interval", "amount"
|
|
|
|
)
|
|
|
|
|
2023-01-14 16:36:22 +00:00
|
|
|
if window is not None:
|
|
|
|
window_number = window[:-1]
|
|
|
|
if not window_number.isdigit():
|
|
|
|
raise RuleParseError("Window prefix must be a number", "window")
|
|
|
|
window_number = int(window_number)
|
|
|
|
window_unit = window[-1]
|
|
|
|
if window_unit not in SECONDS_PER_UNIT:
|
|
|
|
raise RuleParseError(
|
2023-01-14 17:24:54 +00:00
|
|
|
(
|
|
|
|
"Window unit must be one of "
|
|
|
|
f"{', '.join(SECONDS_PER_UNIT.keys())},"
|
|
|
|
f" not '{window_unit}'"
|
|
|
|
),
|
2023-01-14 16:36:22 +00:00
|
|
|
"window",
|
|
|
|
)
|
|
|
|
window_seconds = window_number * SECONDS_PER_UNIT[window_unit]
|
|
|
|
if window_seconds > MAX_WINDOW:
|
|
|
|
raise RuleParseError(
|
|
|
|
f"Window cannot be larger than {MAX_WINDOW} seconds (30 days)",
|
|
|
|
"window",
|
|
|
|
)
|
|
|
|
|
2023-01-16 07:20:37 +00:00
|
|
|
if amount is not None:
|
|
|
|
if service == "ntfy":
|
|
|
|
if amount > MAX_AMOUNT_NTFY:
|
|
|
|
raise RuleParseError(
|
|
|
|
f"Amount cannot be larger than {MAX_AMOUNT_NTFY} for ntfy",
|
|
|
|
"amount",
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
if amount > MAX_AMOUNT_WEBHOOK:
|
|
|
|
raise RuleParseError(
|
|
|
|
(
|
|
|
|
f"Amount cannot be larger than {MAX_AMOUNT_WEBHOOK} for "
|
|
|
|
f"{service}"
|
|
|
|
),
|
|
|
|
"amount",
|
|
|
|
)
|
|
|
|
|
2023-01-12 07:20:43 +00:00
|
|
|
def validate_permissions(self):
|
|
|
|
"""
|
|
|
|
Validate permissions for the source and index variables.
|
2023-01-16 07:20:37 +00:00
|
|
|
Also set the default values for the user if not present.
|
|
|
|
Stores the default or expanded values in the parsed field.
|
|
|
|
:raises QueryError: if the user does not have permission to use the source
|
2023-01-12 07:20:43 +00:00
|
|
|
"""
|
|
|
|
if "index" in self.parsed:
|
|
|
|
index = self.parsed["index"]
|
|
|
|
if type(index) == list:
|
|
|
|
for i in index:
|
2023-01-15 17:59:12 +00:00
|
|
|
parse_index(self.user, {"index": i}, raise_error=True)
|
|
|
|
# else:
|
|
|
|
# db.parse_index(self.user, {"index": index}, raise_error=True)
|
2023-01-12 07:20:43 +00:00
|
|
|
else:
|
|
|
|
# Get the default value for the user if not present
|
2023-01-15 17:59:12 +00:00
|
|
|
index = parse_index(self.user, {}, raise_error=True)
|
2023-01-16 00:23:23 +00:00
|
|
|
self.parsed["index"] = [index]
|
2023-01-12 07:20:43 +00:00
|
|
|
|
|
|
|
if "source" in self.parsed:
|
|
|
|
source = self.parsed["source"]
|
|
|
|
if type(source) == list:
|
|
|
|
for i in source:
|
2023-01-15 17:59:12 +00:00
|
|
|
parse_source(self.user, {"source": i}, raise_error=True)
|
|
|
|
# else:
|
|
|
|
# parse_source(self.user, {"source": source}, raise_error=True)
|
2023-01-12 07:20:43 +00:00
|
|
|
else:
|
|
|
|
# Get the default value for the user if not present
|
2023-01-15 17:59:12 +00:00
|
|
|
source = parse_source(self.user, {}, raise_error=True)
|
2023-02-02 19:35:27 +00:00
|
|
|
self.parsed["source"] = source
|
2023-01-12 07:20:43 +00:00
|
|
|
|
|
|
|
def parse_data(self):
|
|
|
|
"""
|
|
|
|
Parse the data in the text field to YAML.
|
2023-01-16 07:20:37 +00:00
|
|
|
:raises RuleParseError: if the data is invalid
|
2023-01-12 07:20:43 +00:00
|
|
|
"""
|
|
|
|
try:
|
|
|
|
self.parsed = load(self.data, Loader=Loader)
|
|
|
|
except (ScannerError, ParserError) as e:
|
2023-01-16 07:20:37 +00:00
|
|
|
raise RuleParseError(f"Invalid YAML: {e}", "data")
|
2023-01-12 07:20:43 +00:00
|
|
|
|
|
|
|
def __str__(self):
|
2023-01-16 07:20:37 +00:00
|
|
|
"""
|
|
|
|
Get a YAML representation of the data field of the rule.
|
|
|
|
"""
|
2023-01-12 07:20:43 +00:00
|
|
|
return dump(self.parsed, Dumper=Dumper)
|
|
|
|
|
|
|
|
def get_data(self):
|
2023-01-16 07:20:37 +00:00
|
|
|
"""
|
|
|
|
Return the data field as a dictionary.
|
|
|
|
"""
|
2023-01-12 07:20:48 +00:00
|
|
|
return self.parsed
|