Cyber Threat Intelligence === :::info The Solution used during this project is Wazuh, it is composed of 3 principal components namely, ::: - WAZUH Indexer: it stores and indexes the data received by the Wazuh server. It enables fast search and analysis of large amounts of security data. - WAZUH Server: it is the central component of the platform. It receives data from the Wazuh agents, processes and analyzes it, and triggers alerts and notifications when security events are detected. The server includes a set of pre-defined rules and policies to detect common attack patterns and suspicious behavior. - WAZUH Dashboard: is a web-based user interface that provides visibility into the security events detected by the Wazuh platform. The dashboard displays alerts and notifications, system health metrics, and other relevant information in an easily digestible format. and an Agent: it collects security-related data from the endpoint it is installed on. The agent can collect information about the system configuration, file changes, process activity, network connections, and more. The agent then sends this data to the Wazuh server for processing and analysis. ![](https://hackmd.io/_uploads/S1QiXDRS2.png) source: wazuh documentation # Table of Content [TOC] ## Task 1. Wazuh deployment ### Step by step installation - To have a better understanding of wazuh components and how they interact a step by step installation was done. **1. Wazuh indexer** - Installation of Utilities ```!bash apt-get install debconf adduser procps apt-get install gnupg apt-transport-https ``` - Adding wazuh GPG key and repository ```!bash curl -s https://packages.wazuh.com/key/GPG-KEY-WAZUH | gpg --no-default-keyring --keyring gnupg-ring:/usr/share/keyrings/wazuh.gpg --import && chmod 644 /usr/share/keyrings/wazuh.gpg echo "deb [signed-by=/usr/share/keyrings/wazuh.gpg] https://packages.wazuh.com/4.x/apt/ stable main" | tee -a /etc/apt/sources.list.d/wazuh.list ``` - The next step is to download the cert-tools to encrypt communication between wazuh components and config.yml which is wazuh's configuration file ``` curl -sO https://packages.wazuh.com/4.4/wazuh-certs-tool.sh curl -sO https://packages.wazuh.com/4.4/config.yml ``` - Edit config.yml with ip address and server names of your wazuh components. Since this is not a multi-node cluster all the components are based on the same node. | | | -------- | | ![](https://i.imgur.com/AimqnCU.png) Fig.1 config.yml| - Generate the certificates as shown below | | | -------- | | ![](https://i.imgur.com/fXjuh9G.png) Fig.2. certificate generation | - Next, install the indexer with the command `sudo apt-get -y install wazuh-indexer` - Copy the certificates to `/etc/wazuh-indexer/certs` and modify the file owner and permissions as shown below: || | -------- | | ![](https://i.imgur.com/jtkfZHP.png) fig.3. Certs | - Enable and start wazuh-indexer with the commands below: ```!bash systemctl daemon-reload systemctl enable wazuh-indexer systemctl start wazuh-indexer ``` - Cluster Initialization | | | -------- | | ![](https://i.imgur.com/kQQY0jf.png) Fig.4. init cluster | | | | -------- | | ![](https://i.imgur.com/LsjaGfL.png) Fig.5. testing installation | **2. Wazuh server** - Installation of wazuh manager `apt-get -y install wazuh-manager` - Enable and start wazuh-manager ```!bash systemctl daemon-reload systemctl enable wazuh-manager systemctl start wazuh-manager ``` | | | -------- | | ![](https://i.imgur.com/FfgkBZP.png) Fig.6. Wazuh manager status | - Installation of filebeat `apt-get -y install filebeat` | | | -------- | | ![](https://i.imgur.com/0K0tepa.png) Fig.7. test filebeat| **3. Wazuh Dashboard** `apt-get install debhelper tar curl libcap2-bin` `apt-get -y install wazuh-dashboard` - Deploy the certificates for wazuh-dashboard ```!bash mkdir /etc/wazuh-dashboard/certs tar -xf ./wazuh-certificates.tar -C /etc/wazuh-dashboard/certs/ ./$NODE_NAME.pem ./$NODE_NAME-key.pem ./root-ca.pem mv -n /etc/wazuh-dashboard/certs/$NODE_NAME.pem /etc/wazuh-dashboard/certs/dashboard.pem mv -n /etc/wazuh-dashboard/certs/$NODE_NAME-key.pem /etc/wazuh-dashboard/certs/dashboard-key.pem chmod 500 /etc/wazuh-dashboard/certs chmod 400 /etc/wazuh-dashboard/certs/* chown -R wazuh-dashboard:wazuh-dashboard /etc/wazuh-dashboard/certs ``` - Enable and start wazuh-dashboard ```!bash systemctl daemon-reload systemctl enable wazuh-dashboard systemctl start wazuh-dashboard ``` | | | -------- | |![](https://i.imgur.com/Tck8Was.png) Fig.8. Wazuh dashboard| **4. Enrolling Windows Agent** - To deploy a windows agent, we selected the windows operating system, version and wazuh server IP address as shown in the images below: | | | -------- | |![](https://i.imgur.com/GYPL0Zz.png) ![](https://i.imgur.com/Iyqe1vV.png) Fig.9. Windows agent enrollment | - We ran the scripts on powershell in admin mode and started the wazuh agent service as shown in the below image. - After refreshing the agents dashboard, the newly enrolled windows agent appears. | | | -------- | |![](https://i.imgur.com/zlF5csl.png) ![](https://i.imgur.com/ATfuonr.png) Fig.10. powershell command | **5. Enrolling Linux Agents** The same procedure is followed for linux agents. But on the agent side the code is ran in a bash shell | | | -------- | | ![](https://i.imgur.com/qh7OxaH.png) ![](https://i.imgur.com/iu7iHnr.png) Fig.11. Enrolling multiple linux agents| After enrolling the different agents, on our dashboard we had the result shown below || | -------- | | ![](https://i.imgur.com/nfhqboD.png) Fig.12. All agents| ## Task 2. SIEM capabilities in action Wazuh provides a numerous possibilities for Security Operations Center (SOC) implementation such as: * Log Data Analysis * Cloud Security * Container Security * File Integrity Monitoring * Intrusion Detection * Security Audit and Analytics * Vulnerability Detection * Policy Auditing * Monitoring Logons * Incident Response During this project we implemented some of these features, ### 1. File Integrity Monitoring(FIM): FIM monitors and alerts on changes made to critical system files in real-time, using customizable detection rules. It can be used to comply with regulatory standards such as PCI DSS and HIPAA, and comes with a web-based user interface for managing and visualizing alerts. Overall, Wazuh's FIM module is a crucial tool for monitoring and detecting security threats, and is highly customizable and easy to integrate into existing security infrastructure. Configuring **FIM** is done both on the agent and server side. #### 1. Configuring Agents - [x] **Linux Agents:** Edit the Wazuh agent `/var/ossec/etc/ossec.conf` configuration file to add the following line which will specify the folder or directory to monitor. ``` <directories check_all="yes" report_changes="yes" realtime="yes">/home/devops/FIM_POC</directories> ``` | | | -------- | | ![](https://i.imgur.com/HnmoRWN.png) Fig.13. FIM configuration| This will enable FIM for a folder created in the users home directory named **FIM_POC**. Then restart the wazuh agent to apply the setting. `sudo systemctl restart wazuh-agent` - [x] **Windows Agent:** Edit the `C:\Program Files (x86)\ossec-agent\ossec.conf` configuration file on the monitored Windows endpoint. Add the directories for monitoring within the **<syscheck\>** block as follows: ``` <directories check_all="yes" report_changes="yes" realtime="yes">C:\Users\user1\Desktop\FIM_POC</directories> ``` Then from a powershell terminal with admin priviledges, restart the agent by running `Restart-Service -Name wazuh` #### 2. Testing FIM With the above configurations done, Changes brought to the monitored directories will trigger alerts as follows: - **Alert with Rule ID 550** is triggered if changes a brought to any file in the monitored directory. - **Alert with Rule ID 553** is triggered if a file present in the monitored directory is deleted. - **Alert with Rule ID 554** is triggered if a file is added to the monitored directory. To test this, we did create a bash script to execute the different phases as follows: ```sh= #!/bin/bash touch /home/devops/FIM_POC/file1 sleep 5 echo "Hello World" >> /home/devops/FIM_POC/file1 sleep 5 rm /home/devops/FIM_POC/file1 ``` | | | -------- | |![](https://i.imgur.com/KhyJhDd.png) ![](https://i.imgur.com/fPkQRIR.png) Fig.14. Alerts triggered on the Linux Server| ### 2. Vulnerability Detection: Wazuh helps organizations identify and remediate security weaknesses in their IT systems through vulnerability detection features such as **OpenVAS integration, asset inventory, configuration assessment**, and **log analysis**. These features provide a comprehensive approach to identifying and mitigating security vulnerabilities in IT systems. Configuring **Vulnerability Detection** is done on the Server's end by editing the `/var/ossec/etc/ossec.conf` to enable the **Vulnerability Detector module** as follows: | | | -------- | | ![](https://i.imgur.com/RaiFrpC.png) Fig.15. Enabling Vulnerabilty Detector| Then restart the Wazuh manager to apply the configuration changes with the following command `sudo systemctl restart wazuh-manager`. Next phase is to test the detectors. Open the dashboard and select any monitored agent and select the vulnerabilities section as follows: | | | -------- | |![](https://i.imgur.com/qvW21WE.png) Fig.16. Vulnerabilities on linux agent | | | | -------- | |![](https://i.imgur.com/f4FyhRW.png) Fig.17. Vulnerabilities on Windows agent | ### 3. Detecting Brute force Attack: Wazuh identifies brute-force attacks by correlating multiple authentication failure events. To simulate this we'll make use of hydra, which is a fast and flexible login cracker which can be used on both Linux and Windows and used to perform rapid dictionary attacks against more than 50 protocols. In this section we'll be installing Hydra on our attacker machine and did create two wordlists; **user.txt** and **passwd.txt** containing random usernames and passwords. | | | -------- | |![](https://i.imgur.com/iY0jH4S.png) Fig.18. Users file | | | | -------- | | ![](https://i.imgur.com/FMagwpr.png) Fig.19. Password file| Then run the following command to simulate an ssh bruteforce on the monitored linux agent: ```!shell hydra -L user.txt -P passwd.txt ssh://10.1.1.47 ``` | | | -------- | | ![](https://i.imgur.com/XCpzU4y.png) ![](https://i.imgur.com/gsAYtTy.png) Fig.20. Wazuh server detecting Bruteforce attempts on linux | To launch attack on windows endpoint, run the following command which will use the RDP protocol: ```shell= hydra -L user.txt -P passwd.txt rdp://10.1.1.77 ``` | | | -------- | | ![](https://i.imgur.com/AuTFoNg.png) ![](https://i.imgur.com/o232BR8.png) Fig.21. Wazuh server detecting Bruteforce attempts on Windows | ### 4. Incidence Response: Wazuh can be integrated with The Hive for case management and incidence response. - To install The Hive we followed: [reference](https://docs.thehive-project.org/thehive/legacy/thehive3/installation/install-guide/) After installation, create an Organization under TheHive dashboard and your organization members (SOC team) and an additional user for API key management | | | -------- | |![](https://i.imgur.com/BTDe15y.png) Fig.22. TheHive interface| - On wazuh server After generating the API key, install thehive on wazuh server with the command below. `sudo /var/ossec/framework/python/bin/pip3 install thehive4py==1.8.1` || | -------- | | ![](https://i.imgur.com/VP9kTff.png) Fig.23. configuring the server| After installation add the python code present in the Appendix section 1 under `/var/ossec/integrations/custom-w2thive.py` and create a bash script under `/var/ossec/integrations/custom-w2thive` with the bash code present in Appendix section 2. Once done set the appropriate access rights ```!shell sudo chmod 755 /var/ossec/integrations/custom-w2thive.py sudo chmod 755 /var/ossec/integrations/custom-w2thive sudo chown root:ossec /var/ossec/integrations/custom-w2thive.py sudo chown root:ossec /var/ossec/integrations/custom-w2thive ``` - Finally add the appropriate ossec rule in `/var/ossec/etc/ossec.conf.` ```!xml <ossec_config> … <integration> <name>custom-w2thive</name> <hook_url>http://TheHive_Server_IP:9000</hook_url> <api_key>API-KEY</api_key> <alert_format>json</alert_format> </integration> … </ossec_config> ``` ### 5. Container Security: **On the Wazuh agent** - Run the following commands on the agent with docker engine to install the necessary dependencies: ```bash! sudo apt update && sudo apt -y install python3 sudo pip3 install --upgrade pip sudo apt -y update && sudo apt -y install python3-pip sudo pip3 install docker ``` >[color=#10e] *To monitor the containers, we will use docker listener module.* - Edit the `/var/ossec/etc/ossec.conf` file on the docker VM *(the vm hosting the containers)*, by adding the following configuration: ```xml= <!-- Container Monitoring --> <wodle name="docker-listener"> <disabled>no</disabled> </wodle> ``` | | | -------- | |![](https://i.imgur.com/Lr7pxzR.png) Fig.24. agent configuration | - Run the following command to enable the wazuh agent receive remote commands from the wazuh server ```sh= echo "logcollector.remote_commands=1" >> /var/ossec/etc/local_internal_options.conf ``` >[color=#10e] *NB: Remote commands are disabled by default on the wazuh agents for security.* - Restart the wazuh agent service using the below command: ```sh= sudo systemctl restart wazuh-agent ``` **On the Wazuh Server:** - Elevate privilege to root and run the following command to create an agent group called `container`. ```sh= /var/ossec/bin/agent_groups -a -g container -q ``` - Run the below command to acquire the ID for all wazuh agents: ```sh= /var/ossec/bin/manage_agents -l ``` - Add the wazuh agent(s) on the docker VM(s) (running the containers) to the docker container group created in the earlier step using the following command: ```sh= /var/ossec/bin/agent_groups -a -i <AGENT_ID> -g container -q ``` >[color=#10e] *In this case, agent ID is **004**.* | | | -------- | | ![](https://i.imgur.com/qQR1Ruu.png) Fig.25. server configuration | :::spoiler Docker listener configuration file (agent.conf) ```xml! <agent_config> <!-- Configuration to enable Docker listener module. --> <wodle name="docker-listener"> <interval>10m</interval> <attempts>5</attempts> <run_on_start>yes</run_on_start> <disabled>no</disabled> </wodle> <!-- Command to extract container resources information. --> <localfile> <log_format>command</log_format> <command>docker stats --format "{{.Container}} {{.Name}} {{.CPUPerc}} {{.MemUsage}} {{.MemPerc}} {{.NetIO}}" --no-stream</command> <alias>docker container stats</alias> <frequency>120</frequency> <out_format>$(timestamp) $(hostname) docker-container-resource: $(log)</out_format> </localfile> <!-- Command to extract container health information. --> <localfile> <log_format>command</log_format> <command>docker ps --format "{{.Image}} {{.Names}} {{.Status}}"</command> <alias>docker container ps</alias> <frequency>120</frequency> <out_format>$(timestamp) $(hostname) docker-container-health: $(log)</out_format> </localfile> </agent_config> ``` ::: - Edit the `/var/ossec/etc/shared/container/agent.conf` file by entering the configuration above to enable docker listener module for gathering container information. :::spoiler decoder file (docker_decoders.xml) ```xml= <!-- Decoder for container resources information. --> <decoder name="docker-container-resource"> <program_name>^docker-container-resource</program_name> </decoder> <decoder name="docker-container-resource-child"> <parent>docker-container-resource</parent> <prematch>ossec: output: 'docker container stats':</prematch> <regex>(\S+) (\S+) (\S+) (\S+) / (\S+) (\S+) (\S+) / (\S+)</regex> <order>container_id, container_name, container_cpu_usage, container_memory_usage, container_memory_limit, container_memory_perc, container_network_rx, container_network_tx</order> </decoder> <!-- Decoder for container health information. --> <decoder name="docker-container-health"> <program_name>^docker-container-health</program_name> </decoder> <decoder name="docker-container-health-child"> <parent>docker-container-health</parent> <prematch>ossec: output: 'docker container ps':</prematch> <regex offset="after_prematch" type="pcre2">(\S+) (\S+) (.*?) \((.*?)\)</regex> <order>container_image, container_name, container_uptime, container_health_status</order> </decoder> ``` ::: - Create a decoder file named `docker_decoders.xml` in the `/var/ossec/etc/decoders/` directory and add the configuration above to decode logs received from the wazuh agent :::spoiler rules (docker_rules.xml) ```xml= <group name="container,"> <!-- Rule for container resources information. --> <rule id="100100" level="5"> <decoded_as>docker-container-resource</decoded_as> <description>Docker: Container $(container_name) Resources</description> <group>container_resource,</group> </rule> <!-- Rule to trigger when container CPU and memory usage are above 80%. --> <rule id="100101" level="12"> <if_sid>100100</if_sid> <field name="container_cpu_usage" type="pcre2">^(0*[8-9]\d|0*[1-9]\d{2,})</field> <field name="container_memory_perc" type="pcre2">^(0*[8-9]\d|0*[1-9]\d{2,})</field> <description>Docker: Container $(container_name) CPU usage ($(container_cpu_usage)) and memory usage ($(container_memory_perc)) is over 80%</description> <group>container_resource,</group> </rule> <!-- Rule to trigger when container CPU usage is above 80%. --> <rule id="100102" level="12"> <if_sid>100100</if_sid> <field name="container_cpu_usage" type="pcre2">^(0*[8-9]\d|0*[1-9]\d{2,})</field> <description>Docker: Container $(container_name) CPU usage ($(container_cpu_usage)) is over 80%</description> <group>container_resource,</group> </rule> <!-- Rule to trigger when container memory usage is above 80%. --> <rule id="100103" level="12"> <if_sid>100100</if_sid> <field name="container_memory_perc" type="pcre2">^(0*[8-9]\d|0*[1-9]\d{2,})</field> <description>Docker: Container $(container_name) memory usage ($(container_memory_perc)) is over 80%</description> <group>container_resource,</group> </rule> <!-- Rule for container health information. --> <rule id="100105" level="5"> <decoded_as>docker-container-health</decoded_as> <description>Docker: Container $(container_name) is $(container_health_status)</description> <group>container_health,</group> </rule> <!-- Rule to trigger when a container is unhealthy. --> <rule id="100106" level="12"> <if_sid>100105</if_sid> <field name="container_health_status">^unhealthy$</field> <description>Docker: Container $(container_name) is $(container_health_status)</description> <group>container_health,</group> </rule> </group> ``` ::: - After completing previous steps, write a rule into a file `docker_rules.xml` in the `/var/ossec/etc/rules/` directory with the configuration above - Restart the wazuh-manager service using the command: ```sh= systemctl restart wazuh-manager ``` **Testing Container Monitoring** - To test the docker monitoring, initiate a docker command. The logs are then visible on the wazuh dashboard. | | | -------- | | ![](https://i.imgur.com/tFbqYpR.png) Fig.26. docker event logs 1| | | | -------- | | ![](https://i.imgur.com/y82bzVH.png) Fig.27. docker event logs 2 | | | | -------- | | ![](https://i.imgur.com/vs8gRVx.png) Fig.28. docker event logs 3 | | | | -------- | | ![](https://i.imgur.com/DhguaKi.png) Fig.29. docker event logs 4 | ### 6. Simulating packet capture attack #### 1. Network sniffing attack | | | -------- | | ![](https://i.imgur.com/cMd3Y3Q.png) Fig.30. Network Sniffing | ### 7. Integration with a with a SOAR solution : shuffle. SOAR stands for Security Orchestration, Automation, and Response. It refers to a technology stack that allows organizations to collect, analyze, and respond to security threats in a coordinated and efficient manner. SOAR platforms typically integrate with a variety of security tools and data sources to provide a centralized view of security events and automate incident response workflows. This can include tools such as Security Information and Event Management (SIEM) systems, Endpoint Detection and Response (EDR) solutions, threat intelligence feeds, and more. for deployment we used the container image of shuffle | | | -------- | | ![](https://i.imgur.com/DTjw3T0.png) Fig.31. Shuffle container| - To integrate shuffle to Wazuh, some modifications need to be made on the wazuh server. Download shuffle integration files for wazuh (https://github.com/Shuffle/Shuffle/blob/main/functions/extensions/wazuh/) and add this files to the wazuh integration folder `/var/ossec/integrations` After adding the files, change the ownership to `root:wazuh` and permissions to `750` | | | -------- | | ![](https://i.imgur.com/qz50X7w.png) Fig.32. Integration files| After adding the integration files, add the integration module in `/var/ossec/etc/ossec.conf` for wazuh to use this files. in this configuration a webhook API has been added to establish a secure communication between wazuh and shuffle | | | -------- | | ![](https://i.imgur.com/kE7ZOzA.png) Fig.33. apply integration | After configuration, restart the wazuh-manager with the command `sudo systemctl restart wazuh-manager` and to verify if the communication is established open the integration log files. It was successful since the return code was HTTP 200 | | | -------- | | ![](https://i.imgur.com/tElSuGk.png) Fig.34. Integration logs | On shuffle workflow we could retrieve the logs from the different endpoints | | | -------- | | ![](https://i.imgur.com/9pVQLj2.png) Fig.35. logs retrieved from wazuh| | | | -------- | | ![](https://i.imgur.com/2YC37bJ.png) Fig.36. A log sample| ## Task 3. Correlation of Wazuh security events with MITRE ATT&CK techniques. - Previously a Brute Force attack has been made on the agent 10.1.1.47. On **ATT&CK Matrix** Brute force is classified as a **Credential Access** Technique with code number **T1110** | | | -------- | | ![](https://i.imgur.com/KbrEluW.png) Fig.37. Brute force on attack matrix| This can equally be verified in Wazuh MITRE ATT&CK menu as shown below: | | | -------- | | ![](https://i.imgur.com/JMUhGir.png) Fig.38. wazuh mitre attack matrix | | | | -------- | | ![](https://i.imgur.com/7DG8uZT.png) Fig.39. brute force attack | - A Network sniffing attack has been performed on 10.1.1.35 On **ATT&CK Matrix** network sniffing is classified as a **Discovery** Technique with code number **T1040** | | | -------- | | ![](https://i.imgur.com/1lymw82.png) Fig.40. sniffing on attack matrix| | | | -------- | | ![](https://i.imgur.com/y5kZe7c.png) Fig.41. wazuh mitre attack matrix | | | | ------- | | ![](https://i.imgur.com/zQOOSbD.png) Fig.42. Network sniffing | ### Incidence Response (continue) In a SOC environment once a SOC analyst L1 detects a True positive incident, he opens a case and the SOC manager elevates the incidence to the SOC analyst L2 (incidence responder) who is in charge of performing Forensics, malware analysis and other activities in order to identify and mitigate the problem. - Once you detect an incidence under wazuh dashboard open a case for the incidence under TheHive as shown below: | | | -------- | |![](https://i.imgur.com/gdxqdFj.png) Fig.43. Opening a case | - After you open the case, add tasks and assign to incidence responders | | | -------- | |![](https://i.imgur.com/2RQaddB.png) Fig.44. assign tasks | - Once this is done the incident responder can visualize the case on his dashboard and once it is solved he can add information on the work done and close the task. Once every tasks are closed the SOC manager can close the case | | | -------- | | ![](https://i.imgur.com/ssUyIEa.png) Fig.45. incident responder | ## APPENDIX ### Section 1: :::spoiler custom-w2thive.py ```!py #!/var/ossec/framework/python/bin/python3 import json import sys import os import re import logging import uuid from thehive4py.api import TheHiveApi from thehive4py.models import Alert, AlertArtifact #start user config # Global vars #threshold for wazuh rules level lvl_threshold=0 #threshold for suricata rules level suricata_lvl_threshold=3 debug_enabled = False #info about created alert info_enabled = True #end user config # Set paths pwd = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) log_file = '{0}/logs/integrations.log'.format(pwd) logger = logging.getLogger(__name__) #set logging level logger.setLevel(logging.WARNING) if info_enabled: logger.setLevel(logging.INFO) if debug_enabled: logger.setLevel(logging.DEBUG) # create the logging file handler fh = logging.FileHandler(log_file) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) logger.addHandler(fh) def main(args): logger.debug('#start main') logger.debug('#get alert file location') alert_file_location = args[1] logger.debug('#get TheHive url') thive = args[3] logger.debug('#get TheHive api key') thive_api_key = args[2] thive_api = TheHiveApi(thive, thive_api_key ) logger.debug('#open alert file') w_alert = json.load(open(alert_file_location)) logger.debug('#alert data') logger.debug(str(w_alert)) logger.debug('#gen json to dot-key-text') alt = pr(w_alert,'',[]) logger.debug('#formatting description') format_alt = md_format(alt) logger.debug('#search artifacts') artifacts_dict = artifact_detect(format_alt) alert = generate_alert(format_alt, artifacts_dict, w_alert) logger.debug('#threshold filtering') if w_alert['rule']['groups']==['ids','suricata']: #checking the existence of the data.alert.severity field if 'data' in w_alert.keys(): if 'alert' in w_alert['data']: #checking the level of the source event if int(w_alert['data']['alert']['severity'])<=suricata_lvl_threshold: send_alert(alert, thive_api) elif int(w_alert['rule']['level'])>=lvl_threshold: #if the event is different from suricata AND suricata-event-type: alert check lvl_threshold send_alert(alert, thive_api) def pr(data,prefix, alt): for key,value in data.items(): if hasattr(value,'keys'): pr(value,prefix+'.'+str(key),alt=alt) else: alt.append((prefix+'.'+str(key)+'|||'+str(value))) return alt def md_format(alt,format_alt=''): md_title_dict = {} #sorted with first key for now in alt: now = now[1:] #fix first key last symbol dot = now.split('|||')[0].find('.') if dot==-1: md_title_dict[now.split('|||')[0]] =[now] else: if now[0:dot] in md_title_dict.keys(): (md_title_dict[now[0:dot]]).append(now) else: md_title_dict[now[0:dot]]=[now] for now in md_title_dict.keys(): format_alt+='### '+now.capitalize()+'\n'+'| key | val |\n| ------ | ------ |\n' for let in md_title_dict[now]: key,val = let.split('|||')[0],let.split('|||')[1] format_alt+='| **' + key + '** | ' + val + ' |\n' return format_alt def artifact_detect(format_alt): artifacts_dict = {} artifacts_dict['ip'] = re.findall(r'\d+\.\d+\.\d+\.\d+',format_alt) artifacts_dict['url'] = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',format_alt) artifacts_dict['domain'] = [] for now in artifacts_dict['url']: artifacts_dict['domain'].append(now.split('//')[1].split('/')[0]) return artifacts_dict def generate_alert(format_alt, artifacts_dict,w_alert): #generate alert sourceRef sourceRef = str(uuid.uuid4())[0:6] artifacts = [] if 'agent' in w_alert.keys(): if 'ip' not in w_alert['agent'].keys(): w_alert['agent']['ip']='no agent ip' else: w_alert['agent'] = {'id':'no agent id', 'name':'no agent name'} for key,value in artifacts_dict.items(): for val in value: artifacts.append(AlertArtifact(dataType=key, data=val)) alert = Alert(title=w_alert['rule']['description'], tlp=2, tags=['wazuh', 'rule='+w_alert['rule']['id'], 'agent_name='+w_alert['agent']['name'], 'agent_id='+w_alert['agent']['id'], 'agent_ip='+w_alert['agent']['ip'],], description=format_alt , type='wazuh_alert', source='wazuh', sourceRef=sourceRef, artifacts=artifacts,) return alert def send_alert(alert, thive_api): response = thive_api.create_alert(alert) if response.status_code == 201: logger.info('Create TheHive alert: '+ str(response.json()['id'])) else: logger.error('Error create TheHive alert: {}/{}'.format(response.status_code, response.text)) if __name__ == "__main__": try: logger.debug('debug mode') # if debug enabled # Main function main(sys.argv) except Exception: logger.exception('EGOR') ``` ::: ### Section 2 : :::spoiler custom-w2thive ```bash! #!/bin/sh # Copyright (C) 2015-2020, Wazuh Inc. # Created by Wazuh, Inc. <info@wazuh.com>. # This program is free software; you can redistribute it and/or modify it under the terms of GP> WPYTHON_BIN="framework/python/bin/python3" SCRIPT_PATH_NAME="$0" DIR_NAME="$(cd $(dirname ${SCRIPT_PATH_NAME}); pwd -P)" SCRIPT_NAME="$(basename ${SCRIPT_PATH_NAME})" case ${DIR_NAME} in */active-response/bin | */wodles*) if [ -z "${WAZUH_PATH}" ]; then WAZUH_PATH="$(cd ${DIR_NAME}/../..; pwd)" fi PYTHON_SCRIPT="${DIR_NAME}/${SCRIPT_NAME}.py" ;; */bin) if [ -z "${WAZUH_PATH}" ]; then WAZUH_PATH="$(cd ${DIR_NAME}/..; pwd)" fi PYTHON_SCRIPT="${WAZUH_PATH}/framework/scripts/${SCRIPT_NAME}.py" ;; */integrations) if [ -z "${WAZUH_PATH}" ]; then WAZUH_PATH="$(cd ${DIR_NAME}/..; pwd)" fi PYTHON_SCRIPT="${DIR_NAME}/${SCRIPT_NAME}.py" ;; esac ${WAZUH_PATH}/${WPYTHON_BIN} ${PYTHON_SCRIPT} $@ ``` ::: **Reference:** 1. https://wazuh.com/blog/docker-container-security-monitoring-with-wazuh/