Skip to content
29nlsPublic

About

Anti‑DDoS System adalah aplikasi berbasis Windows yang dirancang untuk mendeteksi dan mitigasi serangan DDoS secara real‑time. Menggunakan Scapy untuk penyadaran paket, GeoIP2 untuk pencarian lokasi geografis penyerang, Tkinter dengan ttkbootstrap untuk antarmuka grafis modern, dan Windows Firewall (netsh) untuk blokir IP secara otomatis.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

10 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Anti-DDoS System v2.1

Real-time DDoS Detection & Mitigation for Windows

Features • Installation • Usage • Configuration • Tuning • Architecture • Security • License • Changelog

Python Windows License Version Changelog Coverage


🛡️ What is Anti-DDoS?

A Python-based DDoS detection and mitigation system for Windows that provides real-time network traffic analysis, automatic attack detection, and instant IP blocking via Windows Firewall.

Originally reverse-engineered from an existing executable with 99% accuracy, then enhanced with security hardening, rate limiting, visualization, and PDF reporting.

Key Highlights

Feature Description
🔍 Real-time Detection SYN, Slowloris, HTTP, DNS, NTP, UDP, ICMP flood detection using Scapy
🧩 Plugin Detection Rules Extensible rule-based engine — add attack types without touching core code
🚫 Auto-Blocking Threshold-based automatic IP blocking via Windows Firewall
🗄️ Persistent History SQLite-backed attack history (attacks.db) survives restarts
⚙️ External Config Tune thresholds, logging, and storage via config.json/config.yaml — no code edits
🌍 GeoIP Lookup Identify attacker country using MaxMind GeoLite2 database
📊 Live Visualization Real-time charts showing attack distribution
📄 PDF Reports Reports include historical data from the persistent store
🔒 Security Hardened Thread-safe, input validation, no command injection

Every release since the original v1.2 executable is documented in the CHANGELOG.


✨ Features

Core Detection

Feature Description
SYN Flood Detection Identifies TCP SYN packets without ACK (flag 0x02 set, 0x10 not set)
HTTP Flood Detection Flags TCP traffic to ports 80/443 (non-SYN web traffic)
Slowloris Detection Flags partial, low-payload TCP handshakes to ports 80/443
DNS Amplification Detection Flags UDP traffic to port 53 (query floods)
NTP Amplification Detection Flags UDP traffic to port 123 (amplifier query floods)
UDP Flood Detection Detects high-volume UDP traffic
ICMP Flood Detection Catches ICMP flood attacks
Plugin Rule Engine DetectionRule interface; register/remove rules at runtime (add_rule(), remove_rule(), get_rule_types())
Rate Limiting Per-IP windows with configurable burst; prevents GUI flooding during real attacks
Auto-Blocking Configurable threshold (default: 100 packets) triggers automatic blocking
SQLite Attack History Every detected attack persisted to attacks.db — survives restarts, powers historical reports

GUI Features

Feature Description
Start/Stop Detection Control sniffing with one click
Block Selected IPs Manually block IPs via Windows Firewall
Copy to Clipboard Export IP addresses for external tools
Exclude IPs (Whitelist) Manage trusted IPs that should not be blocked
Search & Filter Search by port number or country name
Right-Click Menu Quick actions on selected IPs

Visualization & Reporting

Feature Description
Real-time Charts Top IPs, country distribution, port analysis, timeline
PDF Export Professional reports with summary statistics and charts
Historical PDF Data Report includes an all-time history section from attacks.db (top attackers, country/type breakdown, daily timeline)
File Logging Rotating log files with configurable size limits

📦 Installation

Prerequisites

  • Windows 10/11 (required for Windows Firewall integration)
  • Python 3.8+
  • Administrator privileges (for IP blocking)

Quick Install

# Clone the repository
git clone https://github.com/yourusername/Anti-DDoS.git
cd Anti-DDoS

# Install dependencies
pip install -r requirements.txt

# Or install individually
pip install scapy geoip2 ttkbootstrap pyperclip matplotlib reportlab

Manual Install

# Core dependencies (required)
pip install scapy
pip install geoip2
pip install ttkbootstrap
pip install pyperclip

# Optional dependencies (for enhanced features)
pip install matplotlib    # For visualization charts
pip install reportlab     # For PDF report export

GeoIP Database

Download the GeoLite2-Country database from MaxMind and place it in the project directory:

Anti-DDoS/
├── Anti-DDoS_enhanced.py
├── GeoLite2-Country.mmdb    ← Required
├── excluded_ips.txt
└── blocked_ips.txt

🚀 Usage

Basic Usage

# Run as Administrator (required for IP blocking)
python Anti-DDoS_enhanced.py

Step-by-Step Guide

  1. Launch the application

    # Right-click Command Prompt → Run as Administrator
    python Anti-DDoS_enhanced.py
  2. Start Detection

    • Click the ▶ Start Detection button
    • The status bar will show "Sniffing Started..."
  3. Monitor Attacks

    • Attacks appear in real-time in the table
    • Each row shows: Timestamp, IP, Type, Country, Port, Count
  4. Block an Attacker

    • Select one or more IPs in the table
    • Click Block Selected IPs
    • The IP and its /24 subnet will be blocked via Windows Firewall
  5. View Visualization (optional)

    • Click 📊 Show Charts to open real-time charts
    • View Top IPs, Country Distribution, Port Analysis, and Timeline
  6. Export Report

    • Click 📄 Export PDF to generate a professional report
    • Choose save location and the report will be generated
    • Besides current-session statistics, the report includes a Historical Attack Data section sourced from attacks.db (all-time top attackers, country/type breakdown, daily timeline)

Persistent History

Every detected attack is written to attacks.db (SQLite) in the application directory:

  • History survives restarts — restarting the app never loses past attacks
  • attacks.db is created automatically on first run; no setup required
  • Historical data feeds the PDF report and is available for forensic/trend analysis
  • Use the DB_PATH config key to relocate it (see Configuration)

Keyboard Shortcuts

Action Shortcut
Right-click menu Right-click on selected IPs
Search Type in search field + Enter

⚙️ Configuration

All settings ship with sensible defaults in the CONFIG dictionary in Anti-DDoS_enhanced.py. To customize without editing source code, place a config.json in the application directory (or config.yaml when PyYAML is installed). The app loads it automatically at startup and validates every value.

Key Default Description
RATE_LIMIT_INTERVAL 1.0 Seconds per rate-limit window per IP
RATE_LIMIT_BURST 1 Max events per IP per window (including the first)
AUTO_BLOCK_THRESHOLD 100 Packets before auto-blocking triggers
AUTO_BLOCK_ENABLED true Enable/disable auto-blocking
LOG_FILE antiddos.log Log file name
LOG_MAX_SIZE 5242880 Rotating log max bytes (5 MB)
LOG_BACKUP_COUNT 3 Number of rotated logs to keep
DB_PATH attacks.db SQLite attack history file
RULES all 7 built-ins Active detection rules (attack-type names, canonical priority order, first match wins)
CONFIG_PROFILE "" Per-environment profile name (see below); empty = none

Config files are partial overrides — include only the keys you want to change; every omitted key keeps its default:

{
  "AUTO_BLOCK_THRESHOLD": 250,
  "AUTO_BLOCK_ENABLED": false,
  "RULES": ["SYN Flood", "UDP Flood", "ICMP Flood"]
}

Two ready-to-copy examples ship in the repo root (documentation only — rename to config.json / config.yaml to use):

  • config.example.yaml — every option explained inline with comments (requires PyYAML)
  • config.example.json — the identical keys in comment-free JSON; safe to copy as-is with zero loader warnings

🎛️ Tuning

Three ready-to-paste presets for common environments. Copy one into config.json, adjust to taste, then restart — or use the ⟳ Reload Config button to apply it live. Remember: config files are partial overrides, so omitted keys keep their defaults.

Setting Home / Office Server Forensic
RATE_LIMIT_INTERVAL 5.0 s 0.25 s 0.1 s
RATE_LIMIT_BURST 2 5 50
AUTO_BLOCK_THRESHOLD 500 50 200
AUTO_BLOCK_ENABLED off on on
LOG_MAX_SIZE 2 MB 10 MB 50 MB
LOG_BACKUP_COUNT 2 5 10

Each preset is also shipped as a ready-to-copy profile — see the --profile notes under each preset below.

1. Home / Office — permissive (low false positives, quiet logs):

{
  "RATE_LIMIT_INTERVAL": 5.0,
  "RATE_LIMIT_BURST": 2,
  "AUTO_BLOCK_THRESHOLD": 500,
  "AUTO_BLOCK_ENABLED": false,
  "LOG_MAX_SIZE": 2097152,
  "LOG_BACKUP_COUNT": 2
}
  • Rate limiting allows up to 2 logged events per 5 s per IP — the GUI stays quiet during normal browsing.
  • Auto-blocking is off so a false positive can never cut off your own traffic; review the attack table and block manually.
  • Also ships as a profile — config.home.example.json / config.home.example.yaml: rename to config.home.json (or .yaml) and launch with --profile home.

2. Server — aggressive (fast reaction to floods):

{
  "RATE_LIMIT_INTERVAL": 0.25,
  "RATE_LIMIT_BURST": 5,
  "AUTO_BLOCK_THRESHOLD": 50,
  "AUTO_BLOCK_ENABLED": true,
  "LOG_MAX_SIZE": 10485760,
  "LOG_BACKUP_COUNT": 5
}
  • 0.25 s windows with burst 5 keep the GUI responsive under load; a 50-packet threshold blocks attackers in under a second.
  • Also ships as a profile — config.server.example.json / config.server.example.yaml: rename to config.server.json (or .yaml) and launch with --profile server.

3. Forensic — max logging (record every event, heavier disk use):

{
  "RATE_LIMIT_INTERVAL": 0.1,
  "RATE_LIMIT_BURST": 50,
  "AUTO_BLOCK_THRESHOLD": 200,
  "AUTO_BLOCK_ENABLED": true,
  "LOG_MAX_SIZE": 52428800,
  "LOG_BACKUP_COUNT": 10
}
  • 0.1 s windows with burst 50 log up to ~500 events/sec/IP — everything is captured for post-incident analysis.
  • Blocking stays on at a sane 200-packet threshold so evidence keeps flowing; log rotation caps total disk use at ~550 MB.
  • Also ships as a profile — config.forensic.example.json / config.forensic.example.yaml: rename to config.forensic.json (or .yaml) and launch with --profile forensic.

Validation & Fallback

  • Missing keys fall back to defaults.
  • Invalid values (negative thresholds, non-boolean toggles, empty paths) are rejected with a logged warning and the default is used — a bad config file never crashes startup.
  • Unknown keys are ignored with a warning (e.g. SCRIPT_DIR cannot be overridden).
  • File resolution order: config.yaml → config.yml → config.json. YAML is only read when PyYAML is installed; otherwise config.json is used. An unreadable preferred file falls through to the next candidate.
  • Overrides take effect before logging is configured, so LOG_FILE/LOG_MAX_SIZE/LOG_BACKUP_COUNT changes apply from the first log line.

Per-Environment Profiles

Launch with a profile to swap tuning presets without editing the base config:

python Anti-DDoS_enhanced.py --profile server    # or --profile=server

or set "CONFIG_PROFILE": "server" in the base config file (the --profile CLI flag wins over the key). The profile loads config.<name>.json (or config.<name>.yaml with PyYAML) on top of the base config; profile values win conflicts. Profile names are restricted to letters, digits, _ and -, so a hostile --profile argument can never escape the config directory. Three example profiles ship in the repo — config.home.example.json / .yaml, config.server.example.json / .yaml, config.forensic.example.json / .yaml — matching the Tuning presets above. Rename one (e.g. config.server.example.json → config.server.json) to activate it; a requested-but-missing profile degrades gracefully to the base config with a logged notice.

Whitelist Management

Edit excluded_ips.txt to add trusted IPs/CIDRs:

# Cloudflare IPs
103.21.244.0/22
104.16.0.0/13
108.162.192.0/18

# Your monitoring server
192.168.1.100

# Local network
10.0.0.0/8

Or use the 📋 Whitelist button in the GUI to manage it visually.


🏗️ Architecture

┌─────────────────────────────────────────────────────────────────┐
│                    Anti-DDoS System v2.1                        │
├─────────────────────────────────────────────────────────────────┤
│  GUI Layer (tkinter + ttkbootstrap)                             │
│  ├── Control Buttons (Start/Stop/Block/Copy/Exclude)            │
│  ├── Attack Table (Treeview with 7 columns)                     │
│  ├── Search & Filter                                            │
│  └── Status Bar + Statistics                                    │
├─────────────────────────────────────────────────────────────────┤
│  Detection Engine (Scapy)                                       │
│  ├── Background Sniffing Thread                                 │
│  ├── 7 Rules: SYN / Slowloris / HTTP / DNS / NTP / UDP / ICMP   │
│  ├── Pluggable Rule Engine (detection_rules.py)                 │
│  ├── Rate Limiting (per IP, configurable burst)                 │
│  └── Threshold-based Auto-blocking                              │
├─────────────────────────────────────────────────────────────────┤
│  Mitigation Layer (Windows Firewall)                            │
│  ├── subprocess.run() (secure, no shell injection)              │
│  ├── Single IP + /24 Subnet Blocking                            │
│  └── Persistent Blocking (blocked_ips.txt)                      │
├─────────────────────────────────────────────────────────────────┤
│  Data Layer                                                     │
│  ├── GeoIP2 (MaxMind GeoLite2-Country.mmdb)                     │
│  ├── Whitelist (excluded_ips.txt)                               │
│  ├── Blocked IPs (blocked_ips.txt)                              │
│  ├── Rotating Log (antiddos.log)                                │
│  └── Attack History (attacks.db — SQLite, persistent)           │
├─────────────────────────────────────────────────────────────────┤
│  Configuration Layer                                            │
│  └── config_loader.py: config.yaml / config.json + validation   │
├─────────────────────────────────────────────────────────────────┤
│  Optional Modules                                               │
│  ├── Visualization (matplotlib) - Real-time charts              │
│  ├── Whitelist Manager - GUI for managing excluded IPs          │
│  └── PDF Report Generator (reportlab)                           │
└─────────────────────────────────────────────────────────────────┘

Thread Safety

The application uses proper thread synchronization:

  • threading.Lock() — Protects all shared data structures
  • root.after() — Ensures GUI updates run on the main thread
  • queue pattern — Thread-safe communication between sniffing and GUI threads

🔒 Security

Security Features

Feature Description
Input Validation All IPs validated with regex + ipaddress module
Secure Execution subprocess.run() with argument lists (no shell injection)
Thread Safety All shared state protected by locks
Admin Check Warns if not running with Administrator privileges
Error Handling Graceful degradation on failures

Known Limitations

  • Requires Administrator privileges for Windows Firewall operations
  • Detects 7 attack types (SYN, Slowloris, HTTP, DNS Amplification, NTP Amplification, UDP, ICMP). Additional types can be added through the DetectionRule interface (detection_rules.py) without touching the engine
  • HTTP/DNS rules flag by port only — they do not inspect application payloads; rate limiting and auto-block thresholds separate flood behavior from normal traffic
  • GeoIP database requires periodic updates

Reporting Security Issues

If you discover a security vulnerability, please report it responsibly by opening an issue with the security label.


📁 File Structure

Anti-DDoS/
├── Anti-DDoS_enhanced.py        # Main application (v2.1)
├── detection_engine.py          # Core detection engine (GUI-free, testable)
├── detection_rules.py           # Pluggable detection rules (SYN/Slowloris/HTTP/DNS/NTP/UDP/ICMP)
├── config_loader.py             # External config file loader (yaml/json + validation)
├── storage.py                   # Persistent attack history (SQLite)
├── Anti_DDoS_visualization.py   # Real-time chart visualization
├── Anti_DDoS_whitelist.py       # Whitelist management UI
├── Anti_DDoS_settings.py        # Settings dialog (writes a validated config.json)
├── Anti_DDoS_report.py          # PDF report generator
├── test_detection_engine.py     # Detection engine tests (incl. rules)
├── test_storage.py              # Storage layer tests
├── test_config.py               # Config loader tests
├── test_report.py               # PDF report tests
├── requirements.txt             # Production dependencies
├── requirements-dev.txt         # Dev dependencies (pytest, mypy, flake8)
├── .flake8                      # Linter configuration
├── mypy.ini                     # Type checker configuration
├── .gitignore                   # Ignored files (logs, caches, db files)
├── plans/                       # Agent improvement plans (see plans/README.md)
├── .github/
│   └── workflows/
│       └── ci.yml               # GitHub Actions CI pipeline
├── GeoLite2-Country.mmdb        # MaxMind GeoIP database
├── excluded_ips.txt             # Whitelist (IPs to ignore)
├── blocked_ips.txt              # Blocked IPs history
├── antiddos.log                 # Application logs
├── custom_settings.log          # Runtime log (created when a custom LOG_FILE is used)
├── attacks.db                   # SQLite attack history (auto-created on first run)
├── config.example.json          # Example external config, JSON (documentation only)
├── config.example.yaml          # Example external config, commented (docs only)
├── config.home.example.json       # Example 'home' profile — permissive (docs only)
├── config.home.example.yaml       # Example 'home' profile, commented (docs only)
├── config.server.example.json     # Example 'server' profile — aggressive (docs only)
├── config.server.example.yaml     # Example 'server' profile, commented (docs only)
├── config.forensic.example.json   # Example 'forensic' profile — max logging (docs only)
├── config.forensic.example.yaml   # Example 'forensic' profile, commented (docs only)
├── config.json                  # Optional — user-created (via Settings dialog or manual copy)
├── config.yaml                  # Optional — used over JSON when PyYAML is installed
├── assets/
│   └── readme/                  # README visual assets
│       ├── hero-banner.svg
│       └── feature-detect.svg
├── CHANGELOG.md
├── README.md
├── AGENTS.md                     # Project rules for AI agents & contributors
├── CONTEXT.md                    # Domain glossary / shared design vocabulary
└── LICENSE                       # MIT license


Reverse-engineering artifacts (original v1.2 reference — read-only):

├── Anti-DDoS.exe                # Original PyInstaller binary (v1.2)
├── Anti-DDoS.exe_extracted/     # Extracted PyInstaller contents (read-only)
├── Anti-DDoS_reconstructed.py   # Bytecode-faithful reconstruction of v1.2
├── ANALISIS_PERBANDINGAN.md     # v1.2 vs v2.x comparison analysis
├── SECURITY_AUDIT_REPORT.html   # Security audit of the original code
└── SIDE_BY_SIDE_COMPARISON.html # Side-by-side code comparison

📊 Optional Modules

Visualization (Anti_DDoS_visualization.py)

Real-time charts using matplotlib:

  • Top Attacking IPs — Horizontal bar chart
  • Country Distribution — Pie/donut chart
  • Port Analysis — Vertical bar chart
  • Attack Timeline — Line chart with trend
# Requires matplotlib
pip install matplotlib

Whitelist Manager (Anti_DDoS_whitelist.py)

GUI for managing excluded IPs:

  • View all whitelisted IPs/CIDRs
  • Add single or bulk IPs
  • Remove selected IPs
  • Import/Export to file

PDF Report Generator (Anti_DDoS_report.py)

Professional PDF reports with:

  • Executive summary with key metrics
  • Top attackers table
  • Country and port distribution charts
  • Attack log
  • Recommendations
# Requires reportlab
pip install reportlab

🤝 Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Setup

# Clone your fork
git clone https://github.com/yourusername/Anti-DDoS.git
cd Anti-DDoS

# Install all dependencies
pip install -r requirements.txt

# Run the application
python Anti-DDoS_enhanced.py

📜 License

This project is licensed under the MIT License - see the LICENSE file for details.


🙏 Acknowledgments

  • Scapy — Packet manipulation library
  • GeoIP2 — MaxMind GeoIP2 Python API
  • ttkbootstrap — Themed tkinter widgets
  • matplotlib — Visualization library
  • reportlab — PDF generation library
  • OllyDbg x RaGEZONE — Original v1.2 implementation

Made with ❤️ by Your Name

About

Anti‑DDoS System adalah aplikasi berbasis Windows yang dirancang untuk mendeteksi dan mitigasi serangan DDoS secara real‑time. Menggunakan Scapy untuk penyadaran paket, GeoIP2 untuk pencarian lokasi geografis penyerang, Tkinter dengan ttkbootstrap untuk antarmuka grafis modern, dan Windows Firewall (netsh) untuk blokir IP secara otomatis.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages