Wazuh integration with AWS SNS 

| by | Wazuh 4.7.1
Post icon

AWS Simple Notification Service (SNS) is a fully managed messaging service that enables sending notifications from the cloud. It supports publishing messages to various endpoints like AWS services, email, SMS, and HTTP/HTTPS webhooks.

SNS facilitates application-to-application (A2A) and application-to-person (A2P) communication. This post explores using A2P to publish Wazuh security alerts to SNS topics. The topics then distribute notifications to subscribed endpoints.

With SNS, Wazuh can send real-time alert notifications securely to users via SMS to their mobile devices. This enables responding promptly to critical security events detected by Wazuh agents across an environment. Using SNS topics decouples Wazuh from the underlying notification endpoints, allowing more flexibility in managing notifications.

SNS Endpoint
Figure 1: Message flow from Publisher to endpoint in SNS

The image above shows how Amazon SNS works. Publishers send data to the topics of their choice. Meanwhile, the subscriber(Lambda, SQS, etc ) receives messages from the topics to which it is subscribed.

How it works

The following diagram shows how the SMS notification is generated and delivered, from the SNS integration with Wazuh.

SNS integration workflow
Figure 2: SNS integration workflow

When the Wazuh server generates an alert from events received from a Wazuh agent, it is sent to a user-defined script. This happens if its alert level matches the specification within the Integration module.

The custom-sns-integration.py script which can be customized, determines the specific actions or responses triggered by the alert. The integration script parses the data received to shorten the description and remove the sensitive data from the Amazon Resource Name (ARN) for the SNS topic. Topic ARN is a unique identifier for the SNS topic that is used to route messages to subscribers. 

Once the data is in its final form, the message is created and sent to the SNS topic which has SMS subscribed and delivers the messages to register mobile devices. The script also logs all the errors and successes to the /var/ossec/logs/sns.log file.

Requirements

  • A pre-built, ready-to-use Wazuh OVA 4.7.1. Follow this guide to download the virtual machine (VM). This VM hosts the Wazuh central components (Wazuh server, Wazuh indexer, and Wazuh dashboard).
  • An AWS account that includes permissions for all SNS actions. We recommend using a dedicated IAM user with privileges limited to SNS permissions.
  • A Kali Linux endpoint as the attacker endpoint.
  • An  Ubuntu 22.04 endpoint with Wazuh agent 4.7.1 installed and enrolled to the Wazuh server. Refer to the Wazuh Linux installation guide to install the Wazuh agent.

Configuration

We configure the Wazuh server to access and send customized alerts to the AWS SNS, we create the topic and subscription in SNS and configure it to send received alerts via SMS to a mobile device.

Configure AWS credentials

Perform the following steps on the Wazuh server to authenticate using your AWS account and manage your resources from the command line.

1. Download and install AWS CLI:

# if [ -f /etc/lsb-release ]; then apt-get update -y && apt-get install -y unzip; elif [ -f /etc/centos-release ]; then yum update -y && yum install -y unzip; else echo "Unsupported OS. Can't install unzip."; fi
# curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
# unzip awscliv2.zip
# ./aws/install

2. Configure your AWS credentials: To do this, run the following command and follow the prompts to enter your AWS Access Key ID, AWS Secret Access Key, and AWS_REGION.

You can find your access keys in the AWS Management Console under “My Security Credentials.”

# /usr/local/bin/aws configure

3. Verify the configuration in ~/.aws/ directory, and check that your config and credentials files look as follows:

Config:

# vi ~/.aws/config

Output:

[default]
region = <AWS_REGION>
output = json

Configure AWS SNS

Navigate to SNS console on AWS to configure your topic and subscription.

Create an SNS topic

1. Go to Topics > Create topic to start creating a new topic. Choose a topic type as seen

SNS topic

NB: Take note of the Topic ARN after it has been created, as it will be used in the custom script below.

Create a subscription for the topic

1. After creating the Topic named Test, as illustrated in our example above, create a subscription for that topic. Change Protocol to SMS and enter a desired mobile number for the Endpoint.

Subscription for the topic

Wazuh server

Configure the Wazuh server to send specific levels of alert logs to the custom script that forwards logs to the SNS topic.

1. Add the integrator block within the <ossec_config> block in /var/ossec/etc/ossec.conf file:

<integration>
  <name>custom-sns-integration.py</name>
  <alert_format>json</alert_format>
  <level>10</level>
</integration>

The parameter <level> above can be modified to represent any alert level you want to capture and send over to the SNS topic.

2. Create a file /var/ossec/integrations/custom-sns-integration.py and add the custom integration script below to it. Modify the script by replacing the following variables; <AWS Access Key ID>,<AWS Secret Access Key>,<AWS_REGION> and <TOPIC_ARN>:

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

import boto3
import json
import logging
import sys
import os


# AWS SNS configuration
os.environ['AWS_ACCESS_KEY_ID'] = '<AWS Access Key ID>'
os.environ['AWS_SECRET_ACCESS_KEY'] = '<AWS Secret Access Key>'
os.environ['AWS_DEFAULT_REGION'] = '<AWS_REGION>'
region = '<AWS_REGION>'
sns_topic_arn = '<TOPIC_ARN>'


# Log file configuration
log_file_path = '/var/ossec/logs/sns.log'
#json_alert = {}

def send_alert_to_sns(alert_message):
    try:
        # Connect to SNS
        sns = boto3.client('sns', region_name=region)

        # Send the message to the topic
        sns.publish(TopicArn=sns_topic_arn, Message=alert_message)

        # Log success
        logging.info("Sent alert to SNS successfully")
    except Exception as e:
        # Log error
        logging.error(f"Error sending alert to SNS: {str(e)}")

def main(args):

    # Read args
    alert_file_location = args[1]
     # Load alert. Parse JSON object.
    with open(alert_file_location) as alert_file:
        json_alert = json.load(alert_file)

    try:

        # Extract relevant information from the alert for the message
        agent_id = json_alert['agent']['id']
        alert_level = json_alert['rule']['level']
        description = json_alert['rule']['description']

        # Create a message
        message = f"Agent ID: {agent_id}\nLevel: {alert_level}\nDescription: {description}"

        logging.info(message)
        send_alert_to_sns(message)

    except json.JSONDecodeError as json_error:
        # Log JSON decoding error
        logging.error(f"Error decoding JSON: {str(json_error)}")
    except KeyError as key_error:
        # Log missing key error
        logging.error(f"Key not found in JSON: {str(key_error)}")

    except FileNotFoundError:
        # Log file not found error
        logging.error("Alerts file not found")
    except Exception as e:
        # Log other exceptions
        logging.error(f"Error processing alerts: {str(e)}")

if __name__ == "__main__":
    try:

      # Configure logging to write to a file
      logging.basicConfig(filename=log_file_path, level=logging.INFO, format='%(asctime)s - %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')

      # Redirect stdout and stderr to the log file
      sys.stdout = open(log_file_path, 'a')
      sys.stderr = open(log_file_path, 'a')


      main(sys.argv)
    except Exception as e:
      logging.error(str(e))
      raise

3. Change the file permissions and ownership of the custom integration script:

# chmod 750 /var/ossec/integrations/custom-sns-integration.py
# chown root:wazuh /var/ossec/integrations/custom-sns-integration.py

4. Restart the wazuh-manager service to implement the changes made.

a) For Systemd:

# systemctl restart wazuh-manager

b) For SysV Init:

# service wazuh-manager restart

Generating a sample alert

Test the configuration by generating an alert based on what was specified within the integrator block in the /var/ossec/etc/ossec.conf file.

We will generate level 10 alerts by simulating an SSH brute force attack.

Kali endpoint

1. Run the command below to use Hydra to simulate a brute force attack for any monitored endpoint. Replace <VICTIM_IP_ADDRESS> with the IP address of your Ubuntu machine with a Wazuh agent:

$ sudo hydra -l test -P /usr/share/wordlists/dirb/small.txt ssh://<VICTIM_IP_ADDRESS>

NB: This action will trigger multiple alerts in your environment. Cancel the process as soon as an alert is generated.

Visualizing the alert

Navigate to Mobile >Text messaging (SMS) within the SNS console. The SNS console shows the delivery status of the SMS sent successfully and also shows other failures if any. The image below shows 17 successfully delivered SMS messages sent from the topic to your mobile device.

Text messaging (SMS) within the SNS console

Finally, alerts are received via SMS showing the description of the specified alert level configured on your Wazuh server.

Alerts via SMS showing

Conclusion

In this blog post, we demonstrate how to send Wazuh alerts as SMS messages to smartphones using the AWS SNS service. This way, you can receive timely and relevant notifications about the security events and incidents detected within your environment.

If you have any questions about this, do not hesitate to check out our documentation to learn more about Wazuh or join our community, where our team and contributors will assist you.