2024-05-18 21:23:35 +02:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
|
|
|
|
|
import getopt
|
|
|
|
|
import json
|
|
|
|
|
import os
|
|
|
|
|
import sys
|
|
|
|
|
import time
|
|
|
|
|
from os.path import join, dirname
|
2024-05-22 21:05:27 +02:00
|
|
|
from sys import _getframe as frame
|
2024-05-18 21:23:35 +02:00
|
|
|
|
2024-05-27 12:40:39 +02:00
|
|
|
import tomli
|
2024-05-18 21:23:35 +02:00
|
|
|
from dotenv import load_dotenv
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Define paths: wazuh_path = wazuh root directory
|
2024-05-22 21:05:27 +02:00
|
|
|
# log_path = wazuh-notify.log path,
|
2024-05-18 21:23:35 +02:00
|
|
|
# config_path = wazuh-notify-config.yaml
|
2024-05-22 21:05:27 +02:00
|
|
|
|
2024-05-18 21:23:35 +02:00
|
|
|
def set_environment() -> tuple:
|
2024-05-27 12:40:39 +02:00
|
|
|
set_wazuh_path = os.path.abspath(os.path.join(__file__, "../.."))
|
|
|
|
|
# set_wazuh_path = os.path.abspath(os.path.join(__file__, "../../.."))
|
2024-05-22 21:05:27 +02:00
|
|
|
set_log_path = '{0}/logs/wazuh-notify.log'.format(set_wazuh_path)
|
2024-05-27 12:40:39 +02:00
|
|
|
set_config_path = '{0}/etc/wazuh-notify-config.toml'.format(set_wazuh_path)
|
2024-05-18 21:23:35 +02:00
|
|
|
|
2024-05-22 21:05:27 +02:00
|
|
|
return set_wazuh_path, set_log_path, set_config_path
|
2024-05-18 21:23:35 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
# Set paths for use in this module
|
2024-05-22 21:05:27 +02:00
|
|
|
wazuh_path, log_path, config_path = set_environment()
|
2024-05-18 21:23:35 +02:00
|
|
|
|
2024-05-22 21:05:27 +02:00
|
|
|
|
|
|
|
|
# Set structured timestamps for notifications.
|
2024-05-18 21:23:35 +02:00
|
|
|
def set_time_format():
|
|
|
|
|
now_message = time.strftime('%A, %d %b %Y %H:%M:%S')
|
2024-05-22 21:05:27 +02:00
|
|
|
now_logging = time.strftime('%Y-%m-%d %H:%M:%S')
|
2024-05-18 21:23:35 +02:00
|
|
|
now_time = time.strftime('%H:%M')
|
|
|
|
|
now_weekday = time.strftime('%A')
|
2024-05-22 21:05:27 +02:00
|
|
|
|
2024-05-18 21:23:35 +02:00
|
|
|
return now_message, now_logging, now_weekday, now_time
|
|
|
|
|
|
|
|
|
|
|
2024-05-22 21:05:27 +02:00
|
|
|
# Logger: print to console and/or log to file
|
|
|
|
|
def logger(level, config, me, him, message):
|
2024-05-24 13:06:46 +02:00
|
|
|
_, now_logging, _, _ = set_time_format()
|
2024-05-27 20:24:00 +02:00
|
|
|
|
2024-05-22 21:05:27 +02:00
|
|
|
logger_wazuh_path = os.path.abspath(os.path.join(__file__, "../../.."))
|
|
|
|
|
logger_log_path = '{0}/logs/wazuh-notify.log'.format(logger_wazuh_path)
|
2024-05-18 21:23:35 +02:00
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
# When logging from main(), the destination function is called "<module>". For cosmetic reasons rename to "main".
|
2024-05-22 21:05:27 +02:00
|
|
|
him = 'main' if him == '<module>' else him
|
2024-05-27 20:24:00 +02:00
|
|
|
log_line = f'{now_logging} | {level} | {me: <26} | {him: <13} | {message}'
|
2024-05-24 13:06:46 +02:00
|
|
|
|
|
|
|
|
# Compare the extended_print log level in the configuration to the log level of the message.
|
2024-05-27 12:40:39 +02:00
|
|
|
if config.get('python').get('extended_print', 0) >= level:
|
2024-05-22 21:05:27 +02:00
|
|
|
print(log_line)
|
2024-05-24 13:06:46 +02:00
|
|
|
try:
|
|
|
|
|
# Compare the extended_logging level in the configuration to the log level of the message.
|
2024-05-27 12:40:39 +02:00
|
|
|
if config.get('python').get('extended_logging', 0) >= level:
|
2024-05-22 21:05:27 +02:00
|
|
|
with open(logger_log_path, mode="a") as log_file:
|
|
|
|
|
log_file.write(log_line + "\n")
|
|
|
|
|
except (FileNotFoundError, PermissionError, OSError):
|
2024-05-24 13:06:46 +02:00
|
|
|
# Special message to console when logging to file fails and console logging might not be set.
|
2024-05-27 20:24:00 +02:00
|
|
|
log_line = f'{now_logging} | {level} | {me: <26} | {him: <13} | error opening log file: {logger_log_path}'
|
2024-05-22 21:05:27 +02:00
|
|
|
print(log_line)
|
|
|
|
|
|
|
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
# Get the content of the .env file (url's and/or webhooks).
|
2024-05-18 21:23:35 +02:00
|
|
|
def get_env():
|
2024-05-24 13:06:46 +02:00
|
|
|
# The 'me' variable sets the called function (current function), the 'him' the calling function. Used for logging.
|
2024-05-22 21:05:27 +02:00
|
|
|
me = frame(0).f_code.co_name
|
|
|
|
|
him = frame(1).f_code.co_name
|
|
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
# Write the configuration to a dictionary.
|
2024-05-18 21:23:35 +02:00
|
|
|
config: dict = get_config()
|
|
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
# Check if the secrets .env file is available.
|
2024-05-18 21:23:35 +02:00
|
|
|
try:
|
|
|
|
|
dotenv_path = join(dirname(__file__), '.env')
|
|
|
|
|
load_dotenv(dotenv_path)
|
|
|
|
|
if not os.path.isfile(dotenv_path):
|
2024-05-22 21:05:27 +02:00
|
|
|
logger(0, config, me, him, dotenv_path + " not found")
|
2024-05-18 21:23:35 +02:00
|
|
|
raise Exception(dotenv_path, "file not found")
|
|
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
# Retrieve URLs from .env
|
2024-05-18 21:23:35 +02:00
|
|
|
discord_url = os.getenv("DISCORD_URL")
|
|
|
|
|
ntfy_url = os.getenv("NTFY_URL")
|
|
|
|
|
slack_url = os.getenv("SLACK_URL")
|
|
|
|
|
|
|
|
|
|
except Exception as err:
|
|
|
|
|
# output error, and return with an error code
|
2024-05-22 21:05:27 +02:00
|
|
|
logger(0, config, me, him, 'Error reading ' + str(err))
|
2024-05-18 21:23:35 +02:00
|
|
|
exit(err)
|
2024-05-22 21:05:27 +02:00
|
|
|
logger(2, config, me, him, dotenv_path + " loaded")
|
|
|
|
|
|
2024-05-18 21:23:35 +02:00
|
|
|
return discord_url, ntfy_url, slack_url
|
|
|
|
|
|
|
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
# Read and process configuration settings from wazuh-notify-config.yaml and create dictionary.
|
2024-05-18 21:23:35 +02:00
|
|
|
def get_config():
|
2024-05-24 13:06:46 +02:00
|
|
|
# The 'me' variable sets the called function (current function), the 'him' the calling function. Used for logging.
|
2024-05-22 21:05:27 +02:00
|
|
|
me = frame(0).f_code.co_name
|
|
|
|
|
him = frame(1).f_code.co_name
|
2024-05-18 21:23:35 +02:00
|
|
|
this_config_path: str = ""
|
2024-05-22 21:05:27 +02:00
|
|
|
config: dict = {}
|
2024-05-18 21:23:35 +02:00
|
|
|
|
2024-05-27 20:24:00 +02:00
|
|
|
# logger(2, config, me, him, "Loading TOML configuration")
|
2024-05-18 21:23:35 +02:00
|
|
|
try:
|
|
|
|
|
_, _, this_config_path = set_environment()
|
2024-05-27 12:40:39 +02:00
|
|
|
with open(this_config_path, 'rb') as ntfier_config:
|
|
|
|
|
config: dict = tomli.load(ntfier_config)
|
2024-05-18 21:23:35 +02:00
|
|
|
except (FileNotFoundError, PermissionError, OSError):
|
2024-05-22 21:05:27 +02:00
|
|
|
logger(2, config, me, him, "Error accessing configuration file: " + this_config_path)
|
|
|
|
|
logger(2, config, me, him, "Reading configuration file: " + this_config_path)
|
2024-05-18 21:23:35 +02:00
|
|
|
|
2024-05-27 12:40:39 +02:00
|
|
|
config['targets'] = config.get('general').get('targets', 'discord, slack, ntfy')
|
|
|
|
|
config['full_alert'] = config.get('general').get('full_alert', False)
|
|
|
|
|
config['excluded_rules'] = config.get('general').get('excluded_rules', '')
|
|
|
|
|
config['excluded_agents'] = config.get('general').get('excluded_agents', '')
|
2024-05-24 13:06:46 +02:00
|
|
|
config['priority_map'] = config.get('priority_map', [])
|
2024-05-27 12:40:39 +02:00
|
|
|
config['sender'] = config.get('general').get('sender', 'Wazuh (IDS)')
|
|
|
|
|
config['click'] = config.get('general').get('click', 'https://wazuh.com')
|
|
|
|
|
config['md_e'] = config.get('general').get('markdown_emphasis', '')
|
|
|
|
|
config['excluded_days'] = config.get('python').get('excluded_days', '')
|
|
|
|
|
config['excluded_hours'] = config.get('python').get('excluded_hours', '')
|
|
|
|
|
config['test_mode'] = config.get('python').get('test_mode', False)
|
|
|
|
|
config['extended_logging'] = config.get('python').get('extended_logging', 0)
|
|
|
|
|
config['extended_print'] = config.get('python').get('extended_print', 0)
|
2024-05-18 21:23:35 +02:00
|
|
|
|
|
|
|
|
return config
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Show configuration settings from wazuh-notify-config.yaml
|
|
|
|
|
def view_config():
|
|
|
|
|
_, _, this_config_path, _ = set_environment()
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
with open(this_config_path, 'r') as ntfier_config:
|
|
|
|
|
print(ntfier_config.read())
|
|
|
|
|
except (FileNotFoundError, PermissionError, OSError):
|
|
|
|
|
print(this_config_path + " does not exist or is not accessible")
|
|
|
|
|
return
|
|
|
|
|
|
2024-05-22 21:05:27 +02:00
|
|
|
|
|
|
|
|
# Get script arguments during execution. Params found here override config settings.
|
2024-05-18 21:23:35 +02:00
|
|
|
def get_arguments():
|
2024-05-24 13:06:46 +02:00
|
|
|
# The 'me' variable sets the called function (current function), the 'him' the calling function. Used for logging.
|
2024-05-22 21:05:27 +02:00
|
|
|
me = frame(0).f_code.co_name
|
|
|
|
|
him = frame(1).f_code.co_name
|
|
|
|
|
|
|
|
|
|
# Retrieve the configuration information
|
2024-05-18 21:23:35 +02:00
|
|
|
config: dict = get_config()
|
2024-05-22 21:05:27 +02:00
|
|
|
|
2024-05-18 21:23:35 +02:00
|
|
|
# Short options
|
|
|
|
|
options: str = "u:s:p:m:t:c:hv"
|
|
|
|
|
|
|
|
|
|
# Long options
|
2024-05-22 21:05:27 +02:00
|
|
|
long_options: list = ["url=",
|
|
|
|
|
"sender=",
|
|
|
|
|
"targets=",
|
|
|
|
|
"priority=",
|
|
|
|
|
"message=",
|
|
|
|
|
"tags=",
|
|
|
|
|
"click=",
|
|
|
|
|
"help",
|
|
|
|
|
"view"
|
|
|
|
|
]
|
2024-05-18 21:23:35 +02:00
|
|
|
|
|
|
|
|
help_text: str = """
|
|
|
|
|
-u, --url is the url for the server, ending with a "/".
|
|
|
|
|
-s, --sender is the sender of the message, either an app name or a person.
|
2024-05-22 21:05:27 +02:00
|
|
|
-d, --targets is the list of platforms to send a message to (slack, ntfy, discord)
|
2024-05-18 21:23:35 +02:00
|
|
|
-p, --priority is the priority of the message, ranging from 1 (lowest), to 5 (highest).
|
|
|
|
|
-m, --message is the text of the message to be sent.
|
|
|
|
|
-t, --tags is an arbitrary strings of tags (keywords), seperated by a "," (comma).
|
|
|
|
|
-c, --click is a link (URL) that can be followed by tapping/clicking inside the message.
|
|
|
|
|
-h, --help shows this help message. Must have no value argument.
|
|
|
|
|
-v, --view show config.
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
2024-05-22 21:05:27 +02:00
|
|
|
# Initialize some variables.
|
|
|
|
|
url: str = ""
|
|
|
|
|
sender: str = ""
|
|
|
|
|
targets: str = ""
|
|
|
|
|
message: str = ""
|
|
|
|
|
priority: int = 0
|
|
|
|
|
tags: str = ""
|
|
|
|
|
click: str = ""
|
|
|
|
|
|
|
|
|
|
# Fetch the arguments from the command line, skipping the first argument (name of the script).
|
2024-05-18 21:23:35 +02:00
|
|
|
argument_list: list = sys.argv[1:]
|
2024-05-22 21:05:27 +02:00
|
|
|
logger(2, config, me, him, "Found arguments:" + str(argument_list))
|
|
|
|
|
|
2024-05-18 21:23:35 +02:00
|
|
|
if not argument_list:
|
2024-05-22 21:05:27 +02:00
|
|
|
logger(1, config, me, him, 'No argument list found (no arguments provided with script execution')
|
2024-05-24 13:06:46 +02:00
|
|
|
|
|
|
|
|
# Store defaults for the non-existing arguments in the arguments dictionary to avoid None errors.
|
|
|
|
|
arguments: dict = {'url': url,
|
|
|
|
|
'sender': sender,
|
|
|
|
|
'targets': targets,
|
|
|
|
|
'message': message,
|
|
|
|
|
'priority': priority,
|
|
|
|
|
'tags': tags,
|
|
|
|
|
'click': click}
|
2024-05-22 21:05:27 +02:00
|
|
|
return arguments
|
2024-05-18 21:23:35 +02:00
|
|
|
else:
|
|
|
|
|
try:
|
2024-05-22 21:05:27 +02:00
|
|
|
logger(2, config, me, him, "Parsing arguments")
|
2024-05-18 21:23:35 +02:00
|
|
|
|
|
|
|
|
# Parsing arguments
|
2024-05-22 21:05:27 +02:00
|
|
|
p_arguments, values = getopt.getopt(argument_list, options, long_options)
|
|
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
# Check each argument. Arguments that are present will override the defaults.
|
2024-05-22 21:05:27 +02:00
|
|
|
for current_argument, current_value in p_arguments:
|
2024-05-18 21:23:35 +02:00
|
|
|
if current_argument in ("-h", "--help"):
|
|
|
|
|
print(help_text)
|
|
|
|
|
exit()
|
|
|
|
|
elif current_argument in ("-v", "--view"):
|
|
|
|
|
view_config()
|
|
|
|
|
exit()
|
|
|
|
|
elif current_argument in ("-u", "--url"):
|
|
|
|
|
url: str = current_value
|
|
|
|
|
elif current_argument in ("-s", "--sender"):
|
|
|
|
|
sender: str = current_value
|
2024-05-22 21:05:27 +02:00
|
|
|
elif current_argument in ("-d", "--targets"):
|
|
|
|
|
targets: str = current_value
|
2024-05-18 21:23:35 +02:00
|
|
|
elif current_argument in ("-p", "--priority"):
|
|
|
|
|
priority: int = int(current_value)
|
|
|
|
|
elif current_argument in ("-m", "--message"):
|
|
|
|
|
message: str = current_value
|
|
|
|
|
elif current_argument in ("-t", "--tags"):
|
|
|
|
|
tags: str = current_value
|
|
|
|
|
elif current_argument in ("-c", "--click"):
|
|
|
|
|
click: str = current_value
|
|
|
|
|
except getopt.error as err:
|
2024-05-22 21:05:27 +02:00
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
# Output error, and return error code
|
2024-05-22 21:05:27 +02:00
|
|
|
logger(0, config, me, him, "Error during argument parsing:" + str(err))
|
|
|
|
|
logger(2, config, me, him, "Arguments returned as dictionary")
|
|
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
# Store the arguments in the arguments dictionary.
|
2024-05-22 21:05:27 +02:00
|
|
|
arguments: dict = {'url': url, 'sender': sender, 'targets': targets, 'message': message,
|
|
|
|
|
'priority': priority, 'tags': tags, 'click': click}
|
|
|
|
|
return arguments
|
2024-05-18 21:23:35 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
# Receive and load message from Wazuh
|
|
|
|
|
def load_message():
|
2024-05-24 13:06:46 +02:00
|
|
|
# The 'me' variable sets the called function (current function), the 'him' the calling function. Used for logging.
|
2024-05-22 21:05:27 +02:00
|
|
|
me = frame(0).f_code.co_name
|
|
|
|
|
him = frame(1).f_code.co_name
|
2024-05-18 21:23:35 +02:00
|
|
|
config: dict = get_config()
|
|
|
|
|
|
|
|
|
|
# get alert from stdin
|
2024-05-22 21:05:27 +02:00
|
|
|
logger(2, config, me, him, "Loading event message from STDIN")
|
2024-05-18 21:23:35 +02:00
|
|
|
|
|
|
|
|
input_str: str = ""
|
|
|
|
|
for line in sys.stdin:
|
|
|
|
|
input_str: str = line
|
|
|
|
|
break
|
|
|
|
|
|
|
|
|
|
data: json = json.loads(input_str)
|
|
|
|
|
|
|
|
|
|
if data.get("command") == "add":
|
2024-05-22 21:05:27 +02:00
|
|
|
logger(1, config, me, him, "Relevant event data found")
|
2024-05-18 21:23:35 +02:00
|
|
|
return data
|
|
|
|
|
else:
|
2024-05-24 13:06:46 +02:00
|
|
|
# Event came in, but wasn't processed.
|
2024-05-22 21:05:27 +02:00
|
|
|
logger(0, config, me, him, "Event data not found")
|
2024-05-18 21:23:35 +02:00
|
|
|
sys.exit(1)
|
|
|
|
|
|
|
|
|
|
|
2024-05-27 20:24:00 +02:00
|
|
|
# Check if we are in test mode (test_mode setting in config yaml). If so, load test event instead of live event.
|
|
|
|
|
def check_test_mode(config):
|
|
|
|
|
me = frame(0).f_code.co_name
|
|
|
|
|
him = frame(1).f_code.co_name
|
|
|
|
|
|
|
|
|
|
if config.get('python').get('test_mode'):
|
|
|
|
|
logger(1, config, me, him, "Running in test mode: using test message wazuh-notify-test-event.json")
|
|
|
|
|
# Load the test event data.
|
|
|
|
|
home_path, _, _ = set_environment()
|
|
|
|
|
with (open(home_path + '/etc/wazuh-notify-test-event.json') as event_file):
|
|
|
|
|
data: dict = json.loads(event_file.read())
|
|
|
|
|
else:
|
|
|
|
|
# We are running live. Load the data from the Wazuh process.
|
|
|
|
|
logger(2, config, me, him, "Running in live mode: using live message")
|
|
|
|
|
data = load_message()
|
|
|
|
|
return data
|
|
|
|
|
|
2024-05-18 21:23:35 +02:00
|
|
|
|
2024-05-27 20:24:00 +02:00
|
|
|
# Check if there are reasons not to process this event. Check exclusions for rules, agents, days and hours.
|
2024-05-18 21:23:35 +02:00
|
|
|
def exclusions_check(config, alert):
|
2024-05-24 13:06:46 +02:00
|
|
|
# The 'me' variable sets the called function (current function), the 'him' the calling function. Used for logging.
|
2024-05-22 21:05:27 +02:00
|
|
|
me = frame(0).f_code.co_name
|
|
|
|
|
him = frame(1).f_code.co_name
|
|
|
|
|
|
2024-05-18 21:23:35 +02:00
|
|
|
# Set some environment
|
|
|
|
|
now_message, now_logging, now_weekday, now_time = set_time_format()
|
|
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
# Check the exclusion records from the configuration yaml.
|
2024-05-27 20:24:00 +02:00
|
|
|
logger(1, config, me, him, "Checking if we are outside of the exclusion rules: ")
|
|
|
|
|
ex_hours: tuple = config.get('python').get('excluded_hours')
|
2024-05-18 21:23:35 +02:00
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
# Start hour may not be later than end hours. End hour may not exceed 00:00 midnight to avoid day jump.
|
2024-05-18 21:23:35 +02:00
|
|
|
ex_hours = [ex_hours[0], "23:59"] if (ex_hours[1] >= '23:59' or ex_hours[1] < ex_hours[0]) else ex_hours
|
|
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
# Get some more exclusion records from the config.
|
2024-05-27 12:40:39 +02:00
|
|
|
ex_days = config.get('python').get('excluded_days')
|
|
|
|
|
ex_agents = config.get('general').get("excluded_agents")
|
|
|
|
|
ex_rules = config.get('general').get("excluded_rules")
|
2024-05-18 21:23:35 +02:00
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
# Check agent and rule from within the event.
|
2024-05-18 21:23:35 +02:00
|
|
|
ev_agent = alert['agent']['id']
|
|
|
|
|
ev_rule = alert['rule']['id']
|
|
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
# Let's assume all lights are green, until proven otherwise.
|
2024-05-18 21:23:35 +02:00
|
|
|
ex_hours_eval, ex_weekday_eval, ev_rule_eval, ev_agent_eval = True, True, True, True
|
|
|
|
|
|
|
|
|
|
# Evaluate the conditions for sending a notification. Any False will cause the notification to be discarded.
|
|
|
|
|
if (now_time > ex_hours[0]) and (now_time < ex_hours[1]):
|
2024-05-22 21:05:27 +02:00
|
|
|
logger(2, config, me, him, "excluded: event inside exclusion time frame")
|
2024-05-18 21:23:35 +02:00
|
|
|
ex_hours_eval = False
|
|
|
|
|
elif now_weekday in ex_days:
|
2024-05-22 21:05:27 +02:00
|
|
|
logger(2, config, me, him, "excluded: event inside excluded weekdays")
|
2024-05-18 21:23:35 +02:00
|
|
|
ex_weekday_eval = False
|
2024-05-22 21:05:27 +02:00
|
|
|
|
2024-05-18 21:23:35 +02:00
|
|
|
elif ev_rule in ex_rules:
|
2024-05-22 21:05:27 +02:00
|
|
|
logger(2, config, me, him, "excluded: event id inside exclusion list")
|
2024-05-18 21:23:35 +02:00
|
|
|
ev_rule_eval = False
|
|
|
|
|
elif ev_agent in ex_agents:
|
2024-05-22 21:05:27 +02:00
|
|
|
logger(2, config, me, him, "excluded: event agent inside exclusion list")
|
2024-05-18 21:23:35 +02:00
|
|
|
ev_rule_eval = False
|
|
|
|
|
|
2024-05-22 21:05:27 +02:00
|
|
|
notification_eval = True if (ex_hours_eval and ex_weekday_eval and ev_rule_eval and ev_agent_eval) else False
|
|
|
|
|
logger(1, config, me, him, "Exclusion rules evaluated. Final decision: " + str(notification_eval))
|
2024-05-18 21:23:35 +02:00
|
|
|
|
2024-05-27 20:24:00 +02:00
|
|
|
if not notification_eval:
|
|
|
|
|
# The event was excluded by the exclusion rules in the configuration.
|
|
|
|
|
logger(1, config, me, him, "Event excluded, no notification sent. Exiting")
|
|
|
|
|
exit()
|
|
|
|
|
else:
|
|
|
|
|
# The event was not excluded by the exclusion rules in the configuration. Keep processing.
|
|
|
|
|
logger(2, config, me, him, "Event NOT excluded, notification will be sent")
|
|
|
|
|
return
|
2024-05-18 21:23:35 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
# Map the event threat level to the appropriate 5-level priority scale and color for use in the notification platforms.
|
|
|
|
|
def threat_mapping(config, threat_level, fired_times):
|
2024-05-24 13:06:46 +02:00
|
|
|
# The 'me' variable sets the called function (current function), the 'him' the calling function. Used for logging.
|
2024-05-22 21:05:27 +02:00
|
|
|
me = frame(0).f_code.co_name
|
|
|
|
|
him = frame(1).f_code.co_name
|
|
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
# Map threat level to priority. Enters Homeland Security :-).
|
2024-05-18 21:23:35 +02:00
|
|
|
p_map = config.get('priority_map')
|
2024-05-22 21:05:27 +02:00
|
|
|
logger(2, config, me, him, "Prio map: " + str(p_map))
|
2024-05-18 21:23:35 +02:00
|
|
|
|
|
|
|
|
for i in range(len(p_map)):
|
2024-05-22 21:05:27 +02:00
|
|
|
logger(2, config, me, him, "Loop: " + str(i))
|
|
|
|
|
logger(2, config, me, him, "Level: " + str(threat_level))
|
|
|
|
|
|
2024-05-18 21:23:35 +02:00
|
|
|
if threat_level in p_map[i]["threat_map"]:
|
|
|
|
|
color_mapping = p_map[i]["color"]
|
|
|
|
|
priority_mapping = 5 - i
|
2024-05-22 21:05:27 +02:00
|
|
|
logger(2, config, me, him, "Prio: " + str(priority_mapping))
|
|
|
|
|
logger(2, config, me, him, "Color: " + str(color_mapping))
|
|
|
|
|
|
2024-05-18 21:23:35 +02:00
|
|
|
if fired_times >= p_map[i]["mention_threshold"]:
|
2024-05-24 13:06:46 +02:00
|
|
|
# When this flag is set, Discord recipients get a stronger message (DM).
|
2024-05-18 21:23:35 +02:00
|
|
|
mention_flag = "@here"
|
|
|
|
|
else:
|
|
|
|
|
mention_flag = ""
|
2024-05-22 21:05:27 +02:00
|
|
|
logger(2, config, me, him, "Threat level mapped as: " +
|
2024-05-24 13:06:46 +02:00
|
|
|
"prio:" + str(priority_mapping) + " color: " + str(color_mapping) + " mention: " + mention_flag)
|
2024-05-18 21:23:35 +02:00
|
|
|
return priority_mapping, color_mapping, mention_flag
|
2024-05-22 21:05:27 +02:00
|
|
|
|
|
|
|
|
logger(0, config, me, him, "Threat level mapping failed! Returning garbage (99, 99, 99)")
|
2024-05-24 13:06:46 +02:00
|
|
|
return 99, 99, "99"
|
2024-05-18 21:23:35 +02:00
|
|
|
|
|
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
# Construct the message that will be sent to the notifier platforms.
|
2024-05-27 20:24:00 +02:00
|
|
|
def construct_message_body(caller, config, arguments, data: dict) -> str:
|
2024-05-24 13:06:46 +02:00
|
|
|
# The 'me' variable sets the called function (current function), the 'him' the calling function. Used for logging.
|
2024-05-22 21:05:27 +02:00
|
|
|
me = frame(0).f_code.co_name
|
|
|
|
|
him = frame(1).f_code.co_name
|
|
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
# Include a specific control sequence for markdown bold parameter names.
|
2024-05-27 20:24:00 +02:00
|
|
|
# todo To be fixed
|
|
|
|
|
md_map = config.get('markdown_emphasis', '')
|
2024-05-22 21:05:27 +02:00
|
|
|
md_e = md_map[caller]
|
|
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
# If the --message (-m) argument was fulfilled, use this message to be sent.
|
2024-05-22 21:05:27 +02:00
|
|
|
if arguments['message']:
|
2024-05-27 20:24:00 +02:00
|
|
|
message_body = arguments['message']
|
2024-05-22 21:05:27 +02:00
|
|
|
else:
|
|
|
|
|
_, timestamp, _, _ = set_time_format()
|
2024-05-27 20:24:00 +02:00
|
|
|
message_body: str = \
|
2024-05-22 21:05:27 +02:00
|
|
|
(
|
|
|
|
|
md_e + "Timestamp:" + md_e + " " + timestamp + "\n" +
|
|
|
|
|
md_e + "Agent:" + md_e + " " + data["agent"]["name"] + " (" + data["agent"]["id"] + ")" + "\n" +
|
|
|
|
|
md_e + "Rule id:" + md_e + " " + data["rule"]["id"] + "\n" +
|
|
|
|
|
md_e + "Rule:" + md_e + " " + data["rule"]["description"] + "\n" +
|
|
|
|
|
md_e + "Description:" + md_e + " " + data["full_log"] + "\n" +
|
|
|
|
|
md_e + "Threat level:" + md_e + " " + str(data["rule"]["level"]) + "\n" +
|
2024-05-27 20:24:00 +02:00
|
|
|
md_e + "Times fired:" + md_e + " " + str(data["rule"]["firedtimes"]) + "\n"
|
|
|
|
|
)
|
2024-05-18 21:23:35 +02:00
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
logger(2, config, me, him, caller + " basic message constructed.")
|
2024-05-27 20:24:00 +02:00
|
|
|
return message_body
|
2024-05-18 21:23:35 +02:00
|
|
|
|
|
|
|
|
|
2024-05-22 21:05:27 +02:00
|
|
|
# Construct the notification (message + additional information) that will be sent to the notifier platforms.
|
2024-05-27 20:24:00 +02:00
|
|
|
def prepare_payload(caller, config, arguments, message_body, alert, priority):
|
2024-05-24 13:06:46 +02:00
|
|
|
# The 'me' variable sets the called function (current function), the 'him' the calling function. Used for logging.
|
2024-05-22 21:05:27 +02:00
|
|
|
me = frame(0).f_code.co_name
|
|
|
|
|
him = frame(1).f_code.co_name
|
|
|
|
|
|
2024-05-27 20:24:00 +02:00
|
|
|
logger(2, config, me, him, "Notification being constructed.")
|
2024-05-22 21:05:27 +02:00
|
|
|
|
2024-05-27 20:24:00 +02:00
|
|
|
md_map = config.get('markdown_emphasis', '')
|
2024-05-22 21:05:27 +02:00
|
|
|
md_e = md_map[caller]
|
|
|
|
|
|
2024-05-27 12:40:39 +02:00
|
|
|
click: str = config.get('general').get('click', 'https://wazuh.com')
|
2024-05-18 21:23:35 +02:00
|
|
|
priority: str = str(priority)
|
|
|
|
|
tags = (str(alert['rule']['groups']).replace("[", "")
|
|
|
|
|
.replace("]", "")
|
|
|
|
|
.replace("'", "")
|
|
|
|
|
.replace(",", ", ")
|
|
|
|
|
)
|
2024-05-24 13:06:46 +02:00
|
|
|
logger(2, config, me, him, caller + " full event formatted.")
|
2024-05-22 21:05:27 +02:00
|
|
|
|
2024-05-18 21:23:35 +02:00
|
|
|
full_event: str = str(json.dumps(alert, indent=4)
|
|
|
|
|
.replace('"', '')
|
|
|
|
|
.replace('{', '')
|
|
|
|
|
.replace('}', '')
|
|
|
|
|
.replace('[', '')
|
|
|
|
|
.replace(']', '')
|
|
|
|
|
.replace(',', ' ')
|
|
|
|
|
)
|
2024-05-24 13:06:46 +02:00
|
|
|
# Fill some of the variables with argument values if available.
|
|
|
|
|
|
2024-05-22 21:05:27 +02:00
|
|
|
priority = arguments['priority'] if arguments['priority'] else priority
|
|
|
|
|
tags = arguments['tags'] if arguments['tags'] else tags
|
2024-05-27 20:24:00 +02:00
|
|
|
sender: str = config.get('general').get('sender', 'Wazuh (IDS)')
|
|
|
|
|
sender = arguments['sender'] if arguments['sender'] else sender
|
|
|
|
|
click: str = config.get('general').get('click', 'https://wazuh.com')
|
|
|
|
|
click = arguments['click'] if arguments['click'] else click
|
2024-05-22 21:05:27 +02:00
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
# Add the full alert data to the notification.
|
|
|
|
|
if caller in config["full_alert"]:
|
2024-05-27 20:24:00 +02:00
|
|
|
logger(2, config, me, him, caller + "Full alert data will be attached.")
|
|
|
|
|
# Add the full alert data to the notification body
|
|
|
|
|
notification_body: str = ("\n\n" + message_body + "\n" +
|
|
|
|
|
md_e + "__Full event__" + md_e + "\n" + "```\n" + full_event + "```")
|
|
|
|
|
else:
|
|
|
|
|
notification_body: str = message_body
|
2024-05-22 21:05:27 +02:00
|
|
|
|
2024-05-27 20:24:00 +02:00
|
|
|
# Add priority & tags to the notification body
|
|
|
|
|
notification_body = (notification_body + "\n\n" + md_e + "Priority:" + md_e + " " + str(priority) + "\n" +
|
|
|
|
|
md_e + "Tags:" + md_e + " " + tags + "\n\n" + click)
|
2024-05-22 21:05:27 +02:00
|
|
|
logger(2, config, me, him, caller + " adding priority and tags")
|
|
|
|
|
|
|
|
|
|
config["targets"] = arguments['targets'] if arguments['targets'] != "" else config["targets"]
|
2024-05-18 21:23:35 +02:00
|
|
|
|
2024-05-27 20:24:00 +02:00
|
|
|
return notification_body, click, sender
|
2024-05-22 21:05:27 +02:00
|
|
|
|
2024-05-24 13:06:46 +02:00
|
|
|
|
2024-05-27 20:24:00 +02:00
|
|
|
def build_discord_notification(caller, config, notification_body, color, mention, sender):
|
|
|
|
|
# The 'me' variable sets the called function (current function), the 'him' the calling function. Used for logging.
|
|
|
|
|
me = frame(0).f_code.co_name
|
|
|
|
|
him = frame(1).f_code.co_name
|
|
|
|
|
logger(2, config, me, him, caller + " payload created")
|
|
|
|
|
|
|
|
|
|
payload_json = {"username": sender,
|
|
|
|
|
"content": mention,
|
|
|
|
|
"embeds": [{"description": notification_body,
|
|
|
|
|
"color": color,
|
|
|
|
|
"title": sender}]}
|
|
|
|
|
logger(2, config, me, him, caller + " notification built")
|
|
|
|
|
return "", "", payload_json
|
2024-05-22 21:05:27 +02:00
|
|
|
|
|
|
|
|
|
2024-05-27 20:24:00 +02:00
|
|
|
def build_ntfy_notification(caller, config, notification_body, priority, click, sender):
|
|
|
|
|
# The 'me' variable sets the called function (current function), the 'him' the calling function. Used for logging.
|
|
|
|
|
me = frame(0).f_code.co_name
|
|
|
|
|
him = frame(1).f_code.co_name
|
|
|
|
|
logger(2, config, me, him, caller + " payloads created")
|
2024-05-22 21:05:27 +02:00
|
|
|
|
2024-05-27 20:24:00 +02:00
|
|
|
# if caller == "ntfy":
|
|
|
|
|
# todo Check this out
|
|
|
|
|
# basic_msg = " \n" + basic_msg
|
2024-05-22 21:05:27 +02:00
|
|
|
|
2024-05-27 20:24:00 +02:00
|
|
|
payload_data = notification_body
|
|
|
|
|
payload_headers = {"Markdown": "yes",
|
|
|
|
|
"Title": sender,
|
|
|
|
|
"Priority": str(priority),
|
|
|
|
|
"Click": click}
|
|
|
|
|
logger(2, config, me, him, caller + " notification built")
|
|
|
|
|
return payload_headers, payload_data, ""
|
2024-05-22 21:05:27 +02:00
|
|
|
|
|
|
|
|
|
2024-05-27 20:24:00 +02:00
|
|
|
def build_slack_notification(caller, config, arguments, notification_body, priority, color, mention, click, sender):
|
|
|
|
|
# The 'me' variable sets the called function (current function), the 'him' the calling function. Used for logging.
|
|
|
|
|
me = frame(0).f_code.co_name
|
|
|
|
|
him = frame(1).f_code.co_name
|
|
|
|
|
sender: str = config.get('general').get('sender', 'Wazuh (IDS)')
|
|
|
|
|
sender = arguments['sender'] if arguments['sender'] else sender
|
2024-05-22 21:05:27 +02:00
|
|
|
|
2024-05-27 20:24:00 +02:00
|
|
|
logger(2, config, me, him, caller + " payloads created")
|
2024-05-22 21:05:27 +02:00
|
|
|
|
2024-05-27 20:24:00 +02:00
|
|
|
# todo Need some investigation.
|
2024-05-24 13:06:46 +02:00
|
|
|
|
2024-05-27 20:24:00 +02:00
|
|
|
payload_json = {"text": notification_body}
|
|
|
|
|
# payload_json = {"username": sender,
|
|
|
|
|
# "content": mention,
|
|
|
|
|
# "embeds": [{"description": notification,
|
|
|
|
|
# "color": color,
|
|
|
|
|
# "title": sender}]}
|
2024-05-22 21:05:27 +02:00
|
|
|
|
2024-05-27 20:24:00 +02:00
|
|
|
logger(2, config, me, him, caller + " notification built")
|
2024-05-22 21:05:27 +02:00
|
|
|
|
2024-05-27 20:24:00 +02:00
|
|
|
return "", "", payload_json
|