avatarELWALI KARKOUB

Summary

The provided web content outlines the process of integrating Wazuh security alerts with Discord using a custom Python script and webhook configuration to enhance real-time security monitoring and communication.

Abstract

The article details a method for integrating Wazuh, an open-source security monitoring solution, with Discord, a popular communication platform. By utilizing a Discord webhook, Wazuh alerts can be directly sent to a Discord server, providing immediate and detailed security updates to team members. The integration is facilitated by a Python script that formats and sends the alerts to Discord, with the script needing to be placed within the Wazuh manager's integrations directory and properly configured. The script processes alert data, including severity levels, rule descriptions, and compliance information, and formats this data into Discord-compatible messages with rich embeds. The article also provides step-by-step instructions for setting up the Discord webhook and configuring the Wazuh Manager to use the custom Python script for alert notifications. This integration ensures that security teams are promptly informed about potential threats and can act swiftly to mitigate risks.

Opinions

  • The integration of Wazuh with Discord is presented as a valuable tool for security teams, emphasizing the importance of quick and effective communication in the event of security incidents.
  • The use of Discord as a platform for receiving security alerts is likened to having a "security guard in your digital hangout," suggesting that it enhances the overall security posture of an organization by keeping all relevant parties informed in real-time.
  • The guide is positioned as user-friendly and instructive, aiming to simplify the process of setting up the integration for users who may not be familiar with the technical details involved.
  • The article concludes with an endorsement of an AI service, ZAI.chat, which is offered as a cost-effective alternative to ChatGPT Plus (GPT-4), indicating a belief in the value of accessible AI services for users interested in similar functionalities.

Discord & Wazuh Integration

Discord is a popular communication platform where people chat, share info, and connect. Integrating Wazuh alerts into Discord is key for quick and effective security updates. It can be deemed as a security guard in your digital hangout, making sure everyone stays informed and acts fast if there’s a potential threat.

In this guide, we’ll walk through setting up a Discord webhook to receive Wazuh alerts in a Discord server directly. This integration is made possible through the integrations module within Wazuh.

Discord Configuration:

  • In Discord, select the Server, and under Text Channels, select Edit Channel (gear icon)
  • Select Integrations > View Webhooks and click New Webhook
  • Copy the Webhook URL

Discord Python Script:

#!/var/ossec/framework/python/bin/python3

import sys
import json
import time
import requests
 
 
# Log messages to `integrations.log` file
def logger(message):
  f = open('/var/ossec/logs/integrations.log', 'a')
  f.write('{0} [Discord]: {1}\n'.format(time.strftime('%Y/%m/%d %H:%M:%S %Z'), message))
  f.close()

 
# Get alert json of alert file
def get_alert(alert_file):
  f = open(alert_file)
  alert_json = json.loads(f.read())
  f.close()
  return alert_json

# Generate Discord message
def generate_message(alert_json):
  level = alert_json['rule']['level']

  # Message color depending on alert rule level
  if level <= 5:
    color = 16776960 # yellow
  else:
    color = 15158332 # red
   
  embed_data = {}
  embed_data['title'] = alert_json['rule']['description'] if 'description' in alert_json['rule'] else 'N/A'
  embed_data['description'] = alert_json['full_log'] if 'full_log' in alert_json else ''
  embed_data['fields'] = []
 
  if 'agent' in alert_json:
    agent_text = '{0} (ID: {1})'.format(alert_json['agent']['name'], alert_json['agent']['id'])
    embed_data['fields'].append({
      'name' : 'Agent',
      'value' : '{0}'.format(agent_text),
      'inline' : True
    }) 
 
  embed_data['fields'].append({
    'name' : 'Rule ID',
    'value' : '{0} (Alert Level: {1})'.format(alert_json['rule']['id'], alert_json['rule']['level']),
    'inline' : True
  })
 
  if 'groups' in alert_json['rule'] and len(alert_json['rule']['groups']) > 0:
    embed_data['fields'].append({
      'name' : 'Group(s)',
      'value' : ', '.join(alert_json['rule']['groups']),
      'inline' : True
    })

  if 'mitre' in alert_json['rule']:
    embed_data['fields'].append({
      'name' : 'Mitre Tactic',
      'value' : '{0}'.format(alert_json['rule']['mitre']['tactic']),
      'inline' : True
    })
 
  if 'pci_dss' in alert_json['rule']:
    embed_data['fields'].append({
      'name' : 'PCI DSS',
      'value' : '{0}'.format(alert_json['rule']['pci_dss']),
      'inline' : True
    })

  if 'gdpr' in alert_json['rule']:
    embed_data['fields'].append({
      'name' : 'GDPR',
      'value' : '{0}'.format(alert_json['rule']['gdpr']),
      'inline' : True
    })

  embed_data['fields'].append({
    'name' : 'Location',
    'value' : alert_json['location'],
    'inline' : True
  })
 
  embed_data['color'] = color
  embed_data['url'] = '{0}/app/discover'.format(server_url)
  embed_data['timestamp'] = alert_json['timestamp']
 
  message = {'embeds': [ embed_data ] }
 
  return json.dumps(message)
 
# Send request to Discord webhook with the message
def send_message(message):
  headers = {'content-type': 'application/json', 'accept-charset': 'UTF-8'}
  response = requests.post(discord_webhook_url, data=message, headers=headers)
  logger(response)
 
if __name__ == '__main__':
  try:
    # Get arguments
    alert_file = sys.argv[1]
    server_url = sys.argv[2]
    discord_webhook_url = sys.argv[3]
 
    # Get alert from file and send message
    alert_json = get_alert(alert_file)
    message = generate_message(alert_json)
    send_message(message)
    sys.exit(0)
  except Exception as e:
    logger('ERROR: {0}'.format(str(e)))
    raise 

Wazuh Manager Configuration:

Place the script in the Wazuh manager under the path /var/ossec/integrations assigning the following permissions and ownership:

chown :wazuh /var/ossec/integrations/custom-discord.py
chmod 750 /var/ossec/integrations/custom-discord
cp -p /var/ossec/integrations/slack /var/ossec/integrations/custom-discord

Add the integration configuration to your Wazuh manager:

 <integration>
  <name>custom-discord</name>
  <api_key>Wazuh_Dashboard_URL</api_key>
  <hook_url>DISCORD_WEBHOOK_URL</hook_url>
  <alert_format>json</alert_format>
</integration> 

Then save and restart the Wazuh manager.

Result:

The alerts are sent to Discord in real-time and are enriched with important information such as Mitre Tactic and alert full-log among others.

Hope this helps :)

Siem
Edr
Discord
Wazuh
Cybersecurity
Recommended from ReadMedium