Simulating Attacks and Analyzing Logs in Your Cybersecurity Home Lab

IritT
32 min readDec 4, 2024

--

Cybersecurity is not just about defending systems — it’s about understanding how attackers think and operate. By learning to simulate common attacks like port scanning, brute force attacks, DoS (Denial of Service), and Pass-the-Hash, you gain valuable hands-on experience with offensive techniques. This knowledge is key to improving your defense strategies.

Why Simulate Attacks?

Recognize attack patterns: Learn to spot signs of attacks early.

Enhance defense strategies: Understand how attackers exploit vulnerabilities so you can build better defenses.

Practice using real tools: Get familiar with powerful tools like Kali Linux, Snort, Splunk, and Sysmon, which help you detect and respond to real-world threats.

In this lab, we will simulate four common types of attacks and analyze how they work and their risks. You’ll also learn how to detect and prevent these attacks using industry-standard tools.

Configuring Event Logging and Custom Rules in PowerShell

Proper logging and firewall configuration are essential for detecting suspicious activity and generating meaningful alerts. Here’s how to configure your firewall and logs in PowerShell.

Configuring Windows Firewall in PowerShell

  1. Allow Incoming ICMP (Ping) Traffic: This rule allows ICMP ping requests to pass through your firewall. Pinging is used by attackers to check if a system is online.
New-NetFirewallRule -DisplayName "Allow ICMPv4-In" -Protocol ICMPv4 -Direction Inbound -Action Allow -Enabled True

2. Allow Specific TCP/UDP Traffic (Ports 80 and 443 for HTTP/HTTPS): HTTP (Port 80) and HTTPS (Port 443) are common web service ports. You can allow traffic on these ports if your system is running a web server.

New-NetFirewallRule -DisplayName "Allow HTTP" -Protocol TCP -LocalPort 80 -Direction Inbound -Action Allow -Enabled True
New-NetFirewallRule -DisplayName "Allow HTTPS" -Protocol TCP -LocalPort 443 -Direction Inbound -Action Allow -Enabled True

3. Allow Traffic from Specific IP (e.g., Kali Machine): If you want to allow traffic from a particular IP (your Kali Linux machine), create a rule like this:

New-NetFirewallRule -DisplayName "Allow Kali IP" -Direction Inbound -Protocol TCP -LocalPort 6666 -RemoteAddress <Attacker_IP>-Action Allow
New-NetFirewallRule -DisplayName "192.168.19.15" -Direction Inbound -Protocol TCP -LocalPort 6666 -RemoteAddress 192.168.19.15 -Action Allow

Simulate Attacks and Analyze Logs

Once your firewall and logging systems are set up, it’s time to simulate common attacks and analyze the resulting logs. Common attacks include port scans, brute force attacks, and DoS attacks. We’ll first focus on port scanning, a reconnaissance technique commonly used by attackers.

First Attack: Understanding and Defending Against Port Scanning

Port scanning is a common reconnaissance technique used by attackers to identify potential vulnerabilities in a system. Attackers use this method to probe a target machine by identifying open ports that can be exploited. Think of it as a burglar trying different doors on a building to see which ones are unlocked. Once the attacker identifies an open port, it can serve as a potential entry point into the system.

How Does Port Scanning Work?

  1. Probing the System: Attackers use a tool like nmap to send small signals to various ports on a target system. If the system responds to certain signals, the attacker knows that the port is open and potentially usable.
  2. Identifying Open Ports: A system has many ports (65,535 in total), but only some are open to the outside world. Common open ports might include:

Port 22 for SSH (secure login).

Port 80 for HTTP (web traffic).

Port 443 for HTTPS (secure web traffic).

Attackers look for these open ports to exploit vulnerabilities in the services running on them.

Why Do Attackers Use Port Scanning?

  1. To Discover Open Ports: Open ports are entry points that allow attackers to access the system. Common ports like 22 (SSH) and 80 (HTTP) are often targeted.
  2. To Identify Running Services: Attackers can probe open ports to identify the software running on them, allowing them to find vulnerabilities.
  3. To Plan Exploits: Once attackers know which ports are open and what services are running, they can craft specific attacks.

How Attackers Perform a Port Scan

The most common tool attackers use for port scanning is nmap.

nmap -sS -p- -T4 -A -v <Target_IP>
nmap -sS -p- -T4 -A -v 192.168.1.12

nmap: The tool used for network scanning.

-sS: Performs a “stealth scan” that sends SYN packets to probe ports without completing a full connection, reducing the likelihood of detection.

-p-: Scans all 65,535 ports on the target.

T: sets the timing template for the scan. Timing templates control the speed and stealthiness of the scan. The values range from -T0 (paranoid) to -T5 (insane). -T4 is a good balance, making the scan faster but still relatively stealthy. It is often used for real-world penetration testing because it speeds up the process without triggering too many alerts.

-A: enables multiple advanced scan features in nmap:

OS Detection: Identifies the operating system running on the target machine.

Version Detection: Detects versions of services running on open ports.

Script Scanning: Runs nmap’s scripting engine (NSE) to check for vulnerabilities or gather more information.

Traceroute: Traces the route packets take to reach the target, helping identify where the target is located in the network.

<Target_IP>: Replace this with the IP address of your Windows 10 target machine.

Risks of Port Scanning

If attackers successfully identify open ports on your system, they may:

Gain unauthorized access by exploiting weak or vulnerable services.

Cause a data breach by extracting sensitive information.

Compromise the entire network by moving laterally from the initial system.

How to Defend Against Port Scanning

Defending against port scanning involves both preventative and detective measures.

  1. Minimize Open Ports: Disable unused services to close unnecessary ports. For example, if you’re not using SSH (port 22), disable it.
  2. Use Windows Firewall: Create specific firewall rules to block unused ports or allow traffic only from trusted IP addresses.
  3. Enable Firewalls and Intrusion Detection Systems: Snort (IDS tool) that can be configured to detect SYN Flood attempts.

A Snort rule to detect such attacks:

alert tcp any any -> any any (msg:"Port Scan Detected"; flags:S; threshold:type both, track by_src, count 20, seconds 30; sid:1000001;)

View Alerts in Snort

Access pfSense Dashboard: Log in to your pfSense web interface.

Navigate to the Snort Package:

Go to Services in the top menu.

Select Snort from the dropdown.

Check the Alerts Tab:

Inside the Snort settings, you’ll find several tabs, including Interfaces, Global Settings, and Alerts.

Click on the Alerts tab to view logs for any detected alerts.

4. Update Software and Services: Ensure all services running on open ports of the Windows 10 target are updated and patched to avoid exploitation.

5. Use Port-Knocking: Port-knocking is a technique where ports remain closed until a specific sequence of network packets is received, adding an extra layer of protection.

6. Monitor Logs: Use tools like Splunk to analyze network logs and detect suspicious activities.

Splunk query to identify repeated scan attempts:

index=* sourcetype="auth" host=* "Possible IP Scan"
| rex field=_raw "Possible IP Scan {TCP} (?<src_ip>\d+\.\d+\.\d+\.\d+):(?<src_port>\d+) -> (?<dst_ip>\d+\.\d+\.\d+\.\d+):(?<dst_port>\d+)"
| table _time, src_ip, src_port, dst_ip, dst_port, _raw

index=*: This searches across all indexes in Splunk. If you know the specific index where your logs are stored (e.g., pfSense), you can replace * with the specific index name, which will improve search performance.

sourcetype=”auth”: This filters the search to logs with the auth sourcetype, likely coming from /var/log/auth.log, where Snort-related authentication and network logs might be stored.

host=*: The host=* filter means logs can come from any machine, which is flexible but could be more specific if you want to narrow down to logs from specific devices (host=”kali”).

“Possible IP Scan”: This ensures that only logs containing the phrase “Possible IP Scan” are returned. It’s a good way to filter for Snort detection events related to IP scanning.

| rex field=_raw “Possible IP Scan {TCP} (?<src_ip>\d+\.\d+\.\d+\.\d+):(?<src_port>\d+) -> (?<dst_ip>\d+\.\d+\.\d+\.\d+):(?<dst_port>\d+)”:

The rex command extracts fields from the raw log using regular expressions:

(?<src_ip>\d+\.\d+\.\d+\.\d+): Captures the source IP address.

(?<src_port>\d+): Captures the source port.

(?<dst_ip>\d+\.\d+\.\d+\.\d+): Captures the destination IP address.

(?<dst_port>\d+): Captures the destination port.

| table _time, src_ip, src_port, dst_ip, dst_port, _raw:

The table command formats the output to display the following columns:

_time: The timestamp of the event.

src_ip: The source IP of the scan.

src_port: The source port number used in the scan.

dst_ip: The destination IP being scanned.

dst_port: The destination port being targeted.

_raw: The complete raw log entry for context.

Second Attack: Understanding and Defending Against SYN Flood Attack

A SYN Flood attack is a type of Denial-of-Service (DoS) attack in which an attacker sends a large number of SYN (synchronize) packets to a target system without completing the TCP handshake. The goal is to exhaust the target’s resources (such as memory or connection slots), rendering the service unavailable to legitimate users. In this specific case, the attacker often uses randomized source IP addresses to make it harder for the target to block the attack.

A SYN Flood attack exploits the TCP three-way handshake, which is a process that establishes a connection between a client and server. The attack disrupts this process by sending multiple SYN packets without completing the handshake, leading to resource exhaustion on the target system.

Why Do Attackers Use SYN Floods?

  1. Service Disruption: The attack overloads the server, making it unresponsive to legitimate requests.
  2. Resource Exhaustion: Flooding the target with SYN packets consumes system resources like memory and CPU.
  3. Evasion of Detection: Using randomized source IPs makes it challenging to trace the attack back to the origin or to block it with simple rules.

How Attackers Perform a SYN Flood

Attackers commonly use tools like hping3 to generate SYN Floods. hping3 is a network tool that allows users to craft custom packets and launch various types of attacks.

sudo hping3 -S -p 53 --flood --rand-source 192.168.19.12
sudo hping3 -S -p 53 --flood --rand-source <Target_IP>

hping3: A network tool used to send custom packets.

-S: Sends SYN packets.

-p 53: Targets port 53 (commonly used by DNS).

— flood: Enables flood mode, sending packets as quickly as possible.

— rand-source: Randomizes the source IP addresses to make the attack harder to block.

<Target_IP>: Replace this with the IP of the target machine.

What Are the Risks to the Target?

  1. Denial of Service: The targeted service becomes unavailable to legitimate users due to resource exhaustion.

2. System Overload: The system may experience crashes or significant slowdowns as it struggles to manage the flood of SYN packets.

3. Firewall Evasion: The attack’s randomized source IP addresses complicate efforts to block malicious traffic using simple firewall rules.

How to Defend Against SYN Flood Attacks

  1. Enable Rate-Limiting: Configure rate-limiting on the target system to restrict the number of SYN requests from a single IP within a specific time frame. This can be achieved using tools like iptables on Linux or pfSense on network appliances.

2. Enable Firewalls and Intrusion Detection Systems: Snort (IDS tool) that can be configured to detect SYN Flood attempts.

A Snort rule to detect such attacks:

alert tcp any any -> any any (msg:"Possible SYN Flood Detected"; flags:S; threshold:type both, track by_src, count 100, seconds 10; sid:1000002;)

View Alerts in Snort

Access pfSense Dashboard: Log in to your pfSense web interface.

Navigate to the Snort Package:

Go to Services in the top menu.

Select Snort from the dropdown.

Check the Alerts Tab:

Inside the Snort settings, you’ll find several tabs, including Interfaces, Global Settings, and Alerts.

Click on the Alerts tab to view logs for any detected alerts.

3. Deploy SYN Cookies: Enable SYN cookies on the target system to validate incoming SYN requests without consuming excessive resources.

4. Blackhole Routing: Divert traffic from suspicious source IPs to a “null route” to prevent it from affecting the target.

5. Monitor Traffic: Use tools like Wireshark to identify an unusually high volume of SYN packets.

Splunk Query for SYN Flood Detection

index=pfsense sourcetype=syslog "Possible SYN Flood"

Third Attack: Understanding and Defending Against Brute Force Attacks

Brute force attacks are a common method used by attackers to gain unauthorized access to systems by systematically guessing login credentials. Understanding how brute force attacks work, the risks they pose, and how to detect and mitigate them is essential for securing your systems.

What Is a Brute Force Attack?

A brute force attack involves systematically attempting different username and password combinations until the correct credentials are found. Attackers often use automated tools to speed up the process, targeting remote access services like SSH (Port 22) or RDP (Port 3389).

Why Do Attackers Use Brute Force Attacks?

  1. Gain Unauthorized Access: Attackers aim to gain control of a system by discovering valid credentials.

2. Move Laterally Across the Network: Once inside, attackers can explore other systems using the same credentials.

3. Data Theft and Exploitation: Access to critical systems allows attackers to exfiltrate sensitive information or install malware.

How Attackers Perform a Brute Force Attack

Tool like Hydra is commonly used for automating brute force attacks. This tools try different username and password combinations until it’s find the correct one.

hydra -l admin -P /path/to/rockyou.txt -t 4 ssh://<Target_IP>
hydra -l admin -P /usr/share/wordlists/rockyou.txt -t 4 ssh://192.168.19.12

hydra: A tool used for password-cracking attacks.

-l admin: Specifies the username (admin) to target.

-P /usr/share/wordlists/rockyou.txt: Uses the rockyou.txt wordlist containing thousands of common passwords.

-t 4: Specifies the number of parallel tasks to run (for faster attack execution).

ssh://<Target_IP>: Targets the SSH service on the specified IP address.

What Are the Risks to the Target?

  1. Unauthorized System Access: Attackers gain control over the system if valid credentials are found.
  2. System Compromise: Attackers can install malware, create backdoors, or exfiltrate sensitive data.
  3. Account Lockouts: Failed login attempts may trigger account lockouts, disrupting legitimate access.

How to Defend Against Brute Force Attacks

  1. Implement Strong Password Policies: Use complex passwords with a combination of uppercase letters, lowercase letters, numbers, and special characters.
  2. Enable Account Lockout Policies: Lock accounts after a certain number of failed login attempts to prevent unlimited guessing.
  3. Use Multi-Factor Authentication (MFA): Require a second form of authentication (e.g., a one-time code) in addition to a password.
  4. Monitor Logs: Use Event Viewer or Sysmon to track failed login attempts and network activity.
  5. Limit Remote Access: Restrict remote services like SSH or RDP to trusted IP addresses using firewalls or VPNs.
  6. Deploy Intrusion Detection Systems (IDS): Use tools like Snort to detect and alert on repeated login attempts.
  7. Use Port-Knocking or Dynamic Port Allocation:

8. Enable Firewalls and Intrusion Detection Systems: Snort (IDS tool) that can be configured to detect attacks.

A Snort rule to detect such attacks:

# SSH Brute Force (detection of brute-force SSH login attempts)
alert tcp any any -> any 22 (msg:"SSH Brute Force Attempt"; flags:S; threshold:type both, track by_src, count 5, seconds 60; sid:1001022;)

View Alerts in Snort

Access pfSense Dashboard: Log in to your pfSense web interface.

Navigate to the Snort Package:

Go to Services in the top menu.

Select Snort from the dropdown.

Check the Alerts Tab:

Inside the Snort settings, you’ll find several tabs, including Interfaces, Global Settings, and Alerts.

Click on the Alerts tab to view logs for any detected alerts.

The reason Snort is showing “Possible ICMP Sweep” instead of detecting a brute-force attack is that it’s likely detecting ICMP requests (ping) being sent to multiple IP addresses. Hydra, while performing a brute-force attack, might be sending ICMP pings to check if hosts are alive before attempting the login attempts.

Splunk Query for Brute Force Attacks

index=* sourcetype=*
| fieldsummary

index=*: This specifies that the query should search across all indexes in Splunk.

In Splunk, indexes are containers where logs or event data is stored. You can have multiple indexes based on the type of data, for example, main, security, web_logs, etc.

The wildcard * means all indexes, so the query will scan every indexed event in your Splunk instance, regardless of the specific source or type.

sourcetype=*: This part indicates that you want to search for events of all sourcetypes.

A sourcetype is a field in Splunk that defines the format of the data or the type of log source (syslog, apache, csv, etc.).

Again, the wildcard * means it will consider all possible sourcetypes, providing flexibility to search across any data type stored in Splunk, whether it’s logs from firewalls, web servers, or application logs.

| fieldsummary: This is a Splunk Search Processing Language (SPL) command that provides a summary of the fields present in the events.

It scans the data for fields (such as src_ip, username, status_code, etc.) and summarizes information such as:

The field names (src_ip, username, etc).

The unique values for each field.

The count of occurrences for each value.

Other statistics, like the distribution of values, which help you understand how often certain values appear in the data.

index=* sourcetype=*
| search EventCode=4625
| head 10

index=*: This specifies that the search should be conducted across all indexes within Splunk.

In Splunk, indexes are where event data (such as logs) is stored. By using index=*, you’re telling Splunk to look through every index and source of data, whether it’s application logs, system logs, or network logs.

The wildcard * means it applies to every index in your Splunk environment.

sourcetype=*: This part of the query specifies that you want to search across all sourcetypes.

Sourcetype defines the format of the data or the type of log source, such as syslog, windows, apache, etc.

The wildcard * means the search will include all types of logs, regardless of the source, making this a broad query.

This means that you’re searching through all available logs, regardless of their specific format.

| search EventCode=4625: The | search command is a search filter that is applied after the initial search to narrow down the results.

EventCode=4625 is a filter that specifies the Windows Event ID you’re interested in.

Event ID 4625 is logged by Windows when there is a failed logon attempt. This event is commonly used in security monitoring to detect brute force attacks, unauthorized access attempts, or misconfigured systems.

Why EventCode=4625? Because you’re specifically looking for failed login attempts. Event ID 4625 is generated whenever a login attempt is made and fails. It provides detailed information about the failure, including the username, source IP, and reason for failure (e.g., wrong password, locked account).

Forte Attack: Understanding and Defending Against Denial-of-Service (DoS) Attacks

A Denial-of-Service (DoS) attack aims to disrupt the normal operation of a system or network by overwhelming it with a flood of traffic or requests. This attack prevents legitimate users from accessing services. Understanding DoS attacks, their impact, and how to defend against them is essential for maintaining system availability.

What Is a Denial-of-Service Attack?

In a DoS attack, the attacker generates a massive amount of traffic or resource-consuming requests, causing the target system to become unresponsive. Unlike other attacks, the goal is not to steal data or gain unauthorized access but to render the system unusable.

Why Do Attackers Use DoS Attacks?

  1. To Disrupt Services: Prevent users from accessing critical services, such as websites or applications.

2. To Cause Financial or Reputational Damage:
Organizations can lose revenue or credibility due to prolonged downtime.

3. To Mask Other Attacks: A DoS attack can distract from or create a smokescreen for other malicious activities, like data breaches or malware installation.

How Attackers Perform a DoS Attack

Attackers use tools or scripts to send a large volume of requests or data packets to a target. Below is an example of a simple DoS attack using the ping command in Kali Linux.

ping -f -s 65500 <Target_IP>
ping -f -s 65500 192.168.1.12

sudo: The sudo (SuperUser Do) command runs the ping utility with elevated privileges. This is necessary because certain ping options (such as setting a very large packet size or using flood mode) require administrative permissions.

ping:ping is a common network diagnostic tool used to test connectivity between the source and a target machine by sending ICMP (Internet Control Message Protocol) echo request packets and measuring the time it takes for the target to respond.

-f: The -f option stands for “flood mode”. When used, it sends ping requests as fast as possible, without waiting for replies. This can generate a lot of network traffic in a very short period of time, potentially overwhelming the network or the target system. This is often used in stress testing or in DDoS (Distributed Denial of Service) simulations to see how the target responds to extreme traffic.

-s 65500: The -s option specifies the size of the ping packet payload (the amount of data in each ICMP request). Normally, the default size is 56 bytes for an IPv4 address. However, with -s 65500, you are setting the packet size to 65500 bytes (approximately 65 KB), which is significantly larger than the default size. This will send large packets in each ping request, which can consume more bandwidth and resources on both the sending and receiving systems.

Note: The maximum permissible size for an ICMP packet is 65,535 bytes (the size of an IP packet). By setting it to 65500 bytes, the packet is nearly at its maximum size, which will increase the load on the network, the target machine, and routers that process the packet.

<Target_IP>: Replace this with the IP address of your target

or

sudo ab -n 1000 -c 100 http://<Target_IP>/
sudo ab -n 1000 -c 100 http://192.168.19.12/

sudo:sudo stands for “superuser do” and is used to run commands with elevated privileges. This is necessary because Apache Bench (ab) may require elevated permissions to open many network connections or perform other privileged actions during testing.

ab:ab is the command-line tool used for benchmarking the performance of a web server. It sends HTTP requests to a web server and reports on the response times, throughput, and other important performance metrics.

-n 1000: The -n option specifies the total number of requests to perform during the test. In this case, 1000 requests will be sent to the server (Apache Bench will send 1000 HTTP requests to the specified URL).

-c 100: The -c option specifies the concurrency level, i.e., the number of requests to send simultaneously. In this case, 100 requests will be made in parallel. This simulates the load of 100 users accessing the server at the same time, helping to test how the server handles concurrent connections.

http://<Target_IP>/: This is the URL of the target server that will receive the requests.

What Are the Risks to the Target?

  1. Service Downtime: The system becomes unresponsive, affecting legitimate users.
  2. Resource Exhaustion: High CPU, memory, or bandwidth usage caused by the attack can crash the system.
  3. Network Degradation: Other connected devices may also experience slowdowns or disruptions.

How to Defend Against DoS Attacks

  1. Rate-Limiting: Limit the number of requests or connections allowed from a single IP within a specific time frame.
  2. Enable Firewalls: Configure the Windows Firewall or pfSense to block traffic from suspicious IPs.

Use geofencing to allow traffic only from trusted IP ranges.

  1. Monitor Network Traffic: Use network monitoring tools like Wireshark or Splunk to identify traffic anomalies.
  2. Deploy Intrusion Prevention Systems (IPS): Use tools like Snort to detect and block DoS traffic in real time.
  3. Use Content Delivery Networks (CDNs): Offload traffic to a CDN like Cloudflare to handle large volumes and mitigate bandwidth exhaustion.
  4. Enable Resource Management: Configure system-level resource limits to prevent one process or user from consuming all resources.
  5. Implement Blackhole Routing: Divert malicious traffic to a “null route” to prevent it from reaching the target system.

6. Enable Firewalls and Intrusion Detection Systems: Snort (IDS tool) that can be configured to detect DoS Attacks.

A Snort rule to detect such attacks:

alert icmp any any -> any any (msg:"Possible DoS Attack Detected - ICMP Flood"; threshold:type both, track by_src, count 100, seconds 10; classtype:attempted-dos; sid:1000003; rev:1;)

View Alerts in Snort

Access pfSense Dashboard: Log in to your pfSense web interface.

Navigate to the Snort Package:

Go to Services in the top menu.

Select Snort from the dropdown.

Check the Alerts Tab:

Inside the Snort settings, you’ll find several tabs, including Interfaces, Global Settings, and Alerts.

Click on the Alerts tab to view logs for any detected alerts.

Splunk Query for DoS Attacks

index=pfsense sourcetype=syslog "Possible DDoS Attack"

index=pfsense: This specifies that you’re searching in the pfsense index where the firewall or network traffic logs might be stored.

sourcetype=syslog: This tells Splunk to look for events from syslog, which is commonly used for logging firewall or network appliance data.

“Possible DDoS Attack”: This is the search term used to look for events that indicate a potential DDoS attack, assuming your pfSense firewall (or other network appliance) is configured to log these types of events.

Fourth Attack: Understanding and Defending Against Man-in-the-Middle (MITM) Attacks

A Man-in-the-Middle (MITM) attack is a type of cyberattack where the attacker intercepts and potentially alters the communication between two parties who believe they are directly communicating with each other. The attacker can listen to, steal, or even manipulate the data being transferred between the victim and the intended recipient, all while remaining undetected.

MITM attacks often target unencrypted communication or poorly configured systems, making it an essential security issue to address.

Why Do Attackers Use MITM Attacks?

  1. Data Interception: Attackers can capture sensitive information, such as passwords, credit card numbers, or personal details, when it is transmitted unencrypted.
  2. Data Manipulation: The attacker can modify the data being sent between two parties, such as changing the content of a transaction or altering login credentials.
  3. Identity Theft: By impersonating one of the communicating parties, attackers can perform unauthorized actions or steal identities.
  4. Exploiting Weaknesses in Communication Protocols: Attackers can exploit vulnerabilities in protocols like HTTP or DNS to conduct MITM attacks.

How Do Attackers Perform a MITM Attack?

MITM attacks involve placing the attacker between two communicating parties to intercept or alter the communication. Here’s how attackers commonly perform such attacks:

  1. ARP Spoofing (ARP Poisoning):

Description: The attacker sends fake ARP (Address Resolution Protocol) messages to associate their MAC address with the IP address of another device, often the gateway or a target machine.

Effect: This causes network traffic to be routed through the attacker’s machine, allowing them to intercept or manipulate the data.

sudo arpspoof -i <interface> -t <Target_IP> <Gateway_ip>
sudo arpspoof -i eth0 -t 192.168.19.12 192.168.19.138

sudo: Runs the command with elevated privileges. This is necessary because ARP poisoning requires root or superuser access.

arpspoof: This is the tool used to perform the ARP spoofing attack. It is part of the dsniff suite of tools for network auditing and penetration testing.

-i <interface>: This option specifies the network interface that the tool should use.

Common interfaces include eth0 for Ethernet, wlan0 for wireless, etc.

-t <Target_IP>: This is the IP address of the target device (the victim) whose ARP cache you intend to poison.

When ARP packets are sent to this device, it will associate the wrong MAC address with the IP address of the gateway.

<Gateway_IP>: This is the IP address of the gateway (router) in the network, which the target device is trying to communicate with.

2. DNS Spoofing (DNS Cache Poisoning):

Description: The attacker sends falsified DNS responses to redirect the victim’s traffic to a malicious site.

Effect: This can lead to credential theft, phishing attacks, or malware distribution when the victim unknowingly visits a fake site.

3. SSL Stripping:

Description: The attacker downgrades an HTTPS connection (secure) to HTTP (unencrypted).

Effect: This allows the attacker to read or modify communication, even though the victim believes they are using a secure connection.

Why Do Attackers Target MITM?

  1. Data Theft: By intercepting data in transit, attackers can steal sensitive information like passwords, financial details, and private communications.
  2. Financial Gain: MITM attacks can be used for financial fraud, such as changing the destination of a bank transfer or stealing credit card details.
  3. Session Hijacking: The attacker may take over a valid user session, impersonating the victim and gaining unauthorized access to systems.
  4. Spy on Communications: MITM allows attackers to eavesdrop on private communications between users or between systems.

Risks to the Target from a MITM Attack

  1. Unauthorized Access: If login credentials or authentication tokens are intercepted, attackers can gain unauthorized access to user accounts or systems.
  2. Data Loss or Corruption: The attacker may alter or corrupt data, such as changing the content of financial transactions or modifying messages between two parties.
  3. Identity Theft: If personal details are intercepted, attackers can use this information for identity theft or fraud.
  4. Reputation Damage: For organizations, an MITM attack can lead to significant reputation damage if customer data or sensitive internal information is exposed.

How to Defend Against MITM Attacks

  1. Use Strong Encryption (HTTPS, TLS): Always use secure communication protocols that encrypt data end-to-end, such as HTTPS (for web traffic) and TLS (for email or other communications). This ensures that even if an attacker intercepts the data, it will be unreadable without the decryption key (enforce HTTPS on your website using HSTS (HTTP Strict Transport Security) to ensure that browsers always use HTTPS.
  2. Implement DNSSEC: DNSSEC (Domain Name System Security Extensions) provides cryptographic protection for DNS records, ensuring that DNS queries and responses are authentic and have not been tampered with.
  3. Use Strong SSL/TLS Certificates: Ensure that SSL/TLS certificates are properly validated and up-to-date. Use certificates issued by trusted Certificate Authorities (CAs) and enable certificate pinning where possible.
  4. VPN (Virtual Private Network): Use VPNs to ensure secure communication when using public or untrusted networks. A VPN encrypts the entire network traffic, making it harder for attackers to intercept.
  5. Session Security: Implement techniques like HSTS, secure cookie flags, and session timeout to mitigate the risk of session hijacking during MITM attacks.
  6. Public Key Infrastructure (PKI): Use PKI to authenticate devices and users securely, ensuring that all connections are trusted and verified.
  7. Network Monitoring: Use Snort or Wireshark to monitor for signs of MITM attacks, such as unusual ARP traffic, DNS anomalies, or unexpected SSL/TLS certificate changes.

Snort rule to detect MITM attacks:

Note on Snort and MITM Detection:

Snort does not provide direct detection for MITM (Man-in-the-Middle) attacks based on the ARP protocol (ARP Spoofing). For detecting such attacks, it is recommended to use additional tools such as:

Ettercap — A great tool for handling MITM attacks and ARP Spoofing attacks.

Suricata — Another open-source IDS/IPS system that can provide better support for ARP analysis.

Zeek (formerly Bro) — A robust network monitoring solution that includes MITM attack detection and ARP Spoofing analysis.

Snort, on the other hand, is capable of detecting attacks at the IP and TCP levels (such as Flooding, SYN Flood, SSH Brute Force), but for ARP-based MITM attacks, you may need to use more specialized tools that are specifically designed for that purpose.

Detecting MITM Attack Using Wireshark

Wireshark can help you identify MITM traffic by analyzing the packets. Look for unencrypted HTTP traffic when you expect HTTPS or check for suspicious DNS requests.

Wireshark can be used to analyze network traffic and detect MITM indicators. For example, look for unencrypted HTTP traffic where HTTPS is expected or check for suspicious DNS traffic:

dns.flags.response == 1 && dns.a && !(dns.a == 0.0.0.0)

dns.flags.response == 1: This part of the filter checks for DNS response packets. In the DNS protocol, every DNS packet has a flag field that indicates whether it is a query or a response.

dns.flags.response == 1 means we are only interested in DNS responses (as opposed to DNS queries).

dns.a: This specifies that we are looking for DNS response packets that contain an A record.

An A record in DNS is used to map a domain name (like example.com) to an IPv4 address.

So, this condition ensures that the DNS response contains an A record, which is typically used to return an IP address for a domain name.

!(dns.a == 0.0.0.0): This condition filters out responses where the A record is set to 0.0.0.0, which is an invalid or suspicious IP address.

If an attacker is performing a DNS spoofing attack, they might inject a 0.0.0.0 response to redirect traffic or block access to certain sites.

The ! symbol means NOT, so this part of the filter ensures that we only capture DNS responses where the A record is not 0.0.0.0.

What can we learn about a possible MITM attack from this data?

Suspicious DNS Queries: If DNS responses are coming from unexpected sources (e.g., your local router), it could indicate a MITM attack.

ICMP Destination Unreachable Messages: This could suggest that requests are being intercepted or blocked by an attacker.

Repeated DNS Responses: Multiple responses for the same domain could be an attempt to inject malicious DNS records, a common sign of DNS spoofing.

Splunk Query for Detecting MITM Activity

index=* sourcetype=* "spoofed" OR "arp" OR "dns"

index=*:The index=* part tells Splunk to search across all available indexes. An index in Splunk is essentially a database where data is stored and organized. In most setups, you would specify a particular index to narrow down your search (index=network for network-related data). Using * means “all indexes.”

Why this is used: Searching all indexes ensures that no data is missed, but it can be slower if you have a large number of indexes or a vast amount of data in your Splunk environment.

sourcetype=*:The sourcetype=* component specifies that you are searching across all sourcetypes. A sourcetype in Splunk refers to the type of data (syslog, web logs, network traffic). This wildcard (*) means that all types of data are included in the search.

This allows the search to look at all types of logs, not limiting it to specific sources, which can be useful if you’re uncertain where the relevant data might be located.

“spoofed” OR “arp” OR “dns”: These keywords define the search terms you’re looking for in the events:

“spoofed”: This indicates you’re searching for entries where the word “spoofed” appears, which could be relevant to various types of spoofing attacks like IP or ARP spoofing.

“arp”: This term searches for occurrences of ARP (Address Resolution Protocol), which is commonly used in attacks like ARP poisoning, where attackers impersonate legitimate devices on a network.

“dns”: This term looks for instances where “dns” is present in the event, which is related to DNS spoofing or DNS manipulation attacks, such as redirecting traffic by modifying DNS resolutions.

Logical Operator — OR: The OR operator means you’re searching for any event that contains at least one of the specified terms: either “spoofed”, “arp”, or “dns”. If an event contains any of these words, it will be included in the results.

Using PowerShell to Search to Search Sysmon Logs for Network Connection Events

The use of PowerShell to query Sysmon logs and network connections provides a solid foundation for detecting and analyzing potential network-based threats, including port scanning attempts and abnormal traffic behaviors. Here’s a refined and actionable summary of the key steps and findings:

PowerShell Commands for Searching Sysmon Logs

1. Retrieve Network Connection Events (Event ID 3)

Event ID 3 corresponds to network connection events in Sysmon logs, crucial for detecting unusual network behaviors, including potential port scans or abnormal traffic.

Basic Command:

Get-WinEvent -LogName "Microsoft-Windows-Sysmon/Operational" | Where-Object {$_.Id -eq 3} | Format-Table TimeCreated, Message -AutoSize

Get-WinEvent: Retrieves Windows event logs.

Where-Object {$_.Id -eq 3}: Filters for Event ID 3, which logs network connection activities.

Format-Table: Formats the results into a readable table.

Command for Detailed Data:

This will provide additional attributes, helping to identify processes, IP addresses, and ports involved in each connection.

Get-WinEvent -LogName "Microsoft-Windows-Sysmon/Operational" | Where-Object {$_.Id -eq 3} | Format-List TimeCreated, Id, Message, ProviderName, LevelDisplayName, TaskDisplayName

2. Group Connection States

Monitoring TCP connection states helps identify unusual behaviors like port scanning, DoS attacks, or unauthorized traffic.

Get-NetTCPConnection | Group-Object -Property State | Select-Object Name,Count

Get-NetTCPConnection: Lists current TCP connections on the system.

Group-Object -Property State: Groups the connections by their state (Listen, Established).

Typical TCP connection states:

Listen: Ports awaiting incoming connections. A large number could signal a DoS attack.

Bound: Ports bound but not listening.

Established: Active, normal connections.

TimeWait: Connections closing and waiting for acknowledgment.

3. Monitor Critical Network Ports

Certain ports are frequently targeted by attackers and should be closely monitored for unauthorized access attempts:

Port 135, 139, 445 (SMB, RPC)

Port 3389 (RDP)

Port 22 (SSH)

This provides a comprehensive overview of TCP connections, identifying local and remote addresses, ports, and states of each connection.

Look for open ports (135, 139, 445), connections to unknown IPs, or unusual traffic on critical ports.

Get-NetTCPConnection | Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, State, OwningProcess

4. Investigate Suspicious TCP Connections

For more focused investigation, specifically monitor connections in the Listen state to detect potential unauthorized services or attacks.

Retrieves all ports in the Listen state to check for open, listening services or potential DoS indicators.

Get-NetTCPConnection -State Listen | Select-Object LocalAddress, LocalPort, OwningProcess

Recommendations for Further Investigation

Monitor and Audit Critical Ports: Secure or disable ports associated with RDP (3389), SMB (135, 445), and SSH (22) if they are not essential. If these ports must be open, implement strong security measures like firewalls, encryption, and multi-factor authentication.

Investigate Suspicious Processes: Processes using multiple ports or generating unusual traffic (e.g., processes with PIDs like 2652, 4124) should be investigated to confirm their legitimacy. Cross-reference with known software or services, and if unknown, consider isolating or terminating suspicious processes.

Outbound Connections: Outbound connections to trusted IPs on port 443 (HTTPS) are normal. However, connections to unknown or untrusted remote IPs, especially on high-numbered ports, should be thoroughly analyzed for potential malware or botnet activity.

Monitor Internal Communication: Internal communication on ephemeral ports (like 8191, 49665–50545) may be part of normal system processes or application-specific traffic. Ensure this communication is legitimate, especially in systems where such ports should not be used by unknown or unauthorized applications.

General Security Recommendations

Patch Vulnerabilities: Regularly update your systems and applications to mitigate exploits targeting known vulnerabilities in services like SMB or RDP.

Implement Firewalls and Access Control: Use host-based or network firewalls to restrict unnecessary open ports and control access to critical services. For example, restrict RDP (3389) access to trusted IPs only, or disable RDP entirely if not needed.

Intrusion Detection and Prevention: Implement Intrusion Detection/Prevention Systems (IDS/IPS) to alert on suspicious network traffic patterns, such as port scanning or an unusually high number of connections in Listen or TimeWait states.

Log and Event Management: Continue monitoring Sysmon and Windows event logs for signs of abnormal behavior, such as port scanning, unauthorized access attempts, or unusual outbound connections. Leverage Security Information and Event Management (SIEM) tools to automate this process.

Additional PowerShell Commands for Sysmon Log Investigation
1. Retrieve Sysmon Event 1 (Process Creation)

Process creation events can provide insight into potentially malicious activities, such as unauthorized processes or suspicious binaries being executed.

Event ID 1 corresponds to process creation events in Sysmon logs.
This command will display process creation events, showing the time of execution, process name, and other important details.

Get-WinEvent -LogName "Microsoft-Windows-Sysmon/Operational" | Where-Object {$_.Id -eq 1} | Format-Table TimeCreated, Message -AutoSize

2. Retrieve Sysmon Event 10 (Process Exit)

Event ID 10 logs when a process terminates, which can be useful for detecting unusual process activity or when a malicious process exits unexpectedly.

Event ID 10 logs the termination of a process.
Use this to investigate when certain processes were unexpectedly stopped, possibly by an attacker.

Get-WinEvent -LogName "Microsoft-Windows-Sysmon/Operational" | Where-Object {$_.Id -eq 10} | Format-Table TimeCreated, Message -AutoSize

3. Track DNS Requests (Event ID 22)

If attackers are attempting to resolve domain names for malicious purposes (C2 server communication), Sysmon’s DNS query logging can reveal these activities.

Event ID 22 logs DNS queries made by processes.
This is useful for tracking external domains contacted by the system, which may indicate communication with a malicious actor.

Get-WinEvent -LogName "Microsoft-Windows-Sysmon/Operational" | Where-Object {$_.Id -eq 22} | Format-Table TimeCreated, Message -AutoSize

4. Retrieve Sysmon Event 11 (File Creation)

This event logs when files are created, modified, or deleted. It can help identify the creation of suspicious or unexpected files on the system.

Event ID 11 provides information about file creation activities, which is useful for monitoring unauthorized file creation by potential malware or attackers.

Get-WinEvent -LogName "Microsoft-Windows-Sysmon/Operational" | Where-Object {$_.Id -eq 11} | Format-Table TimeCreated, Message -AutoSize

Additional Recommendations for Investigating Sysmon Logs

1. Investigate Unusual Process Behavior

High Frequency of New Processes: If you see an unusual number of processes being created in a short amount of time, it could suggest malicious activity such as a malware dropper or a botnet controller. Investigate the parent-child relationship of processes (use Event ID 1 to look at parent process IDs).
Unusual Process Names or Locations: Verify the legitimacy of processes by checking the paths and signatures. Malicious processes are often executed from unusual locations (%TEMP% or %APPDATA%).

2. Track Outbound Connections

Check Unusual Destinations: If you observe unusual outbound connections to foreign IPs, especially on uncommon ports (e.g., 6660–6669 for IRC or 1080 for SOCKS proxy), this could be indicative of a botnet, data exfiltration, or C2 communication.
Port Scanning Behavior: Look for rapid connections to multiple remote addresses or ports in a short period, as this is a common signature of port scanning activity. This could be detected by aggregating Sysmon Event ID 3 entries and comparing remote addresses and ports.

3. Monitor File System Activity

Unexpected File Creation/Modification: Suspicious file activity, particularly under system folders (C:\Windows\Temp, %APPDATA%), should be investigated. This might indicate malware or unauthorized access.
Uncommon File Types: Pay attention to the creation of executable files in user folders (e.g., .exe, .dll) that don’t match any known legitimate software.

4. Correlate with Other Logs (Event IDs 4624 and 4634)

Event ID 4624: Logs successful logins. Look for login events from unusual user accounts or IP addresses, especially for accounts with administrative privileges.
Event ID 4634: Logs logoff events. Correlating login and logoff events can help identify unauthorized or suspicious user activity.

General Recommendations for Improving Network and System Security

To strengthen your network and system security, consider implementing the following recommendations:

Regular System and Network Auditing
Conduct regular system and network audits using the provided PowerShell commands to detect potential threats and anomalies. Automate log collection and analysis using SIEM (Security Information and Event Management) tools for real-time threat detection.

Secure Critical Network Ports
Restrict Access to Critical Services:
Use a firewall to restrict access to critical ports such as RDP (3389), SMB (135, 445), and SSH (22). Allow access only from trusted IPs, or disable these services entirely if not needed.
RDP and SMB Security:
If these services must remain enabled, ensure they are properly secured with strong passwords, multi-factor authentication (MFA), and the latest security patches to reduce vulnerabilities.

Enforce Application Whitelisting
Implement application whitelisting to allow only trusted and authorized applications to run on your systems. This prevents the execution of potentially malicious or unauthorized programs.

Patch Management and Vulnerability Scanning
Regularly Update Systems and Software:
Ensure that your operating system and software are up-to-date with the latest patches to prevent exploitation of known vulnerabilities.
Use Vulnerability Scanners:
Tools like Nessus or Qualys can help identify unpatched vulnerabilities or misconfigurations, providing insight into potential security gaps.

Implement Intrusion Detection and Prevention Systems (IDS/IPS)
Use IDS/IPS systems (e.g., Snort, Suricata) to monitor network traffic for suspicious patterns such as port scans or brute-force login attempts. These systems can help detect and block malicious activities in real time.

Investigate Suspicious Traffic or Processes
Investigate unusual outbound traffic to untrusted external IPs, as it could indicate malware communication or data exfiltration.
Suspicious Ports and Processes:
Pay special attention to processes using uncommon ports, as they may signal malicious activity.

Advanced Security Tools and Strategies

To further enhance security, consider the following tools and strategies:

SIEM (Security Information and Event Management):
Centralize log collection from various sources (Sysmon, IDS/IPS, firewalls) and leverage your SIEM platform (such as Splunk or ELK) to monitor and alert on suspicious activity in real-time.

IDS/IPS (Intrusion Detection and Prevention Systems):
Deploy tools like Snort or Suricata to monitor and analyze network traffic for potential threats. Integrate these systems with your SIEM for a comprehensive security solution.

SOAR (Security Orchestration, Automation, and Response):
Automate security responses by configuring SOAR playbooks. For example, automatically block malicious IPs or isolate compromised machines when a threat is detected.

Firewall Configuration:
Enforce strict firewall rules to block unused or risky ports (RDP (3389), SMB (445), SSH (22)) and restrict access to critical services from trusted IPs only.

Multi-Factor Authentication (MFA):
Enforce MFA for access to critical services such as RDP and SSH to strengthen security and ensure that each login attempt is verified using multiple factors.

Zero Trust Architecture:
Adopt a Zero Trust security model where all access is continuously verified, ensuring that only authorized users and devices can access sensitive resources.

Log Management and Continuous Monitoring:
Set up centralized log management systems for continuous monitoring of network traffic, process activities, and system behavior. Use your SIEM or log management tools to analyze logs for suspicious or malicious activity.

Conclusion

Effective defense against cyberattacks requires a multi-layered approach, combining regular audits, strong security measures, and continuous monitoring. By implementing best practices like network monitoring, patch management, and multi-factor authentication, organizations can protect themselves against common threats such as SYN Floods, Brute Force, MITM (Man-in-the-Middle) attacks, and DoS/DDoS attacks. Regular security audits, proactive monitoring, and real-time response are essential for maintaining a robust and resilient security posture

--

--

IritT
IritT

Written by IritT

In the world of cybersecurity, the strongest defense is knowledge. Hack the mind, secure the future.

No responses yet