// π‘οΈ DDoS Protection Edge - Powered by DeepSeek
// Free for All - Protecting Your Infrastructure
// Configuration
const CONFIG = {
// Rate limiting
rateLimit: {
window: 60, // seconds
maxRequests: 100, // per window
blockDuration: 3600 // seconds
},
// Attack detection
detection: {
synFloodThreshold: 50,
httpFloodThreshold: 200,
suspiciousUAThreshold: 10
},
// Whitelist
whitelist: {
ips: [],
paths: ['/api/health', '/metrics'],
ua: []
},
// Response codes
blockStatusCode: 403,
rateLimitStatusCode: 429,
// Dashboard endpoint
dashboardEndpoint: '/dashboard',
// Security headers
securityHeaders: {
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block',
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Permissions-Policy': 'geolocation=(), microphone=(), camera=()'
}
};
// In-memory stores (use KV in production for persistence)
const rateLimitStore = new Map();
const blockedIPs = new Map();
const attackSignatures = new Map();
const trafficStats = new Map();
// Suspicious User-Agent patterns
const suspiciousPatterns = [
/scanner/i,
/bot/i,
/crawler/i,
/spider/i,
/attack/i,
/ddos/i,
/flood/i,
/hack/i,
/sqlmap/i,
/nikto/i,
/nessus/i,
/burp/i,
/wpscan/i,
/acunetix/i
];
// Attack signatures database
const attackSignaturesDB = {
synFlood: {
pattern: /SYN/i,
threshold: CONFIG.detection.synFloodThreshold
},
httpFlood: {
pattern: /GET|POST/i,
threshold: CONFIG.detection.httpFloodThreshold
},
slowloris: {
pattern: /keep-alive|connection: keep-alive/i,
threshold: 20
},
wordpress: {
pattern: /wp-admin|wp-login|xmlrpc/i,
threshold: 30
}
};
// Main request handler
addEventListener('fetch', event => {
event.respondWith(handleRequest(event));
});
async function handleRequest(event) {
const request = event.request;
const url = new URL(request.url);
const clientIP = request.headers.get('CF-Connecting-IP') ||
request.headers.get('X-Real-IP') ||
request.headers.get('X-Forwarded-For')?.split(',')[0] ||
'unknown';
const userAgent = request.headers.get('User-Agent') || '';
const method = request.method;
const path = url.pathname;
// Special routes
if (path === '/install') {
return handleInstallScript(request);
}
if (path === '/dashboard' || path === '/') {
return handleDashboard(request, clientIP);
}
if (path === '/api/stats') {
return handleAPIStats(request, clientIP);
}
if (path === '/api/block') {
return handleBlockRequest(request, clientIP);
}
if (path === '/api/unblock') {
return handleUnblockRequest(request, clientIP);
}
if (path === '/api/report') {
return handleReportRequest(request, clientIP);
}
if (path === '/api/vps-install') {
return handleVPSInstallScript(request);
}
// Protection layers
let response = null;
// Layer 1: Check if IP is blocked
response = checkBlockedIP(clientIP);
if (response) return response;
// Layer 2: Check whitelist
if (isWhitelisted(clientIP, path, userAgent)) {
return fetch(request);
}
// Layer 3: Rate limiting
response = checkRateLimit(clientIP);
if (response) return response;
// Layer 4: Attack detection
response = await detectAttack(request, clientIP, userAgent);
if (response) return response;
// Layer 5: Bot detection
response = detectBot(userAgent);
if (response) return response;
// Update traffic stats
updateTrafficStats(clientIP, request);
// Forward request to origin
try {
const originResponse = await fetch(request);
// Add security headers
const newHeaders = new Headers(originResponse.headers);
Object.entries(CONFIG.securityHeaders).forEach(([key, value]) => {
newHeaders.set(key, value);
});
// Add DDoS protection headers
newHeaders.set('X-Protected-By', 'DeepSeek DDoS Shield');
newHeaders.set('X-Protection-Status', 'Active');
return new Response(originResponse.body, {
status: originResponse.status,
statusText: originResponse.statusText,
headers: newHeaders
});
} catch (error) {
// Origin might be under attack
blockIP(clientIP, 'Origin unreachable - possible DDoS', 1800);
return new Response('Service temporarily unavailable - DDoS mitigation active', {
status: 503,
headers: {
'Content-Type': 'text/plain',
'Retry-After': '120',
'X-Protected-By': 'DeepSeek DDoS Shield'
}
});
}
}
function checkBlockedIP(ip) {
if (blockedIPs.has(ip)) {
const blockInfo = blockedIPs.get(ip);
if (Date.now() < blockInfo.expires) {
return new Response(`Access Denied - DDoS Protection\nReason: ${blockInfo.reason}\nExpires: ${new Date(blockInfo.expires).toISOString()}`, {
status: CONFIG.blockStatusCode,
headers: {
'Content-Type': 'text/plain',
'X-Blocked-By': 'DeepSeek DDoS Shield',
'X-Block-Reason': blockInfo.reason,
'X-Block-Expires': new Date(blockInfo.expires).toISOString()
}
});
} else {
blockedIPs.delete(ip);
}
}
return null;
}
function checkRateLimit(ip) {
const now = Date.now();
const windowMs = CONFIG.rateLimit.window * 1000;
if (!rateLimitStore.has(ip)) {
rateLimitStore.set(ip, {
count: 1,
windowStart: now,
firstRequest: now
});
return null;
}
const record = rateLimitStore.get(ip);
if (now - record.windowStart > windowMs) {
// Reset window
record.count = 1;
record.windowStart = now;
return null;
}
record.count++;
// Check if attack pattern (rapid requests)
const requestRate = record.count / ((now - record.firstRequest) / 1000);
if (requestRate > 50) {
blockIP(ip, `High request rate: ${requestRate.toFixed(2)} req/sec`, 3600);
return new Response('Rate limit exceeded - IP blocked', {
status: CONFIG.rateLimitStatusCode,
headers: {
'X-RateLimit-Limit': CONFIG.rateLimit.maxRequests,
'X-RateLimit-Remaining': '0',
'Retry-After': CONFIG.rateLimit.blockDuration
}
});
}
if (record.count > CONFIG.rateLimit.maxRequests) {
const retryAfter = Math.ceil((record.windowStart + windowMs - now) / 1000);
return new Response('Rate limit exceeded', {
status: CONFIG.rateLimitStatusCode,
headers: {
'X-RateLimit-Limit': CONFIG.rateLimit.maxRequests,
'X-RateLimit-Remaining': '0',
'Retry-After': retryAfter,
'X-RateLimit-Reset': Math.ceil((record.windowStart + windowMs) / 1000)
}
});
}
return null;
}
async function detectAttack(request, ip, ua) {
const url = new URL(request.url);
const method = request.method;
const headers = request.headers;
// Check for SYN flood patterns
if (method === 'CONNECT' || !headers.has('User-Agent')) {
const key = `syn_${ip}`;
const count = (attackSignatures.get(key) || 0) + 1;
attackSignatures.set(key, count);
if (count > CONFIG.detection.synFloodThreshold) {
blockIP(ip, 'SYN flood attack detected', 7200);
return new Response('Attack detected - Access denied', { status: 403 });
}
}
// Check for HTTP flood
const httpKey = `http_${ip}`;
const httpCount = (attackSignatures.get(httpKey) || 0) + 1;
attackSignatures.set(httpKey, httpCount);
if (httpCount > CONFIG.detection.httpFloodThreshold) {
blockIP(ip, 'HTTP flood attack detected', 3600);
return new Response('HTTP flood detected - Access denied', { status: 403 });
}
// Check for suspicious User-Agent
if (isSuspiciousUA(ua)) {
const uaKey = `ua_${ip}`;
const uaCount = (attackSignatures.get(uaKey) || 0) + 1;
attackSignatures.set(uaKey, uaCount);
if (uaCount > CONFIG.detection.suspiciousUAThreshold) {
blockIP(ip, 'Suspicious User-Agent pattern', 3600);
return new Response('Suspicious activity detected', { status: 403 });
}
}
// Check for WordPress attacks
if (url.pathname.includes('wp-admin') || url.pathname.includes('wp-login')) {
const wpKey = `wp_${ip}`;
const wpCount = (attackSignatures.get(wpKey) || 0) + 1;
attackSignatures.set(wpKey, wpCount);
if (wpCount > 30) {
blockIP(ip, 'WordPress brute force attack', 3600);
return new Response('Attack detected - Access denied', { status: 403 });
}
}
// Check for XML-RPC attacks
if (url.pathname.includes('xmlrpc.php')) {
blockIP(ip, 'XML-RPC attack attempt', 7200);
return new Response('Access denied', { status: 403 });
}
return null;
}
function detectBot(ua) {
if (!ua || ua === '') {
return new Response('Access denied - No User-Agent', { status: 403 });
}
// Check for known bad bots
const badBots = [
'AhrefsBot',
'MJ12bot',
'SemrushBot',
'DotBot',
'PetalBot',
'BLEXBot',
'SeznamBot'
];
for (const bot of badBots) {
if (ua.includes(bot)) {
return new Response('Bot access denied', { status: 403 });
}
}
return null;
}
function isSuspiciousUA(ua) {
return suspiciousPatterns.some(pattern => pattern.test(ua));
}
function isWhitelisted(ip, path, ua) {
// Check IP whitelist
if (CONFIG.whitelist.ips.includes(ip)) return true;
// Check path whitelist
if (CONFIG.whitelist.paths.some(p => path.startsWith(p))) return true;
// Check UA whitelist
if (CONFIG.whitelist.ua.some(u => ua.includes(u))) return true;
// Always whitelist Cloudflare IPs
if (ip === '127.0.0.1' || ip.startsWith('10.') || ip.startsWith('172.16.') || ip.startsWith('192.168.')) {
return true;
}
return false;
}
function blockIP(ip, reason, duration) {
blockedIPs.set(ip, {
reason: reason,
expires: Date.now() + (duration * 1000),
timestamp: Date.now()
});
console.log(`π‘οΈ Blocked IP: ${ip} - ${reason}`);
}
function updateTrafficStats(ip, request) {
const now = Date.now();
const hour = Math.floor(now / 3600000);
const key = `stats_${hour}`;
const stats = trafficStats.get(key) || {
totalRequests: 0,
uniqueIPs: new Set(),
blockedRequests: 0,
bandwidth: 0
};
stats.totalRequests++;
stats.uniqueIPs.add(ip);
// Estimate bandwidth
const contentLength = parseInt(request.headers.get('Content-Length') || '0');
stats.bandwidth += contentLength;
trafficStats.set(key, stats);
// Cleanup old stats (keep last 24 hours)
const oldKey = `stats_${hour - 24}`;
trafficStats.delete(oldKey);
}
// Dashboard HTML
async function handleDashboard(request, ip) {
const html = `
DeepSeek DDoS Protection - Live Dashboard
Traffic Analysis
Recently Blocked IPs
| IP Address |
Reason |
Time |
Action |
π Deploy DDoS Protection on Your VPS
Protect your Pterodactyl nodes and high-end VPS with one command:
bash <(curl -s ${window.location.origin}/api/vps-install)
β
Includes: Live dashboard on port 3000 β’ Auto-blocking β’ Traffic analysis β’ Pterodactyl integration
`;
return new Response(html, {
headers: { 'Content-Type': 'text/html' }
});
}
function handleAPIStats(request, ip) {
const now = Date.now();
const hour = Math.floor(now / 3600000);
const currentStats = trafficStats.get(`stats_${hour}`) || {
totalRequests: 0,
uniqueIPs: new Set(),
blockedRequests: 0
};
const blockedList = Array.from(blockedIPs.entries())
.filter(([_, info]) => info.expires > now)
.map(([ip, info]) => ({
ip,
reason: info.reason,
timestamp: info.timestamp,
expires: info.expires
}))
.slice(0, 50);
const stats = {
totalRequests: currentStats.totalRequests,
blockedCount: blockedIPs.size,
activeIPs: currentStats.uniqueIPs?.size || 0,
blockedRequests: currentStats.blockedRequests || 0,
legitimateRequests: currentStats.totalRequests - (currentStats.blockedRequests || 0),
blockedIPs: blockedList,
timestamp: now
};
return new Response(JSON.stringify(stats), {
headers: { 'Content-Type': 'application/json' }
});
}
function handleBlockRequest(request, ip) {
return request.json().then(data => {
if (data.ip) {
blockIP(data.ip, data.reason || 'Manual block', data.duration || 3600);
return new Response(JSON.stringify({ success: true }), {
headers: { 'Content-Type': 'application/json' }
});
}
return new Response(JSON.stringify({ error: 'IP required' }), { status: 400 });
});
}
function handleUnblockRequest(request, ip) {
return request.json().then(data => {
if (data.ip) {
blockedIPs.delete(data.ip);
return new Response(JSON.stringify({ success: true }), {
headers: { 'Content-Type': 'application/json' }
});
}
return new Response(JSON.stringify({ error: 'IP required' }), { status: 400 });
});
}
function handleReportRequest(request, ip) {
return request.json().then(data => {
console.log('Attack report:', data);
return new Response(JSON.stringify({ received: true }), {
headers: { 'Content-Type': 'application/json' }
});
});
}
function handleInstallScript(request) {
const script = `
#!/bin/bash
# DeepSeek DDoS Protection - One-Command Installer
# Free for Everyone
curl -s ${new URL(request.url).origin}/api/vps-install | bash
`;
return new Response(script, {
headers: { 'Content-Type': 'text/plain' }
});
}
function handleVPSInstallScript(request) {
const vpsScript = generateVPSInstallScript(request.url);
return new Response(vpsScript, {
headers: {
'Content-Type': 'text/plain',
'Content-Disposition': 'attachment; filename="ddos-protector-install.sh"'
}
});
}
function generateVPSInstallScript(workerUrl) {
const baseUrl = new URL(workerUrl).origin;
return `#!/bin/bash
###############################################################################
# π‘οΈ DeepSeek DDoS Protection System - VPS Installer
# Made with β€οΈ by DeepSeek - Free for Everyone
# Version: 2.0.0
###############################################################################
set -e
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m'
# Configuration
INSTALL_DIR="/opt/ddos-protector"
DASHBOARD_PORT="3000"
WORKER_URL="${baseUrl}"
VERSION="2.0.0"
# Banner
echo -e "${CYAN}"
cat << "EOF"
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
βΒ Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β β
βΒ Β βββββββ ββββββ βββ βββββββββββββββββββ β
βΒ ββββββββ βββββββββββ βββββββββββββββββββ β
βΒ βββ βββββββββββ βββββββββ ββββββ β
βΒ βββ ββββββββββββ ββββββββββ ββββββ β
βΒ ββββββββ βββ βββ βββββββ ββββββββββββββββ β
β βββββββ βββ βββ βββββ ββββββββββββββββ β
βΒ Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β Β β
βΒ Β Β Β Β Β Β DDoS Protection System v${VERSION}Β Β Β Β Β Β Β Β β
βΒ Β Β Β Β Β Β Β Β Free for EveryoneΒ Β Β Β Β Β Β Β Β Β Β Β Β Β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
EOF
echo -e "${NC}"
# Check root
if [ "\$EUID" -ne 0 ]; then
echo -e "${RED}β Please run as root${NC}"
exit 1
fi
echo -e "${YELLOW}π¦ Installing DeepSeek DDoS Protection...${NC}"
# Update system
apt-get update -qq
# Install dependencies
echo -e "${BLUE}π₯ Installing dependencies...${NC}"
apt-get install -y -qq \
python3 python3-pip python3-venv \
nginx redis-server sqlite3 \
iptables-persistent fail2ban \
tcpdump net-tools curl wget \
git htop nethogs iftop \
ufw unattended-upgrades
# Install Python packages
pip3 install --quiet \
flask==2.3.3 \
flask-socketio==5.3.4 \
flask-cors==4.0.0 \
python-socketio==5.9.0 \
eventlet==0.33.3 \
numpy==1.24.3 \
psutil==5.9.5 \
redis==5.0.0 \
requests==2.31.0
# Create directories
mkdir -p ${INSTALL_DIR}/{server,templates,logs,data}
mkdir -p /var/log/ddos-protector
mkdir -p /etc/ddos-protector
# Create main protection script
cat > ${INSTALL_DIR}/server/protector.py << 'PYTHON_EOF'
#!/usr/bin/env python3
"""DeepSeek DDoS Protection - VPS Layer"""
import os
import sys
import time
import json
import threading
import subprocess
from datetime import datetime
from collections import defaultdict, deque
import psutil
import requests
from redis import Redis
from flask import Flask, jsonify, render_template
from flask_socketio import SocketIO
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
socketio = SocketIO(app, cors_allowed_origins="*")
redis_client = Redis(host='localhost', port=6379, decode_responses=True)
WORKER_URL = "${WORKER_URL}"
class DDoSProtector:
def __init__(self):
self.running = True
self.stats = defaultdict(lambda: {'packets': deque(maxlen=100), 'blocked': False})
self.thresholds = {
'pps': 10000,
'connections': 100,
'bandwidth_mbps': 100
}
def analyze(self):
while self.running:
try:
net_io = psutil.net_io_counters()
connections = len(psutil.net_connections())
pps = net_io.packets_recv
bandwidth = (net_io.bytes_recv * 8) / 1000000
if pps > self.thresholds['pps'] or bandwidth > self.thresholds['bandwidth_mbps']:
self.report_attack(pps, bandwidth)
self.enable_protection()
redis_client.hset('stats', mapping={
'pps': pps,
'bandwidth': bandwidth,
'connections': connections,
'timestamp': time.time()
})
socketio.emit('update', {
'pps': pps,
'bandwidth': bandwidth,
'connections': connections
})
time.sleep(1)
except Exception as e:
print(f"Error: {e}")
time.sleep(5)
def report_attack(self, pps, bandwidth):
try:
requests.post(f"{WORKER_URL}/api/report", json={
'attack_detected': True,
'pps': pps,
'bandwidth': bandwidth,
'server': os.uname().nodename
}, timeout=3)
except:
pass
def enable_protection(self):
os.system("iptables -A INPUT -m conntrack --ctstate NEW -m limit --limit 100/minute -j ACCEPT")
os.system("iptables -A INPUT -m conntrack --ctstate NEW -j DROP")
def block_ip(self, ip, reason):
os.system(f"iptables -A INPUT -s {ip} -j DROP")
redis_client.sadd('blocked_ips', ip)
redis_client.setex(f"block:{ip}", 3600, reason)
try:
requests.post(f"{WORKER_URL}/api/block", json={'ip': ip, 'reason': reason}, timeout=3)
except:
pass
def run(self):
threading.Thread(target=self.analyze, daemon=True).start()
protector = DDoSProtector()
@app.route('/')
def dashboard():
return render_template('dashboard.html')
@app.route('/api/stats')
def api_stats():
stats = redis_client.hgetall('stats')
blocked = list(redis_client.smembers('blocked_ips'))
return jsonify({
'stats': stats,
'blocked': blocked,
'blocked_count': len(blocked),
'system': {
'cpu': psutil.cpu_percent(),
'memory': psutil.virtual_memory().percent
}
})
@app.route('/api/block', methods=['POST'])
def block():
data = request.json
protector.block_ip(data['ip'], data.get('reason', 'Manual block'))
return jsonify({'status': 'blocked'})
@socketio.on('connect')
def handle_connect():
print('Client connected')
if __name__ == '__main__':
protector.run()
socketio.run(app, host='0.0.0.0', port=${DASHBOARD_PORT}, allow_unsafe_werkzeug=True)
PYTHON_EOF
# Create dashboard HTML
cat > ${INSTALL_DIR}/templates/dashboard.html << 'HTML_EOF'
Cave DDoS Protection - VPS Dashboard
Traffic Monitor
Made with β€οΈ by Shine Akhanda β’ Free DDoS Protection
HTML_EOF
# Create systemd service
cat > /etc/systemd/system/ddos-protector.service << EOF
[Unit]
Description=Cave DDoS Protection
After=network.target redis-server.service
[Service]
Type=simple
User=root
WorkingDirectory=${INSTALL_DIR}/server
ExecStart=/usr/bin/python3 ${INSTALL_DIR}/server/protector.py
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
EOF
# Configure firewall
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw allow ${DASHBOARD_PORT}/tcp
echo "y" | ufw enable
# Start services
systemctl daemon-reload
systemctl enable ddos-protector redis-server
systemctl start redis-server
systemctl start ddos-protector
# Get server IP
SERVER_IP=$(curl -s ifconfig.me)
echo ""
echo -e "${GREEN}ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ${NC}"
echo -e "${GREEN}β β${NC}"
echo -e "${GREEN}β β
Cave DDoS Protection Installed Successfully! β${NC}"
echo -e "${GREEN}β β${NC}"
echo -e "${GREEN}ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ${NC}"
echo ""
echo -e "${CYAN}π VPS Dashboard:${NC} http://${SERVER_IP}:${DASHBOARD_PORT}"
echo -e "${CYAN}π Edge Dashboard:${NC} ${WORKER_URL}/dashboard"
echo ""
echo -e "${YELLOW}π Commands:${NC}"
echo " β’ Status: systemctl status ddos-protector"
echo " β’ Logs: journalctl -u ddos-protector -f"
echo " β’ Restart: systemctl restart ddos-protector"
echo ""
echo -e "${PURPLE}π‘οΈ Protection Layers:${NC}"
echo " β
Cloudflare Edge (Free Tier)"
echo " β
VPS-Level Protection"
echo " β
Auto-Blocking Enabled"
echo " β
Live Monitoring Active"
echo ""
echo -e "${GREEN}Made with β€οΈ by Shine Akhanda - Free for Everyone${NC}"
`;